Stage 1 Part 3 L1 JEV recommender, Part 1/2 cache revisions, S2_00-S2_20 alignment #6

Merged
jhogyu merged 7 commits from stage2/s2-20-index-coverage-build into main 2026-11-05 07:01:19 +00:00
2082 changed files with 848799 additions and 831 deletions
@@ -0,0 +1,93 @@
---
name: open-law-kr-download
description: >-
국가법령정보센터(open.law.go.kr / www.law.go.kr/DRF)에서 현행 법령(법률·대통령령·총리령·부령·대법원규칙),
특정 조문·범위 조문(가지조문 자동 포함), 행정규칙(고시·예규·훈령), 대법원·하급심 판례·결정례, 별표·서식을
공식 JSON 형식으로 검색·다운로드·검증하는 전용 스킬. 사용자가 법령·규칙·고시·예규·판례 원문을 JSON으로
다운로드하거나 대조하라고 요청할 때 사용한다.
---
# 국가법령정보센터 (open.law.go.kr) 원문 JSON 다운로드 스킬
## Overview
국가법령정보센터(`https://www.law.go.kr/DRF/lawSearch.do`, `lawService.do`) Open API를 통해 대한민국 현행 법령·시행령·시행규칙·대법원규칙(`target=law`), 행정규칙·고시·예규(`target=admrul`), 판례·결정례(`target=prec`), 별표·서식(`target=licbyl`) 원문을 공식 JSON 스키마 그대로 다운로드하고 무결성을 검증한다.
- **기본 API 인증키(`OC`)**: `jhogyu` (`OPEN_LAW_OC` 환경변수 또는 `--oc` 인자로 재정의 가능; 공용 `OC=test`는 차단됨)
- **핵심 자동화 기능**:
1. 법령명/행정규칙명 정확 일치(공백·괄호 부연 설명 정규화) 및 현행(`현행연혁구분 == "현행"`·최신 `시행일자`) 기준 최신 일련번호(`MST` / `ID`) 자동 조회
2. 단일 조문(`§186`, `§388 2호`, `§13①2나·3호`), 가지조문(`§109의2`, `§2의4`), 복수 조문(`§356·§357·§358·§360`), 범위 조문(`§333~§341`, `§100~§103`, `§60~§66`) 표기 자동 파싱
3. 범위 조문(`A~B`) 조회 시 해당 법령의 전체 조문 목차를 먼저 스캔하여 범위 내 유효한 **가지조문(`제N조의M`, 삭제 조문 제외)**을 누락 없이 자동 포함
4. 복수 조문 조회 시 개별 `JO=NNNNMM`(6자리: 조번호 4자리 + 가지번호 2자리) 호출 결과를 `open.law.go.kr` 표준 스키마(`{"법령": {"법령키": ..., "기본정보": ..., "조문": {"조문단위": [...]}}}`)로 병합 및 `조문단위` 존재 여부 검증
## Dependencies
- Python 3 표준 라이브러리(`urllib`, `json`, `argparse`, `fcntl`, `re`, `pathlib`)만 사용하므로 외부 패키지 설치가 필요 없다.
## Quick Start
스크립트는 본 `SKILL.md`와 동일한 스킬 폴더 하위의 `./scripts/open_law_cli.py`에 위치한다(전역 설치 경로: `~/.codex/skills/open-law-kr-download/scripts/open_law_cli.py` 또는 워크스페이스 `.agents/skills/open-law-kr-download/scripts/open_law_cli.py`).
### 1. 단일 법령 조문·범위 또는 전문 다운로드 (`fetch`)
```bash
SCRIPT_PATH="${SKILL_DIR:-$HOME/.codex/skills/open-law-kr-download}/scripts/open_law_cli.py"
# 특정 조문 또는 복수·범위 조문 다운로드 (가지조문 자동 포함)
python3 "$SCRIPT_PATH" fetch \
--target law \
--name "민사소송법" \
--articles "§333~§341" \
--output "/path/to/민사소송법_제333조_제341조.json"
# 법령 현행 전문 다운로드 (--articles 생략 또는 "전문")
python3 "$SCRIPT_PATH" fetch \
--target law \
--name "부동산등기법" \
--output "/path/to/부동산등기법_현행.json"
# 행정규칙(고시·예규·훈령) 전문 다운로드 (target=admrul)
python3 "$SCRIPT_PATH" fetch \
--target admrul \
--name "감정평가 실무기준" \
--output "/path/to/감정평가_실무기준_전문.json"
```
### 2. 리스트 일괄 다운로드 (`batch`)
사용자가 제시한 마크다운 불릿 리스트(`- 법령명 §조문` 형식)나 JSON 매니페스트 파일을 입력받아 지정 폴더에 일괄 저장한다.
```bash
SCRIPT_PATH="${SKILL_DIR:-$HOME/.codex/skills/open-law-kr-download}/scripts/open_law_cli.py"
cat << 'EOF' > /tmp/law_list.txt
- 지방세기본법 §2
- 지방세법시행령 §109의2
- 상속세 및 증여세법 §60~§66
- `감정평가 실무기준(국토교통부 고시)` 전문
EOF
python3 "$SCRIPT_PATH" batch \
--input /tmp/law_list.txt \
--out-dir "/path/to/output_dir"
```
## Utility Scripts
스크립트 위치: [open_law_cli.py](./scripts/open_law_cli.py)
| 서브커맨드 | 주요 인자 | 설명 |
|---|---|---|
| `search` | `--target {law,admrul,prec,licbyl}` `--query <검색어>` `--limit <N>` `--output <파일>` | 검색 결과를 JSON 파일로 저장 |
| `fetch` | `--target {law,admrul,prec,licbyl}` `--name <법령/규칙명>` `[--id <MST/ID>]` `[--articles <조문표기>]` `--output <파일>` | 단건 법령(전문/조문/범위)·고시·판례·별표 원문 JSON 다운로드 및 검증 |
| `batch` | `--input <리스트파일.txt\|.json>` `--out-dir <저장폴더>` `[--report <요약.json>]` | 항목 리스트를 파싱하여 항목별 표준 파일명으로 일괄 다운로드 |
## Rate Limiting
- [open_law_cli.py](./scripts/open_law_cli.py) 내부에서 프로세스 간 파일 락(`/tmp/open_law_kr_rate_limit.lock`)과 `time.monotonic()`을 사용하여 요청 간 최소 `0.25초` 간격을 강제하며, 일시적 네트워크/5xx 오류 시 지수 백오프(최대 3회)로 자동 재시도한다.
## Common Mistakes
1. **`OC=test` 사용 금지**: 국가법령정보센터에서 공용 `OC=test`는 `"사용자 정보 검증에 실패하였습니다"` 오류로 거부된다. 반드시 기본 설정된 `OC=jhogyu`(또는 유효한 발급 키)를 사용한다.
2. **법령(`target=law`)과 행정규칙(`target=admrul`) 혼동**: 법률·대통령령·부령·대법원규칙은 `target=law`(`MST` 사용)이고, 각 부처 고시(예: `감정평가 실무기준`)·대법원 재판예규(예: `재민 91-1`, `재일 87-4`)·훈령은 `target=admrul`(`ID` 사용)이다.
3. **범위 조문(`§A~§B`)에서 가지조문 누락**: 예컨대 `민사소송법 §333~§341`에는 `제335조의2`, `제339조의2`, `제339조의3`이 포함되어 있다. 단순 정수 루프(`333..341`)로만 호출하면 가지조문이 누락되므로 반드시 본 스크립트의 범위 해석기(`resolve_jo_codes_for_law`)를 사용한다.
@@ -0,0 +1,4 @@
interface:
display_name: "국가법령정보센터(open.law.go.kr) 원문 다운로드"
short_description: "현행 법령·규칙·고시·예규·판례 원문을 공식 JSON으로 검색·다운로드·검증"
default_prompt: "국가법령정보센터(open.law.go.kr) Open API(OC=jhogyu)를 사용하여 요청된 법령·규칙·고시·판례의 현행 원문(특정 조문·가지조문·범위 조문 또는 전문)을 공식 JSON 형식으로 다운로드하고 검증하라."
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
set -euo pipefail
SKILL_NAME="open-law-kr-download"
SRC_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TARGETS=(
"$HOME/.codex/skills/$SKILL_NAME"
"$HOME/.agents/skills/$SKILL_NAME"
"$HOME/.gemini/config/skills/$SKILL_NAME"
"$HOME/.claude/skills/$SKILL_NAME"
)
echo "Installing '$SKILL_NAME' from: $SRC_DIR"
for dest in "${TARGETS[@]}"; do
mkdir -p "$dest/scripts" "$dest/agents"
cp "$SRC_DIR/SKILL.md" "$dest/SKILL.md"
cp "$SRC_DIR/scripts/open_law_cli.py" "$dest/scripts/open_law_cli.py"
if [[ -f "$SRC_DIR/agents/openai.yaml" ]]; then
cp "$SRC_DIR/agents/openai.yaml" "$dest/agents/openai.yaml"
fi
chmod +x "$dest/scripts/open_law_cli.py"
echo " [OK] $dest"
done
echo "Done! '$SKILL_NAME' is now installed globally for Codex, Antigravity, and Claude Code."
+556
View File
@@ -0,0 +1,556 @@
#!/usr/bin/env python3
"""National Law Information Center (open.law.go.kr) DRF JSON Downloader CLI.
Supports:
- target=law : Statutes, Presidential Decrees, Ministerial Ordinances, Supreme Court Rules
(full law or article/range selection with automatic branch-article discovery)
- target=admrul : Administrative Rules (Notices/고시, Directives/훈령, Established Rules/예규)
- target=prec : Supreme Court & Lower Court Precedents / Decisions (판례·결정례)
- target=licbyl : Statute Attached Tables & Forms (별표·서식)
Default OC authentication key: "jhogyu" (override via --oc or OPEN_LAW_OC env var).
"""
from __future__ import annotations
import argparse
import fcntl
import json
import os
import re
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any
DEFAULT_OC = os.environ.get("OPEN_LAW_OC", "jhogyu")
BASE_SEARCH_URL = "https://www.law.go.kr/DRF/lawSearch.do"
BASE_SERVICE_URL = "https://www.law.go.kr/DRF/lawService.do"
RATE_LIMIT_LOCK = Path(tempfile.gettempdir()) / "open_law_kr_rate_limit.lock"
MIN_INTERVAL_SEC = 0.25
class OpenLawError(RuntimeError):
"""Raised when open.law.go.kr returns an error or invalid payload."""
def _rate_limited_get(url: str, timeout: int = 25, max_retries: int = 3) -> bytes:
"""Perform a cross-process rate-limited HTTP GET with retry on transient errors."""
RATE_LIMIT_LOCK.touch(exist_ok=True)
with RATE_LIMIT_LOCK.open("r+", encoding="utf-8") as lock_file:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
try:
lock_file.seek(0)
content = lock_file.read().strip()
last_ts = float(content) if content else 0.0
elapsed = time.monotonic() - last_ts
if 0.0 <= elapsed < MIN_INTERVAL_SEC:
time.sleep(MIN_INTERVAL_SEC - elapsed)
now_ts = time.monotonic()
lock_file.seek(0)
lock_file.truncate()
lock_file.write(f"{now_ts:.6f}")
lock_file.flush()
finally:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
last_err: Exception | None = None
for attempt in range(1, max_retries + 1):
req = urllib.request.Request(
url,
headers={
"User-Agent": "Mozilla/5.0 (compatible; OpenLawKrSkill/1.0)",
"Accept": "application/json, text/plain, */*",
},
)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
raw = resp.read()
text_preview = raw[:500].decode("utf-8", errors="ignore")
if "사용자 정보 검증에 실패하였습니다" in text_preview:
raise OpenLawError(
f"API key (OC) authentication failed on open.law.go.kr for URL: {url}"
)
return raw
except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError) as exc:
last_err = exc
if isinstance(exc, urllib.error.HTTPError) and 400 <= exc.code < 500 and exc.code != 429:
body = exc.read().decode("utf-8", errors="ignore")[:400]
raise OpenLawError(f"HTTP {exc.code} for {url}: {body}") from exc
wait_sec = 0.8 * (2 ** (attempt - 1))
print(
f"[retry {attempt}/{max_retries}] {exc} -> waiting {wait_sec:.1f}s ({url})",
file=sys.stderr,
)
time.sleep(wait_sec)
raise OpenLawError(f"Failed to fetch {url} after {max_retries} attempts: {last_err}")
def fetch_json(url: str) -> dict[str, Any]:
raw = _rate_limited_get(url)
text = raw.decode("utf-8", errors="replace").strip()
try:
data = json.loads(text)
except json.JSONDecodeError as exc:
raise OpenLawError(
f"Non-JSON response from {url} (first 300 chars): {text[:300]}"
) from exc
if not isinstance(data, dict):
raise OpenLawError(f"Unexpected JSON root type {type(data).__name__} from {url}")
return data
def normalize_law_name(name: str) -> str:
"""Strip spaces and parenthetical notes for resilient matching."""
cleaned = re.sub(r"\([^)]*\)", "", name)
return re.sub(r"\s+", "", cleaned).strip()
def format_jo_code(main_no: int, sub_no: int = 0) -> str:
"""Format article number + branch number into 6-digit JO code (NNNNMM)."""
return f"{main_no:04d}{sub_no:02d}"
def parse_article_token(token: str) -> tuple[int, int]:
"""Parse a single article token like '§109의2', '제2조의4', '§263①', '§388 2호', '§13①2나' into (main, sub)."""
m = re.search(r"(?:제\s*)?(\d+)\s*(?:조)?(?:\s*의\s*(\d+))?", token)
if not m:
raise ValueError(f"Cannot parse article number from token: {token!r}")
main_no = int(m.group(1))
sub_no = int(m.group(2)) if m.group(2) else 0
return main_no, sub_no
def parse_article_spec(spec: str) -> list[dict[str, Any]]:
"""Parse an article specification string into single or range descriptors.
Examples:
"§186" -> [{"type": "single", "main": 186, "sub": 0}]
"§356·§357·§358·§360" -> 4 singles
"§333~§341" -> [{"type": "range", "start": 333, "end": 341}]
"§3·§10·§16~§18" -> 2 singles + 1 range
"§13①2나·3호" -> [{"type": "single", "main": 13, "sub": 0}]
"""
spec = spec.strip()
if not spec or spec in {"전문", "전체", "ALL", "all"}:
return []
parts = [p.strip() for p in re.split(r"[·,]+", spec) if p.strip()]
descriptors: list[dict[str, Any]] = []
for part in parts:
# Check if part is a mere sub-item continuation like "3호" or "2호" without §/제
if re.fullmatch(r"\d+\s*(?:호|목|항)", part) and descriptors:
continue
# Check range pattern: e.g. §333~§341, 60~66, 제16조~제18조
range_match = re.search(
r"(?:§|제)?\s*(\d+)\s*(?:조)?\s*[~\-∼]\s*(?:§|제)?\s*(\d+)\s*(?:조)?",
part,
)
if range_match:
start_no = int(range_match.group(1))
end_no = int(range_match.group(2))
descriptors.append({"type": "range", "start": start_no, "end": end_no})
else:
main_no, sub_no = parse_article_token(part)
descriptors.append({"type": "single", "main": main_no, "sub": sub_no})
return descriptors
def search_law(name: str, oc: str = DEFAULT_OC) -> dict[str, Any]:
"""Find the current law entry matching `name` via lawSearch.do?target=law."""
# Strip parenthetical qualification like "(국토교통부령)" for query if needed
base_query = re.sub(r"\([^)]*\)$", "", name).strip()
q = urllib.parse.quote(base_query)
url = f"{BASE_SEARCH_URL}?OC={urllib.parse.quote(oc)}&target=law&type=JSON& display=100&query={q}".replace(
"& display=", "&display="
)
data = fetch_json(url)
laws = data.get("LawSearch", {}).get("law", [])
if isinstance(laws, dict):
laws = [laws]
if not laws:
raise OpenLawError(f"No law found for query: {base_query!r}")
norm_target = normalize_law_name(base_query)
exact = [
x
for x in laws
if normalize_law_name(str(x.get("법령명한글", ""))) == norm_target
]
candidates = exact if exact else laws
# Prefer 현행연혁구분 == "현행", then latest 시행일자
candidates.sort(
key=lambda x: (
1 if x.get("현행연혁구분") == "현행" else 0,
str(x.get("시행일자", "")),
str(x.get("공포일자", "")),
),
reverse=True,
)
return candidates[0]
def search_admrul(name: str, oc: str = DEFAULT_OC) -> dict[str, Any]:
"""Find the current administrative rule (고시·예규·훈령) matching `name`."""
base_query = re.sub(r"\((?:국토교통부|법무부|국세청|행정안전부|기획재정부|금융위원회)?\s*(?:고시|예규|훈령|지침)\)$", "", name).strip()
q = urllib.parse.quote(base_query)
url = f"{BASE_SEARCH_URL}?OC={urllib.parse.quote(oc)}&target=admrul&type=JSON&display=100&query={q}"
data = fetch_json(url)
items = data.get("AdmRulSearch", {}).get("admrul", [])
if isinstance(items, dict):
items = [items]
if not items:
raise OpenLawError(f"No administrative rule (admrul) found for query: {base_query!r}")
norm_target = normalize_law_name(base_query)
exact = [
x
for x in items
if normalize_law_name(str(x.get("행정규칙명", ""))) == norm_target
]
candidates = exact if exact else items
candidates.sort(
key=lambda x: (
1 if x.get("현행연혁구분") == "현행" else 0,
str(x.get("시행일자", "")),
str(x.get("발령일자", "")),
),
reverse=True,
)
return candidates[0]
def search_prec(query: str, oc: str = DEFAULT_OC) -> dict[str, Any]:
"""Find a precedent/decision (판례·결정례) by case number or query."""
q = urllib.parse.quote(query.strip())
url = f"{BASE_SEARCH_URL}?OC={urllib.parse.quote(oc)}&target=prec&type=JSON&display=50&query={q}"
data = fetch_json(url)
items = data.get("PrecSearch", {}).get("prec", [])
if isinstance(items, dict):
items = [items]
if not items:
raise OpenLawError(f"No precedent (prec) found for query: {query!r}")
for item in items:
if str(item.get("사건번호", "")).strip() == query.strip():
return item
return items[0]
def resolve_jo_codes_for_law(
mst: str,
descriptors: list[dict[str, Any]],
oc: str = DEFAULT_OC,
include_deleted: bool = False,
) -> list[str]:
"""Resolve descriptors (including ranges with branch articles) into 6-digit JO codes."""
has_range = any(d["type"] == "range" for d in descriptors)
full_units: list[dict[str, Any]] = []
if has_range:
full_url = f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}&target=law&type=JSON&MST={urllib.parse.quote(mst)}"
full_data = fetch_json(full_url)
raw_units = full_data.get("법령", {}).get("조문", {}).get("조문단위", [])
if isinstance(raw_units, dict):
raw_units = [raw_units]
full_units = raw_units
jo_codes: list[str] = []
seen: set[str] = set()
for desc in descriptors:
if desc["type"] == "single":
code = format_jo_code(desc["main"], desc["sub"])
if code not in seen:
seen.add(code)
jo_codes.append(code)
elif desc["type"] == "range":
start_no, end_no = desc["start"], desc["end"]
for u in full_units:
if u.get("조문여부") != "조문":
continue
jnum = int(u.get("조문번호", "0"))
if start_no <= jnum <= end_no:
content_str = str(u.get("조문내용", "")).strip()
if not include_deleted and u.get("조문제목") is None and "삭제" in content_str:
continue
sub_str = str(u.get("조문가지번호", "")).strip()
sub_no = int(sub_str) if sub_str.isdigit() else 0
code = format_jo_code(jnum, sub_no)
if code not in seen:
seen.add(code)
jo_codes.append(code)
return jo_codes
def fetch_law_json(
law_name_or_mst: str,
articles_spec: str | None = None,
oc: str = DEFAULT_OC,
include_deleted: bool = False,
) -> tuple[dict[str, Any], dict[str, Any]]:
"""Fetch full law JSON or specific article(s) JSON from open.law.go.kr.
Returns (json_payload, meta_info).
"""
if law_name_or_mst.isdigit():
mst = law_name_or_mst
law_meta = {"법령일련번호": mst}
else:
law_meta = search_law(law_name_or_mst, oc=oc)
mst = str(law_meta["법령일련번호"])
descriptors = parse_article_spec(articles_spec or "")
if not descriptors:
url = f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}&target=law&type=JSON&MST={urllib.parse.quote(mst)}"
data = fetch_json(url)
return data, {"mst": mst, "jo_codes": [], "law_meta": law_meta}
jo_codes = resolve_jo_codes_for_law(
mst=mst,
descriptors=descriptors,
oc=oc,
include_deleted=include_deleted,
)
if len(jo_codes) == 1:
url = (
f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}"
f"&target=law&type=JSON&MST={urllib.parse.quote(mst)}&JO={jo_codes[0]}"
)
data = fetch_json(url)
if "조문" not in data.get("법령", {}) or "조문단위" not in data["법령"]["조문"]:
raise OpenLawError(f"Missing 조문단위 for MST={mst} JO={jo_codes[0]}")
return data, {"mst": mst, "jo_codes": jo_codes, "law_meta": law_meta}
combined_units: list[Any] = []
base_data: dict[str, Any] | None = None
for jo in jo_codes:
url = (
f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}"
f"&target=law&type=JSON&MST={urllib.parse.quote(mst)}&JO={jo}"
)
d = fetch_json(url)
if "조문" not in d.get("법령", {}) or "조문단위" not in d["법령"]["조문"]:
raise OpenLawError(f"Missing 조문단위 for MST={mst} JO={jo}")
if base_data is None:
base_data = d
unit = d["법령"]["조문"]["조문단위"]
if isinstance(unit, list):
combined_units.extend(unit)
else:
combined_units.append(unit)
assert base_data is not None
base_data["법령"]["조문"]["조문단위"] = combined_units
return base_data, {"mst": mst, "jo_codes": jo_codes, "law_meta": law_meta}
def fetch_admrul_json(name_or_id: str, oc: str = DEFAULT_OC) -> tuple[dict[str, Any], dict[str, Any]]:
if name_or_id.isdigit():
adm_id = name_or_id
meta = {"행정규칙일련번호": adm_id}
else:
meta = search_admrul(name_or_id, oc=oc)
adm_id = str(meta["행정규칙일련번호"])
url = f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}&target=admrul&type=JSON&ID={urllib.parse.quote(adm_id)}"
data = fetch_json(url)
return data, {"id": adm_id, "admrul_meta": meta}
def fetch_prec_json(query_or_id: str, oc: str = DEFAULT_OC) -> tuple[dict[str, Any], dict[str, Any]]:
if query_or_id.isdigit():
prec_id = query_or_id
meta = {"판례일련번호": prec_id}
else:
meta = search_prec(query_or_id, oc=oc)
prec_id = str(meta["판례일련번호"])
url = f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}&target=prec&type=JSON&ID={urllib.parse.quote(prec_id)}"
data = fetch_json(url)
return data, {"id": prec_id, "prec_meta": meta}
def build_default_filename(law_name: str, articles_spec: str | None, target: str = "law") -> str:
"""Build a clean, deterministic Korean JSON filename from law name and article spec."""
clean_law = re.sub(r"\([^)]*\)$", "", law_name).strip()
clean_law = re.sub(r"\s+", "_", clean_law)
if target == "admrul" or not articles_spec or articles_spec.strip() in {"전문", "전체", "ALL", "all"}:
suffix = "전문" if (articles_spec and "전문" in articles_spec) else "현행"
return f"{clean_law}_{suffix}.json"
circle_map = {
"①": "제1항", "②": "제2항", "③": "제3항", "④": "제4항", "⑤": "제5항",
"⑥": "제6항", "⑦": "제7항", "⑧": "제8항", "⑨": "제9항", "⑩": "제10항",
}
s = articles_spec.strip()
for c, rep in circle_map.items():
s = s.replace(c, rep)
# Convert §N(의M)? to 제N조(의M)?
s = re.sub(r"§\s*(\d+)(?:의(\d+))?", lambda m: f"제{m.group(1)}조" + (f"의{m.group(2)}" if m.group(2) else ""), s)
s = re.sub(r"[·,~∼\s]+", "_", s).strip("_")
return f"{clean_law}_{s}.json"
def cmd_search(args: argparse.Namespace) -> None:
q = urllib.parse.quote(args.query)
url = f"{BASE_SEARCH_URL}?OC={urllib.parse.quote(args.oc)}&target={urllib.parse.quote(args.target)}&type=JSON&display={args.limit}&query={q}"
data = fetch_json(url)
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"Success! Search results written to: {out_path} ({out_path.stat().st_size} bytes)")
def cmd_fetch(args: argparse.Namespace) -> None:
if args.target == "law":
data, meta = fetch_law_json(
law_name_or_mst=args.name or args.id,
articles_spec=args.articles,
oc=args.oc,
include_deleted=args.include_deleted,
)
elif args.target == "admrul":
data, meta = fetch_admrul_json(args.name or args.id, oc=args.oc)
elif args.target == "prec":
data, meta = fetch_prec_json(args.name or args.id, oc=args.oc)
else:
url = (
f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(args.oc)}"
f"&target={urllib.parse.quote(args.target)}&type=JSON&ID={urllib.parse.quote(args.id or args.name)}"
)
data = fetch_json(url)
meta = {"id": args.id or args.name}
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(
f"Success! Saved {out_path} ({out_path.stat().st_size} bytes) | meta={json.dumps(meta, ensure_ascii=False)}"
)
def parse_batch_line(line: str) -> dict[str, Any] | None:
"""Parse a bullet line such as '- `감정평가 및 감정평가사에 관한 법률` §3·§6' or '- 지방세법시행령 §109의2'."""
s = line.strip()
s = re.sub(r"^[-*•]\s*", "", s).strip()
if not s:
return None
# Check if backtick-quoted law name: `법령명` 스펙
m_bt = re.match(r"^`([^`]+)`\s*(.*)$", s)
if m_bt:
raw_name, rest = m_bt.group(1).strip(), m_bt.group(2).strip()
else:
# Split before first § or '전문'
m_split = re.match(r"^(.+?)\s+(§.+|전문|전체)$", s)
if m_split:
raw_name, rest = m_split.group(1).strip(), m_split.group(2).strip()
else:
raw_name, rest = s, ""
# Common spacing normalizations for decree names (e.g. 지방세법시행령 -> 지방세법 시행령)
if raw_name.endswith("시행령") and not raw_name.endswith(" 시행령"):
raw_name = raw_name[:-3] + " 시행령"
if raw_name.endswith("시행규칙") and not raw_name.endswith(" 시행규칙"):
raw_name = raw_name[:-4] + " 시행규칙"
is_admrul = bool(re.search(r"\((?:[^)]*고시|[^)]*예규|[^)]*훈령)\)", raw_name)) or "실무기준" in raw_name
target = "admrul" if is_admrul else "law"
filename = build_default_filename(raw_name, rest, target=target)
return {
"target": target,
"name": raw_name,
"articles": rest if target == "law" else None,
"filename": filename,
}
def cmd_batch(args: argparse.Namespace) -> None:
spec_path = Path(args.input)
raw_text = spec_path.read_text(encoding="utf-8").strip()
if raw_text.startswith("[") or raw_text.startswith("{"):
parsed = json.loads(raw_text)
items = parsed["items"] if isinstance(parsed, dict) and "items" in parsed else parsed
else:
items = [x for line in raw_text.splitlines() if (x := parse_batch_line(line)) is not None]
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
summary: list[dict[str, Any]] = []
for item in items:
target = item.get("target", "law")
name = item["name"]
articles = item.get("articles")
filename = item.get("filename") or build_default_filename(name, articles, target=target)
if target == "law":
data, meta = fetch_law_json(name, articles_spec=articles, oc=args.oc)
elif target == "admrul":
data, meta = fetch_admrul_json(name, oc=args.oc)
elif target == "prec":
data, meta = fetch_prec_json(name, oc=args.oc)
else:
raise OpenLawError(f"Unsupported batch target: {target}")
dest = out_dir / filename
dest.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
entry = {
"name": name,
"articles": articles,
"target": target,
"filename": str(dest),
"bytes": dest.stat().st_size,
"meta": meta,
}
summary.append(entry)
print(f"Saved: {filename} ({dest.stat().st_size} bytes)")
if args.report:
report_path = Path(args.report)
report_path.parent.mkdir(parents=True, exist_ok=True)
report_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"Batch report written to: {report_path}")
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(description="open.law.go.kr DRF JSON Downloader CLI")
p.add_argument("--oc", default=DEFAULT_OC, help="API key (OC), defaults to OPEN_LAW_OC or 'jhogyu'")
sub = p.add_subparsers(dest="subcommand", required=True)
sp_search = sub.add_parser("search", help="Search law / admrul / prec / licbyl")
sp_search.add_argument("--target", default="law", choices=["law", "admrul", "prec", "licbyl"])
sp_search.add_argument("--query", required=True, help="Search query")
sp_search.add_argument("--limit", type=int, required=True, help="Max results to retrieve")
sp_search.add_argument("--output", required=True, help="Output JSON file path")
sp_search.set_defaults(func=cmd_search)
sp_fetch = sub.add_parser("fetch", help="Fetch a single law (full or articles), admrul, prec, or licbyl")
sp_fetch.add_argument("--target", default="law", choices=["law", "admrul", "prec", "licbyl"])
sp_fetch.add_argument("--name", help="Exact Korean name of law / admrul / case number")
sp_fetch.add_argument("--id", help="Explicit MST or ID if known")
sp_fetch.add_argument("--articles", help="Article spec for target=law (e.g. '§3·§10·§16~§18', '§109의2')")
sp_fetch.add_argument("--include-deleted", action="store_true", help="Include deleted branch articles in ranges")
sp_fetch.add_argument("--output", required=True, help="Output JSON file path")
sp_fetch.set_defaults(func=cmd_fetch)
sp_batch = sub.add_parser("batch", help="Batch download a list of items (markdown bullet list or JSON)")
sp_batch.add_argument("--input", required=True, help="Path to text/markdown list or JSON manifest")
sp_batch.add_argument("--out-dir", required=True, help="Destination directory for JSON files")
sp_batch.add_argument("--report", help="Optional path to write batch download summary JSON")
sp_batch.set_defaults(func=cmd_batch)
return p
def main() -> None:
parser = build_parser()
args = parser.parse_args()
try:
args.func(args)
except Exception as exc:
print(f"ERROR: {exc}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
@@ -0,0 +1,93 @@
---
name: open-law-kr-download
description: >-
국가법령정보센터(open.law.go.kr / www.law.go.kr/DRF)에서 현행 법령(법률·대통령령·총리령·부령·대법원규칙),
특정 조문·범위 조문(가지조문 자동 포함), 행정규칙(고시·예규·훈령), 대법원·하급심 판례·결정례, 별표·서식을
공식 JSON 형식으로 검색·다운로드·검증하는 전용 스킬. 사용자가 법령·규칙·고시·예규·판례 원문을 JSON으로
다운로드하거나 대조하라고 요청할 때 사용한다.
---
# 국가법령정보센터 (open.law.go.kr) 원문 JSON 다운로드 스킬
## Overview
국가법령정보센터(`https://www.law.go.kr/DRF/lawSearch.do`, `lawService.do`) Open API를 통해 대한민국 현행 법령·시행령·시행규칙·대법원규칙(`target=law`), 행정규칙·고시·예규(`target=admrul`), 판례·결정례(`target=prec`), 별표·서식(`target=licbyl`) 원문을 공식 JSON 스키마 그대로 다운로드하고 무결성을 검증한다.
- **기본 API 인증키(`OC`)**: `jhogyu` (`OPEN_LAW_OC` 환경변수 또는 `--oc` 인자로 재정의 가능; 공용 `OC=test`는 차단됨)
- **핵심 자동화 기능**:
1. 법령명/행정규칙명 정확 일치(공백·괄호 부연 설명 정규화) 및 현행(`현행연혁구분 == "현행"`·최신 `시행일자`) 기준 최신 일련번호(`MST` / `ID`) 자동 조회
2. 단일 조문(`§186`, `§388 2호`, `§13①2나·3호`), 가지조문(`§109의2`, `§2의4`), 복수 조문(`§356·§357·§358·§360`), 범위 조문(`§333~§341`, `§100~§103`, `§60~§66`) 표기 자동 파싱
3. 범위 조문(`A~B`) 조회 시 해당 법령의 전체 조문 목차를 먼저 스캔하여 범위 내 유효한 **가지조문(`제N조의M`, 삭제 조문 제외)**을 누락 없이 자동 포함
4. 복수 조문 조회 시 개별 `JO=NNNNMM`(6자리: 조번호 4자리 + 가지번호 2자리) 호출 결과를 `open.law.go.kr` 표준 스키마(`{"법령": {"법령키": ..., "기본정보": ..., "조문": {"조문단위": [...]}}}`)로 병합 및 `조문단위` 존재 여부 검증
## Dependencies
- Python 3 표준 라이브러리(`urllib`, `json`, `argparse`, `fcntl`, `re`, `pathlib`)만 사용하므로 외부 패키지 설치가 필요 없다.
## Quick Start
스크립트는 본 `SKILL.md`와 동일한 스킬 폴더 하위의 `./scripts/open_law_cli.py`에 위치한다(전역 설치 경로: `~/.codex/skills/open-law-kr-download/scripts/open_law_cli.py` 또는 워크스페이스 `.agents/skills/open-law-kr-download/scripts/open_law_cli.py`).
### 1. 단일 법령 조문·범위 또는 전문 다운로드 (`fetch`)
```bash
SCRIPT_PATH="${SKILL_DIR:-$HOME/.codex/skills/open-law-kr-download}/scripts/open_law_cli.py"
# 특정 조문 또는 복수·범위 조문 다운로드 (가지조문 자동 포함)
python3 "$SCRIPT_PATH" fetch \
--target law \
--name "민사소송법" \
--articles "§333~§341" \
--output "/path/to/민사소송법_제333조_제341조.json"
# 법령 현행 전문 다운로드 (--articles 생략 또는 "전문")
python3 "$SCRIPT_PATH" fetch \
--target law \
--name "부동산등기법" \
--output "/path/to/부동산등기법_현행.json"
# 행정규칙(고시·예규·훈령) 전문 다운로드 (target=admrul)
python3 "$SCRIPT_PATH" fetch \
--target admrul \
--name "감정평가 실무기준" \
--output "/path/to/감정평가_실무기준_전문.json"
```
### 2. 리스트 일괄 다운로드 (`batch`)
사용자가 제시한 마크다운 불릿 리스트(`- 법령명 §조문` 형식)나 JSON 매니페스트 파일을 입력받아 지정 폴더에 일괄 저장한다.
```bash
SCRIPT_PATH="${SKILL_DIR:-$HOME/.codex/skills/open-law-kr-download}/scripts/open_law_cli.py"
cat << 'EOF' > /tmp/law_list.txt
- 지방세기본법 §2
- 지방세법시행령 §109의2
- 상속세 및 증여세법 §60~§66
- `감정평가 실무기준(국토교통부 고시)` 전문
EOF
python3 "$SCRIPT_PATH" batch \
--input /tmp/law_list.txt \
--out-dir "/path/to/output_dir"
```
## Utility Scripts
스크립트 위치: [open_law_cli.py](./scripts/open_law_cli.py)
| 서브커맨드 | 주요 인자 | 설명 |
|---|---|---|
| `search` | `--target {law,admrul,prec,licbyl}` `--query <검색어>` `--limit <N>` `--output <파일>` | 검색 결과를 JSON 파일로 저장 |
| `fetch` | `--target {law,admrul,prec,licbyl}` `--name <법령/규칙명>` `[--id <MST/ID>]` `[--articles <조문표기>]` `--output <파일>` | 단건 법령(전문/조문/범위)·고시·판례·별표 원문 JSON 다운로드 및 검증 |
| `batch` | `--input <리스트파일.txt\|.json>` `--out-dir <저장폴더>` `[--report <요약.json>]` | 항목 리스트를 파싱하여 항목별 표준 파일명으로 일괄 다운로드 |
## Rate Limiting
- [open_law_cli.py](./scripts/open_law_cli.py) 내부에서 프로세스 간 파일 락(`/tmp/open_law_kr_rate_limit.lock`)과 `time.monotonic()`을 사용하여 요청 간 최소 `0.25초` 간격을 강제하며, 일시적 네트워크/5xx 오류 시 지수 백오프(최대 3회)로 자동 재시도한다.
## Common Mistakes
1. **`OC=test` 사용 금지**: 국가법령정보센터에서 공용 `OC=test`는 `"사용자 정보 검증에 실패하였습니다"` 오류로 거부된다. 반드시 기본 설정된 `OC=jhogyu`(또는 유효한 발급 키)를 사용한다.
2. **법령(`target=law`)과 행정규칙(`target=admrul`) 혼동**: 법률·대통령령·부령·대법원규칙은 `target=law`(`MST` 사용)이고, 각 부처 고시(예: `감정평가 실무기준`)·대법원 재판예규(예: `재민 91-1`, `재일 87-4`)·훈령은 `target=admrul`(`ID` 사용)이다.
3. **범위 조문(`§A~§B`)에서 가지조문 누락**: 예컨대 `민사소송법 §333~§341`에는 `제335조의2`, `제339조의2`, `제339조의3`이 포함되어 있다. 단순 정수 루프(`333..341`)로만 호출하면 가지조문이 누락되므로 반드시 본 스크립트의 범위 해석기(`resolve_jo_codes_for_law`)를 사용한다.
@@ -0,0 +1,4 @@
interface:
display_name: "국가법령정보센터(open.law.go.kr) 원문 다운로드"
short_description: "현행 법령·규칙·고시·예규·판례 원문을 공식 JSON으로 검색·다운로드·검증"
default_prompt: "국가법령정보센터(open.law.go.kr) Open API(OC=jhogyu)를 사용하여 요청된 법령·규칙·고시·판례의 현행 원문(특정 조문·가지조문·범위 조문 또는 전문)을 공식 JSON 형식으로 다운로드하고 검증하라."
+556
View File
@@ -0,0 +1,556 @@
#!/usr/bin/env python3
"""National Law Information Center (open.law.go.kr) DRF JSON Downloader CLI.
Supports:
- target=law : Statutes, Presidential Decrees, Ministerial Ordinances, Supreme Court Rules
(full law or article/range selection with automatic branch-article discovery)
- target=admrul : Administrative Rules (Notices/고시, Directives/훈령, Established Rules/예규)
- target=prec : Supreme Court & Lower Court Precedents / Decisions (판례·결정례)
- target=licbyl : Statute Attached Tables & Forms (별표·서식)
Default OC authentication key: "jhogyu" (override via --oc or OPEN_LAW_OC env var).
"""
from __future__ import annotations
import argparse
import fcntl
import json
import os
import re
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any
DEFAULT_OC = os.environ.get("OPEN_LAW_OC", "jhogyu")
BASE_SEARCH_URL = "https://www.law.go.kr/DRF/lawSearch.do"
BASE_SERVICE_URL = "https://www.law.go.kr/DRF/lawService.do"
RATE_LIMIT_LOCK = Path(tempfile.gettempdir()) / "open_law_kr_rate_limit.lock"
MIN_INTERVAL_SEC = 0.25
class OpenLawError(RuntimeError):
"""Raised when open.law.go.kr returns an error or invalid payload."""
def _rate_limited_get(url: str, timeout: int = 25, max_retries: int = 3) -> bytes:
"""Perform a cross-process rate-limited HTTP GET with retry on transient errors."""
RATE_LIMIT_LOCK.touch(exist_ok=True)
with RATE_LIMIT_LOCK.open("r+", encoding="utf-8") as lock_file:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
try:
lock_file.seek(0)
content = lock_file.read().strip()
last_ts = float(content) if content else 0.0
elapsed = time.monotonic() - last_ts
if 0.0 <= elapsed < MIN_INTERVAL_SEC:
time.sleep(MIN_INTERVAL_SEC - elapsed)
now_ts = time.monotonic()
lock_file.seek(0)
lock_file.truncate()
lock_file.write(f"{now_ts:.6f}")
lock_file.flush()
finally:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
last_err: Exception | None = None
for attempt in range(1, max_retries + 1):
req = urllib.request.Request(
url,
headers={
"User-Agent": "Mozilla/5.0 (compatible; OpenLawKrSkill/1.0)",
"Accept": "application/json, text/plain, */*",
},
)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
raw = resp.read()
text_preview = raw[:500].decode("utf-8", errors="ignore")
if "사용자 정보 검증에 실패하였습니다" in text_preview:
raise OpenLawError(
f"API key (OC) authentication failed on open.law.go.kr for URL: {url}"
)
return raw
except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError) as exc:
last_err = exc
if isinstance(exc, urllib.error.HTTPError) and 400 <= exc.code < 500 and exc.code != 429:
body = exc.read().decode("utf-8", errors="ignore")[:400]
raise OpenLawError(f"HTTP {exc.code} for {url}: {body}") from exc
wait_sec = 0.8 * (2 ** (attempt - 1))
print(
f"[retry {attempt}/{max_retries}] {exc} -> waiting {wait_sec:.1f}s ({url})",
file=sys.stderr,
)
time.sleep(wait_sec)
raise OpenLawError(f"Failed to fetch {url} after {max_retries} attempts: {last_err}")
def fetch_json(url: str) -> dict[str, Any]:
raw = _rate_limited_get(url)
text = raw.decode("utf-8", errors="replace").strip()
try:
data = json.loads(text)
except json.JSONDecodeError as exc:
raise OpenLawError(
f"Non-JSON response from {url} (first 300 chars): {text[:300]}"
) from exc
if not isinstance(data, dict):
raise OpenLawError(f"Unexpected JSON root type {type(data).__name__} from {url}")
return data
def normalize_law_name(name: str) -> str:
"""Strip spaces and parenthetical notes for resilient matching."""
cleaned = re.sub(r"\([^)]*\)", "", name)
return re.sub(r"\s+", "", cleaned).strip()
def format_jo_code(main_no: int, sub_no: int = 0) -> str:
"""Format article number + branch number into 6-digit JO code (NNNNMM)."""
return f"{main_no:04d}{sub_no:02d}"
def parse_article_token(token: str) -> tuple[int, int]:
"""Parse a single article token like '§109의2', '제2조의4', '§263①', '§388 2호', '§13①2나' into (main, sub)."""
m = re.search(r"(?:제\s*)?(\d+)\s*(?:조)?(?:\s*의\s*(\d+))?", token)
if not m:
raise ValueError(f"Cannot parse article number from token: {token!r}")
main_no = int(m.group(1))
sub_no = int(m.group(2)) if m.group(2) else 0
return main_no, sub_no
def parse_article_spec(spec: str) -> list[dict[str, Any]]:
"""Parse an article specification string into single or range descriptors.
Examples:
"§186" -> [{"type": "single", "main": 186, "sub": 0}]
"§356·§357·§358·§360" -> 4 singles
"§333~§341" -> [{"type": "range", "start": 333, "end": 341}]
"§3·§10·§16~§18" -> 2 singles + 1 range
"§13①2나·3호" -> [{"type": "single", "main": 13, "sub": 0}]
"""
spec = spec.strip()
if not spec or spec in {"전문", "전체", "ALL", "all"}:
return []
parts = [p.strip() for p in re.split(r"[·,]+", spec) if p.strip()]
descriptors: list[dict[str, Any]] = []
for part in parts:
# Check if part is a mere sub-item continuation like "3호" or "2호" without §/제
if re.fullmatch(r"\d+\s*(?:호|목|항)", part) and descriptors:
continue
# Check range pattern: e.g. §333~§341, 60~66, 제16조~제18조
range_match = re.search(
r"(?:§|제)?\s*(\d+)\s*(?:조)?\s*[~\-∼]\s*(?:§|제)?\s*(\d+)\s*(?:조)?",
part,
)
if range_match:
start_no = int(range_match.group(1))
end_no = int(range_match.group(2))
descriptors.append({"type": "range", "start": start_no, "end": end_no})
else:
main_no, sub_no = parse_article_token(part)
descriptors.append({"type": "single", "main": main_no, "sub": sub_no})
return descriptors
def search_law(name: str, oc: str = DEFAULT_OC) -> dict[str, Any]:
"""Find the current law entry matching `name` via lawSearch.do?target=law."""
# Strip parenthetical qualification like "(국토교통부령)" for query if needed
base_query = re.sub(r"\([^)]*\)$", "", name).strip()
q = urllib.parse.quote(base_query)
url = f"{BASE_SEARCH_URL}?OC={urllib.parse.quote(oc)}&target=law&type=JSON& display=100&query={q}".replace(
"& display=", "&display="
)
data = fetch_json(url)
laws = data.get("LawSearch", {}).get("law", [])
if isinstance(laws, dict):
laws = [laws]
if not laws:
raise OpenLawError(f"No law found for query: {base_query!r}")
norm_target = normalize_law_name(base_query)
exact = [
x
for x in laws
if normalize_law_name(str(x.get("법령명한글", ""))) == norm_target
]
candidates = exact if exact else laws
# Prefer 현행연혁구분 == "현행", then latest 시행일자
candidates.sort(
key=lambda x: (
1 if x.get("현행연혁구분") == "현행" else 0,
str(x.get("시행일자", "")),
str(x.get("공포일자", "")),
),
reverse=True,
)
return candidates[0]
def search_admrul(name: str, oc: str = DEFAULT_OC) -> dict[str, Any]:
"""Find the current administrative rule (고시·예규·훈령) matching `name`."""
base_query = re.sub(r"\((?:국토교통부|법무부|국세청|행정안전부|기획재정부|금융위원회)?\s*(?:고시|예규|훈령|지침)\)$", "", name).strip()
q = urllib.parse.quote(base_query)
url = f"{BASE_SEARCH_URL}?OC={urllib.parse.quote(oc)}&target=admrul&type=JSON&display=100&query={q}"
data = fetch_json(url)
items = data.get("AdmRulSearch", {}).get("admrul", [])
if isinstance(items, dict):
items = [items]
if not items:
raise OpenLawError(f"No administrative rule (admrul) found for query: {base_query!r}")
norm_target = normalize_law_name(base_query)
exact = [
x
for x in items
if normalize_law_name(str(x.get("행정규칙명", ""))) == norm_target
]
candidates = exact if exact else items
candidates.sort(
key=lambda x: (
1 if x.get("현행연혁구분") == "현행" else 0,
str(x.get("시행일자", "")),
str(x.get("발령일자", "")),
),
reverse=True,
)
return candidates[0]
def search_prec(query: str, oc: str = DEFAULT_OC) -> dict[str, Any]:
"""Find a precedent/decision (판례·결정례) by case number or query."""
q = urllib.parse.quote(query.strip())
url = f"{BASE_SEARCH_URL}?OC={urllib.parse.quote(oc)}&target=prec&type=JSON&display=50&query={q}"
data = fetch_json(url)
items = data.get("PrecSearch", {}).get("prec", [])
if isinstance(items, dict):
items = [items]
if not items:
raise OpenLawError(f"No precedent (prec) found for query: {query!r}")
for item in items:
if str(item.get("사건번호", "")).strip() == query.strip():
return item
return items[0]
def resolve_jo_codes_for_law(
mst: str,
descriptors: list[dict[str, Any]],
oc: str = DEFAULT_OC,
include_deleted: bool = False,
) -> list[str]:
"""Resolve descriptors (including ranges with branch articles) into 6-digit JO codes."""
has_range = any(d["type"] == "range" for d in descriptors)
full_units: list[dict[str, Any]] = []
if has_range:
full_url = f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}&target=law&type=JSON&MST={urllib.parse.quote(mst)}"
full_data = fetch_json(full_url)
raw_units = full_data.get("법령", {}).get("조문", {}).get("조문단위", [])
if isinstance(raw_units, dict):
raw_units = [raw_units]
full_units = raw_units
jo_codes: list[str] = []
seen: set[str] = set()
for desc in descriptors:
if desc["type"] == "single":
code = format_jo_code(desc["main"], desc["sub"])
if code not in seen:
seen.add(code)
jo_codes.append(code)
elif desc["type"] == "range":
start_no, end_no = desc["start"], desc["end"]
for u in full_units:
if u.get("조문여부") != "조문":
continue
jnum = int(u.get("조문번호", "0"))
if start_no <= jnum <= end_no:
content_str = str(u.get("조문내용", "")).strip()
if not include_deleted and u.get("조문제목") is None and "삭제" in content_str:
continue
sub_str = str(u.get("조문가지번호", "")).strip()
sub_no = int(sub_str) if sub_str.isdigit() else 0
code = format_jo_code(jnum, sub_no)
if code not in seen:
seen.add(code)
jo_codes.append(code)
return jo_codes
def fetch_law_json(
law_name_or_mst: str,
articles_spec: str | None = None,
oc: str = DEFAULT_OC,
include_deleted: bool = False,
) -> tuple[dict[str, Any], dict[str, Any]]:
"""Fetch full law JSON or specific article(s) JSON from open.law.go.kr.
Returns (json_payload, meta_info).
"""
if law_name_or_mst.isdigit():
mst = law_name_or_mst
law_meta = {"법령일련번호": mst}
else:
law_meta = search_law(law_name_or_mst, oc=oc)
mst = str(law_meta["법령일련번호"])
descriptors = parse_article_spec(articles_spec or "")
if not descriptors:
url = f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}&target=law&type=JSON&MST={urllib.parse.quote(mst)}"
data = fetch_json(url)
return data, {"mst": mst, "jo_codes": [], "law_meta": law_meta}
jo_codes = resolve_jo_codes_for_law(
mst=mst,
descriptors=descriptors,
oc=oc,
include_deleted=include_deleted,
)
if len(jo_codes) == 1:
url = (
f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}"
f"&target=law&type=JSON&MST={urllib.parse.quote(mst)}&JO={jo_codes[0]}"
)
data = fetch_json(url)
if "조문" not in data.get("법령", {}) or "조문단위" not in data["법령"]["조문"]:
raise OpenLawError(f"Missing 조문단위 for MST={mst} JO={jo_codes[0]}")
return data, {"mst": mst, "jo_codes": jo_codes, "law_meta": law_meta}
combined_units: list[Any] = []
base_data: dict[str, Any] | None = None
for jo in jo_codes:
url = (
f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}"
f"&target=law&type=JSON&MST={urllib.parse.quote(mst)}&JO={jo}"
)
d = fetch_json(url)
if "조문" not in d.get("법령", {}) or "조문단위" not in d["법령"]["조문"]:
raise OpenLawError(f"Missing 조문단위 for MST={mst} JO={jo}")
if base_data is None:
base_data = d
unit = d["법령"]["조문"]["조문단위"]
if isinstance(unit, list):
combined_units.extend(unit)
else:
combined_units.append(unit)
assert base_data is not None
base_data["법령"]["조문"]["조문단위"] = combined_units
return base_data, {"mst": mst, "jo_codes": jo_codes, "law_meta": law_meta}
def fetch_admrul_json(name_or_id: str, oc: str = DEFAULT_OC) -> tuple[dict[str, Any], dict[str, Any]]:
if name_or_id.isdigit():
adm_id = name_or_id
meta = {"행정규칙일련번호": adm_id}
else:
meta = search_admrul(name_or_id, oc=oc)
adm_id = str(meta["행정규칙일련번호"])
url = f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}&target=admrul&type=JSON&ID={urllib.parse.quote(adm_id)}"
data = fetch_json(url)
return data, {"id": adm_id, "admrul_meta": meta}
def fetch_prec_json(query_or_id: str, oc: str = DEFAULT_OC) -> tuple[dict[str, Any], dict[str, Any]]:
if query_or_id.isdigit():
prec_id = query_or_id
meta = {"판례일련번호": prec_id}
else:
meta = search_prec(query_or_id, oc=oc)
prec_id = str(meta["판례일련번호"])
url = f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}&target=prec&type=JSON&ID={urllib.parse.quote(prec_id)}"
data = fetch_json(url)
return data, {"id": prec_id, "prec_meta": meta}
def build_default_filename(law_name: str, articles_spec: str | None, target: str = "law") -> str:
"""Build a clean, deterministic Korean JSON filename from law name and article spec."""
clean_law = re.sub(r"\([^)]*\)$", "", law_name).strip()
clean_law = re.sub(r"\s+", "_", clean_law)
if target == "admrul" or not articles_spec or articles_spec.strip() in {"전문", "전체", "ALL", "all"}:
suffix = "전문" if (articles_spec and "전문" in articles_spec) else "현행"
return f"{clean_law}_{suffix}.json"
circle_map = {
"①": "제1항", "②": "제2항", "③": "제3항", "④": "제4항", "⑤": "제5항",
"⑥": "제6항", "⑦": "제7항", "⑧": "제8항", "⑨": "제9항", "⑩": "제10항",
}
s = articles_spec.strip()
for c, rep in circle_map.items():
s = s.replace(c, rep)
# Convert §N(의M)? to 제N조(의M)?
s = re.sub(r"§\s*(\d+)(?:의(\d+))?", lambda m: f"제{m.group(1)}조" + (f"의{m.group(2)}" if m.group(2) else ""), s)
s = re.sub(r"[·,~∼\s]+", "_", s).strip("_")
return f"{clean_law}_{s}.json"
def cmd_search(args: argparse.Namespace) -> None:
q = urllib.parse.quote(args.query)
url = f"{BASE_SEARCH_URL}?OC={urllib.parse.quote(args.oc)}&target={urllib.parse.quote(args.target)}&type=JSON&display={args.limit}&query={q}"
data = fetch_json(url)
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"Success! Search results written to: {out_path} ({out_path.stat().st_size} bytes)")
def cmd_fetch(args: argparse.Namespace) -> None:
if args.target == "law":
data, meta = fetch_law_json(
law_name_or_mst=args.name or args.id,
articles_spec=args.articles,
oc=args.oc,
include_deleted=args.include_deleted,
)
elif args.target == "admrul":
data, meta = fetch_admrul_json(args.name or args.id, oc=args.oc)
elif args.target == "prec":
data, meta = fetch_prec_json(args.name or args.id, oc=args.oc)
else:
url = (
f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(args.oc)}"
f"&target={urllib.parse.quote(args.target)}&type=JSON&ID={urllib.parse.quote(args.id or args.name)}"
)
data = fetch_json(url)
meta = {"id": args.id or args.name}
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(
f"Success! Saved {out_path} ({out_path.stat().st_size} bytes) | meta={json.dumps(meta, ensure_ascii=False)}"
)
def parse_batch_line(line: str) -> dict[str, Any] | None:
"""Parse a bullet line such as '- `감정평가 및 감정평가사에 관한 법률` §3·§6' or '- 지방세법시행령 §109의2'."""
s = line.strip()
s = re.sub(r"^[-*•]\s*", "", s).strip()
if not s:
return None
# Check if backtick-quoted law name: `법령명` 스펙
m_bt = re.match(r"^`([^`]+)`\s*(.*)$", s)
if m_bt:
raw_name, rest = m_bt.group(1).strip(), m_bt.group(2).strip()
else:
# Split before first § or '전문'
m_split = re.match(r"^(.+?)\s+(§.+|전문|전체)$", s)
if m_split:
raw_name, rest = m_split.group(1).strip(), m_split.group(2).strip()
else:
raw_name, rest = s, ""
# Common spacing normalizations for decree names (e.g. 지방세법시행령 -> 지방세법 시행령)
if raw_name.endswith("시행령") and not raw_name.endswith(" 시행령"):
raw_name = raw_name[:-3] + " 시행령"
if raw_name.endswith("시행규칙") and not raw_name.endswith(" 시행규칙"):
raw_name = raw_name[:-4] + " 시행규칙"
is_admrul = bool(re.search(r"\((?:[^)]*고시|[^)]*예규|[^)]*훈령)\)", raw_name)) or "실무기준" in raw_name
target = "admrul" if is_admrul else "law"
filename = build_default_filename(raw_name, rest, target=target)
return {
"target": target,
"name": raw_name,
"articles": rest if target == "law" else None,
"filename": filename,
}
def cmd_batch(args: argparse.Namespace) -> None:
spec_path = Path(args.input)
raw_text = spec_path.read_text(encoding="utf-8").strip()
if raw_text.startswith("[") or raw_text.startswith("{"):
parsed = json.loads(raw_text)
items = parsed["items"] if isinstance(parsed, dict) and "items" in parsed else parsed
else:
items = [x for line in raw_text.splitlines() if (x := parse_batch_line(line)) is not None]
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
summary: list[dict[str, Any]] = []
for item in items:
target = item.get("target", "law")
name = item["name"]
articles = item.get("articles")
filename = item.get("filename") or build_default_filename(name, articles, target=target)
if target == "law":
data, meta = fetch_law_json(name, articles_spec=articles, oc=args.oc)
elif target == "admrul":
data, meta = fetch_admrul_json(name, oc=args.oc)
elif target == "prec":
data, meta = fetch_prec_json(name, oc=args.oc)
else:
raise OpenLawError(f"Unsupported batch target: {target}")
dest = out_dir / filename
dest.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
entry = {
"name": name,
"articles": articles,
"target": target,
"filename": str(dest),
"bytes": dest.stat().st_size,
"meta": meta,
}
summary.append(entry)
print(f"Saved: {filename} ({dest.stat().st_size} bytes)")
if args.report:
report_path = Path(args.report)
report_path.parent.mkdir(parents=True, exist_ok=True)
report_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"Batch report written to: {report_path}")
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(description="open.law.go.kr DRF JSON Downloader CLI")
p.add_argument("--oc", default=DEFAULT_OC, help="API key (OC), defaults to OPEN_LAW_OC or 'jhogyu'")
sub = p.add_subparsers(dest="subcommand", required=True)
sp_search = sub.add_parser("search", help="Search law / admrul / prec / licbyl")
sp_search.add_argument("--target", default="law", choices=["law", "admrul", "prec", "licbyl"])
sp_search.add_argument("--query", required=True, help="Search query")
sp_search.add_argument("--limit", type=int, required=True, help="Max results to retrieve")
sp_search.add_argument("--output", required=True, help="Output JSON file path")
sp_search.set_defaults(func=cmd_search)
sp_fetch = sub.add_parser("fetch", help="Fetch a single law (full or articles), admrul, prec, or licbyl")
sp_fetch.add_argument("--target", default="law", choices=["law", "admrul", "prec", "licbyl"])
sp_fetch.add_argument("--name", help="Exact Korean name of law / admrul / case number")
sp_fetch.add_argument("--id", help="Explicit MST or ID if known")
sp_fetch.add_argument("--articles", help="Article spec for target=law (e.g. '§3·§10·§16~§18', '§109의2')")
sp_fetch.add_argument("--include-deleted", action="store_true", help="Include deleted branch articles in ranges")
sp_fetch.add_argument("--output", required=True, help="Output JSON file path")
sp_fetch.set_defaults(func=cmd_fetch)
sp_batch = sub.add_parser("batch", help="Batch download a list of items (markdown bullet list or JSON)")
sp_batch.add_argument("--input", required=True, help="Path to text/markdown list or JSON manifest")
sp_batch.add_argument("--out-dir", required=True, help="Destination directory for JSON files")
sp_batch.add_argument("--report", help="Optional path to write batch download summary JSON")
sp_batch.set_defaults(func=cmd_batch)
return p
def main() -> None:
parser = build_parser()
args = parser.parse_args()
try:
args.func(args)
except Exception as exc:
print(f"ERROR: {exc}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
+92 -15
View File
@@ -69,6 +69,8 @@ MCP 서버 (localdocs) → _resolve_user(ctx) → 해시된 경로에서 파일
| `JEV_API_KEY` | (선택) | TypeSafe JEV(System One 결정 모델) API 키 — task 유형 `jev:` 전용 (§3.4) | | `JEV_API_KEY` | (선택) | TypeSafe JEV(System One 결정 모델) API 키 — task 유형 `jev:` 전용 (§3.4) |
| `JEV_API_URL` | `https://api.typesafe.ai/v1/systemone` | JEV 엔드포인트 (프록시 사용 시 변경) | | `JEV_API_URL` | `https://api.typesafe.ai/v1/systemone` | JEV 엔드포인트 (프록시 사용 시 변경) |
| `JEV_DEFAULT_MODEL` | `jev-latest` | `jev.model` 미지정 시 모델 | | `JEV_DEFAULT_MODEL` | `jev-latest` | `jev.model` 미지정 시 모델 |
| `OPENAI_DECISIONS_URL` | `https://api.openai.com/v1/decisions` | `jev.provider: openai` 엔드포인트 |
| `OPENAI_DECISIONS_MODEL` | `gpt-6-luna` | `jev.provider: openai` 기본 모델 |
### 0.5 API 키 설정 ### 0.5 API 키 설정
@@ -468,6 +470,7 @@ print(json.dumps({
- wildcard task 의 `task_name` 은 반드시 `_*` 로 끝나야 함 (`_is_wildcard_name`) - wildcard task 의 `task_name` 은 반드시 `_*` 로 끝나야 함 (`_is_wildcard_name`)
- cross-fan-out 참조 시 `{same_ordinal}` 은 같은 ordinal 끼리만 연결. 다른 ordinal 의 동일 task type 은 독립. - cross-fan-out 참조 시 `{same_ordinal}` 은 같은 ordinal 끼리만 연결. 다른 ordinal 의 동일 task type 은 독립.
- aggregate token `all Task_X_*` 은 모든 instance 완료를 한 번에 대기. quality gate 패턴의 표준 형태. - aggregate token `all Task_X_*` 은 모든 instance 완료를 한 번에 대기. quality gate 패턴의 표준 형태.
- `all Task_X_*` 로 대기하는 집계자는 **완료된 인스턴스의 결과를 `{{prev.Task_X_0}}`, `{{prev.Task_X_1}}` … 로 받는다** (`{{prev.Task_X_1.answers.route.choice}}` 같은 중첩 접근 포함). 실패·스킵된 인스턴스는 `prev` 에 없으므로 참조하면 문자열이 그대로 남는다 — 인스턴스 수가 가변이면 파일 집계(localdocs) 나 `{{prev}}` 전체를 받는 code task 로 처리한다. code task 의 `{{prev}}` 전체 덤프에도 인스턴스 결과가 함께 들어가므로 크기에 주의.
- 자세한 동작 흐름: `agent.py::TaskProcedureExecutor._maybe_expand_wildcards` - 자세한 동작 흐름: `agent.py::TaskProcedureExecutor._maybe_expand_wildcards`
--- ---
@@ -480,16 +483,16 @@ print(json.dumps({
- task_name: analyze - task_name: analyze
llm_provider: google # google | anthropic | openai | "https://<endpoint>" (OpenAI-compatible) llm_provider: google # google | anthropic | openai | "https://<endpoint>" (OpenAI-compatible)
llm_model: gemini-3.1-pro-preview llm_model: gemini-3.1-pro-preview
llm_reasoning: high # low | medium | high (provider 별 매핑은 아래 주의 참조) llm_reasoning: high # low | medium | high, 또는 숫자(사고 토큰 예산). provider 별 매핑은 아래 주의 참조
llm_verbosity: medium # low | medium | high (OpenAI 전용) llm_verbosity: medium # low | medium | high (OpenAI 전용)
llm_endpoint: completions # "completions" (default) | "responses" (OpenAI; GPT-5.6+ 캐시·체이닝은 responses 권장) llm_endpoint: completions # "completions" (default) | "responses" (OpenAI; GPT-5.6+ 캐시·체이닝은 responses 권장)
llm_token_limit: 16000 # 선택. 출력 토큰 상한 (provider 별 파라미터로 매핑) llm_token_limit: 16000 # 선택. 출력 토큰 상한 (provider 별 파라미터로 매핑). 미지정 시 Anthropic 만 16000, 나머지는 모델 기본 상한
llm_prompt_cache_key: S2:analyze # 선택 (OpenAI). 미지정 시 "<stage>:<task base-name>" 자동 파생 — §6.5.2 llm_prompt_cache_key: S2:analyze # 선택 (OpenAI). 미지정 시 "<stage>:<task base-name>" 자동 파생 — §6.5.2
llm_result_envelope: true # 선택. 다음 task 의 {{prev.<this>}} 를 본문 대신 결과 봉투로 (아래 주의 참조) llm_result_envelope: true # 선택. 다음 task 의 {{prev.<this>}} 를 본문 대신 결과 봉투로 (아래 주의 참조)
use_tools: ["localdocs"] # LLM이 사용할 MCP 서버 use_tools: ["localdocs"] # LLM이 사용할 MCP 서버
cache_control: # 선택. Gemini/Anthropic 은 네이티브 캐시, OpenAI 는 §6.5.2 의 prompt cache 로 번역 cache_control: # 선택. Gemini/Anthropic 은 네이티브 캐시, OpenAI 는 §6.5.2 의 prompt cache 로 번역
mode: auto # "auto" | "explicit" mode: auto # "auto" | "explicit"
ttl: 1h # Gemini/Anthropic: 5m / 10m / 1h / 2h ... (Pro 모델 long-running 은 1h+ 권장). OpenAI GPT-5.6+: "30m" 만 ttl: 1h # Gemini/Anthropic: 5m / 10m / 1h / 2h ... (Pro 모델 long-running 은 1h+ 권장). OpenAI GPT-5.6+: "30m" (기본) 또는 "12h" (responses 엔드포인트 전용, 쓰기 단가 2.5x)
preflight: true # default true. 프롬프트의 파일명을 미리 read_docs (LLM-based task 만 적용) preflight: true # default true. 프롬프트의 파일명을 미리 read_docs (LLM-based task 만 적용)
preflight_files: # 선택. 명시 시 regex 스캔 대신 이 화이트리스트만 preflight preflight_files: # 선택. 명시 시 regex 스캔 대신 이 화이트리스트만 preflight
- evidence_shard_plan.json # glob (*, ?) 지원 - evidence_shard_plan.json # glob (*, ?) 지원
@@ -507,7 +510,19 @@ print(json.dumps({
**주의:** **주의:**
- `use_tools` 를 주면 LLM 이 도구 호출 가능 → 프롬프트에서 **허용 범위를 명시**해야 함 - `use_tools` 를 주면 LLM 이 도구 호출 가능 → 프롬프트에서 **허용 범위를 명시**해야 함
- `llm_reasoning` 은 세 provider 모두 적용된다. OpenAI: `reasoning_effort`(completions) / `reasoning.effort`(responses), Anthropic: `output_config.effort`, Google: `thinkingConfig.thinkingLevel` (native SDK 경로 포함) - `llm_reasoning` 은 **사고 수준을 정하는 단일 키**다. `thinking_level`, `reasoning_effort`, `budget_tokens` 같은 provider 전용 키는 YAML 에 없고, 브리지가 provider 와 모델을 보고 이름을 바꿔 보낸다. 값은 `low | medium | high` 한 세트를 공통으로 쓰며(Gemini 가 추가로 받는 `minimal` 도 같은 키에 적는다), 모델을 바꿔도 YAML 을 고칠 필요가 없게 하기 위한 설계다.
| YAML `llm_reasoning` | 실제로 가는 파라미터 |
|---|---|
| OpenAI | `reasoning_effort` (chat) / `reasoning.effort` (responses) |
| Anthropic 4.6+ | `output_config.effort` (+ adaptive thinking) |
| Anthropic 4.5 이하 | `thinking.budget_tokens` (low 2048 / medium 8192 / high 16384) |
| Gemini 3.x | `thinking_config.thinking_level` |
| Gemini 2.5 이하 | `thinking_config.thinking_budget` (low 1024 / medium 8192 / high 32768) |
- `llm_reasoning` 에 **숫자**를 적으면 사고 토큰 예산으로 해석된다. 정확한 예산 제어가 되는 곳은 Gemini 2.5 이하(`thinking_budget=숫자`)와 Anthropic 4.5 이하(`budget_tokens=숫자`)뿐이다. **Gemini 3.x 이상은 `thinking_budget` 이 deprecated 라(간헐적 400, Gemini 4 는 항상 400) 숫자를 티어로 바꿔 `thinking_level` 로 보낸다.** OpenAI·Anthropic 4.6+ 도 같은 변환이다: ≤1024 low / ≤8192 medium / 그 이상 high. 즉 3.x 에서 사고량 조절 수단은 level 4단계뿐이며, 숫자는 2.5 와 YAML 을 공유할 때만 의미가 있다.
- `llm_token_limit` 은 **출력 토큰 상한**이다. provider 별로 OpenAI responses `max_output_tokens`, OpenAI chat 은 gpt-5/6·o 시리즈·reasoning 있음이면 `max_completion_tokens` 그 외 `max_tokens`, Anthropic `max_tokens`, Gemini native `max_output_tokens` 로 보낸다. **적지 않으면 OpenAI·Gemini 는 파라미터를 보내지 않아 모델 기본 상한까지 출력**하고, Anthropic 만 필수 인자라 기본 16,000 을 넣는다(4.5 이하에서 thinking budget 이 더 크면 budget+1,024 로 자동 상향). **OpenAI 와 Anthropic 은 이 한도에 사고(reasoning) 토큰이 포함**되므로 `llm_reasoning: high` 인 task 에 작은 한도를 주면 본문이 잘리거나 `length`/`incomplete` 로 끝난다 — 넉넉히 잡거나 비워 둔다. Gemini 는 사고가 별도 집계라 본문 길이에만 적용된다.
- Google 상세: Gemini 3.x 이상은 `thinking_level` 로 전송되고(`thinking_budget` 과 동시 전송 불가), 2.5 이하는 `thinking_budget`(low 1024 / medium 8192 / high 32768). 허용값은 모델마다 다르다 — gemini-3.8-flash·3.1-pro: `low|medium|high`, 3.6-flash·3.5-flash-lite: `minimal|low|medium|high`, 3-pro: `low|high`. 미지원 값은 가장 가까운 허용값으로 내려 보내고 경고를 남긴다(pro 에 `minimal` → `low`). 기본값은 flash 계열 medium, pro 계열 high 이므로, 사고량을 줄이려면 `low` 를 명시한다. 사고 토큰은 `thoughts_token_count` 로 따로 집계되며(`[USAGE]` 로그 `thoughts=`), 출력 단가로 과금된다. `llm_token_limit`(`max_output_tokens`)은 본문 길이 상한이지 사고량을 정하지 않는다. 사고 수준과 출력 한도는 API 파라미터라 프롬프트 본문에 적어도 효과가 없다.
- `llm_verbosity` 는 OpenAI 에서만 전송된다 - `llm_verbosity` 는 OpenAI 에서만 전송된다
- `llm_result_envelope: true` 이면 하류 task 가 받는 `{{prev.<task>}}` 가 답변 본문이 아니라 다음 봉투가 된다. provider 의 종료 상태·usage 를 검증 task 가 직접 봐야 할 때 쓴다 (기본 false, 기존 YAML 영향 없음). - `llm_result_envelope: true` 이면 하류 task 가 받는 `{{prev.<task>}}` 가 답변 본문이 아니라 다음 봉투가 된다. provider 의 종료 상태·usage 를 검증 task 가 직접 봐야 할 때 쓴다 (기본 false, 기존 YAML 영향 없음).
```json ```json
@@ -577,24 +592,26 @@ print(json.dumps({
### 3.4 JEV Task (TypeSafe System One — 결정 모델) ### 3.4 JEV Task (TypeSafe System One — 결정 모델)
JEV 는 텍스트를 생성하지 않는다. `state`(판단 대상 자료)에 대해 **choice / score / noul** 세 종류의 질문에 JEV 는 텍스트를 생성하지 않는다. `state`(판단 대상 자료)에 대해 **choice / score / noul** 세 종류의 질문에
선택·점수·확률만 돌려주는 결정 모델이다(TypeSafe `POST /v1/systemone`). 그래서 `llm_provider` 가 아니라 선택·점수·확률만 돌려주는 결정 모델이다(TypeSafe `POST /v1/systemone`). Jev 1.14(2026-10-14)부터 이미지 입력과 **box**(이미지 안 위치 찾기) 질문, 262K long-context 가 추가됐다(아래 "1.14 추가 기능"). 그래서 `llm_provider` 가 아니라
Direct MCP 처럼 **별도 task 유형 `jev:`** 로 쓴다. 프롬프트·도구·preflight 는 없고, 백엔드가 요청을 검증해 Direct MCP 처럼 **별도 task 유형 `jev:`** 로 쓴다. 프롬프트·도구·preflight 는 없고, 백엔드가 요청을 검증해
직접 호출하며 429/529 는 지수 백오프로 최대 4회 재시도, 401/422 는 즉시 실패한다. 직접 호출하며 429/503/529 는 지수 백오프로 최대 4회 재시도, 400/401/422 는 즉시 실패한다.
```yaml ```yaml
- task_name: Task_gate_decision - task_name: Task_gate_decision
jev: jev:
model: jev-latest # 선택. jev-latest | jev-preview | jev-1.13.0 provider: jev # 선택. jev(기본, TypeSafe) | openai (OpenAI Decisions API, 아래 참조)
model: jev-latest # 선택. jev-latest(=jev-1.14.0) | jev-preview(지금은 latest 와 동일) | jev-1.14.0 | jev-1.13.0
long_context: false # 선택. true 면 한도 64K/32K → 262K (opt-in 헤더 전송)
state: "{{prev.Task_assess_bundle.summary}}" # 문자열·객체·배열. JSON 문자열이면 객체로 전달됨 state: "{{prev.Task_assess_bundle.summary}}" # 문자열·객체·배열. JSON 문자열이면 객체로 전달됨
questions: questions:
complete: # noul: 예/아니오 확률 (0~1) complete: # noul: 예/아니오 확률 (0~1)
type: noul type: noul
instructions: "요건사실 검토가 모두 끝났는가?" instructions: "요건사실 검토가 모두 끝났는가?"
severity: # score: 순서 있는 2~10단계 severity: # score: 순서 있는 1~10단계 (위치가 점수, 0부터)
type: score type: score
instructions: "누락의 심각도를 평가하라" instructions: "누락의 심각도를 평가하라"
criteria: ["none", "minor", "major"] criteria: ["none", "minor", "major"]
route: # choice: 선택지 매핑 (2~255개) route: # choice: 선택지 매핑 (1~255개, 설명 null 이면 이름만으로 해석)
type: choice type: choice
instructions: "다음 단계를 고르라" instructions: "다음 단계를 고르라"
criteria: criteria:
@@ -608,7 +625,7 @@ Direct MCP 처럼 **별도 task 유형 `jev:`** 로 쓴다. 프롬프트·도구
출력(task 결과 = 응답 JSON 전체): 출력(task 결과 = 응답 JSON 전체):
```json ```json
{"model": "jev-1.13.0", {"model": "jev-1.14.0",
"answers": { "answers": {
"complete": {"type": "noul", "noul": 0.91}, "complete": {"type": "noul", "noul": 0.91},
"severity": {"type": "score", "score": 1.0, "legend": {"0": "none", "1": "minor", "2": "major"}, "severity": {"type": "score", "score": 1.0, "legend": {"0": "none", "1": "minor", "2": "major"},
@@ -622,11 +639,68 @@ Direct MCP 처럼 **별도 task 유형 `jev:`** 로 쓴다. 프롬프트·도구
처럼 참조하고, `when:` 조건에도 쓸 수 있다. 처럼 참조하고, `when:` 조건에도 쓸 수 있다.
제약과 주의: 제약과 주의:
- 요청당 64K 토큰, `state` + 가장 긴 질문 ≤ 32K 토큰. 넘기면 422. - 요청당 64K 토큰, `state` + 가장 긴 질문 ≤ 32K 토큰. 넘기면 422. `long_context: true` 면 둘 다 262K (1.13·1.14 모두 지원).
- `jev-latest` 는 새 버전이 나오면 따라 움직여 답이 바뀔 수 있다. 임계값을 튜닝한 task 는 `jev-1.14.0` 처럼 고정한다.
- `instructions` 와 `criteria` 값은 문자열뿐 아니라 객체·배열도 된다(구조화된 기준을 그대로 전달).
- 한국어는 지원되지만 영어보다 정확도가 낮다(공식 문서). 질문문은 짧고 명확하게, 선택지 설명(`criteria` 값)은 구체적으로. - 한국어는 지원되지만 영어보다 정확도가 낮다(공식 문서). 질문문은 짧고 명확하게, 선택지 설명(`criteria` 값)은 구체적으로.
- noul 은 `confidence` 가 없다. score 는 `criteria` 목록 순서가 0,1,2… 로 매핑된다. - noul 은 `confidence` 가 없다. score 는 `criteria` 목록 순서가 0,1,2… 로 매핑된다.
- 과금은 입력 토큰만(2026-10 기준 $0.042/M, 출력 무료). usage 는 `token_usage_logs` 에 provider `jev` 로 기록된다. - 과금은 입력 토큰만(2026-10 기준 $0.042/M, 출력 무료). usage 는 `token_usage_logs` 에 provider `jev` 로 기록된다.
- `expose_tools`, `preflight*`, `max_iterations`, `use_tools` 는 JEV task 에 적용되지 않는다. - `expose_tools`, `preflight*`, `max_iterations`, `use_tools` 는 JEV task 에 적용되지 않는다.
- 2026-11-05 dev 에서 실호출 확인: `jev-latest`(=1.14.0), `jev-1.14.0`+`long_context`, `provider: openai`(gpt-6-luna) 세 구성 모두 choice·score·noul 정상.
**작성 규칙 (JEV·OpenAI Decisions 공통)**
1. **쓸 자리.** 자유 텍스트가 필요 없는 판정에만 쓴다 — 분류(어느 유형인가), 게이트(다음 단계로 가도 되는가), 채점(품질 몇 단계인가), 예/아니오. 근거 문장·요약·재작성이 필요하면 LLM task 다. 결정 모델은 입력 토큰만 과금되므로 "LLM 으로 판정 + 설명" 보다 "결정 모델로 판정 → 필요할 때만 LLM 으로 설명" 순서가 싸다.
2. **`state` 는 판정에 필요한 자료만.** 앞 task 의 출력 전체(`{{prev.X}}`)를 통째로 넣지 말고 판정에 쓰이는 필드만 고른다(`{{prev.X.summary}}`, 객체면 필요한 키만 담은 매핑). 긴 원문은 요약본이나 발췌를 넣는다. 한도는 요청 64K·질문 32K 토큰(`long_context` 시 262K)이지만, 길수록 정확도가 떨어지고 비용이 는다. 여러 인스턴스가 같은 자료를 판정하면 `state` 를 완전히 같게 두고 질문만 달리한다 — OpenAI 는 prefix 캐시가, JEV 는 비용이 그대로이므로 **한 요청에 질문을 묶는 편**이 낫다(질문 수 제한: JEV 명시 없음, OpenAI 400개).
3. **질문 하나에 판단 하나.** `instructions` 는 한 문장의 질문·명제로 쓴다("다음 단계로 발행해도 되는가" / "요건사실 검토가 끝났다"). "A 이고 B 이면 C" 같은 복합 조건은 질문을 쪼개 `when:` 이나 code task 에서 합친다. 지시문에 "JSON 으로 답하라", "이유를 써라" 같은 출력 지시를 넣지 않는다 — 결정 모델은 형식이 고정이고 텍스트를 내지 않는다.
4. **choice 는 상호 배타적 선택지 + 구체적 설명.** `criteria` 값(설명)에 "언제 이 선택지인가"를 적는다. 모호한 경계는 "그 외/해당 없음" 선택지를 하나 두어 억지 분류를 막는다. 선택지 이름(키)은 후속 task 가 그대로 쓰는 식별자이므로 영문 snake_case 로 고정하고, 사람이 읽을 말은 설명에 둔다. OpenAI 는 설명이 없으면 이름만으로 해석하므로 설명을 비우지 않는다.
5. **score 는 순서가 곧 점수.** `criteria` 를 낮음→높음 순으로 쓰고 각 단계의 기준을 설명에 적는다. 3~5단계가 적당하다(10단계 상한). 답 `score` 는 확률 가중 평균이라 소수가 나오므로 `when:` 에서는 `>= 1.5` 처럼 구간으로 비교하고, 단계 라벨이 필요하면 `legend` 로 되찾는다. OpenAI 는 2단계 이상이어야 한다.
6. **noul 은 명제문으로.** 지시문을 "…인가?" 보다 "…이다" 형태의 명제로 쓰면 `noul`(참일 확률)의 의미가 분명하다. JEV 는 `criteria: {true: "...", false: "..."}` 로 양쪽 기준을 줄 수 있고(OpenAI 는 지시문에 합쳐져 전달됨), 임계값은 0.5 고정이 아니라 용도별로 정한다 — 게이트는 보수적으로(통과 0.8 이상), 스크리닝은 느슨하게(0.3 이상 검토).
7. **confidence 를 분기에 쓴다.** choice·score 의 `confidence` 가 낮으면(예: 0.6 미만) 자동 확정하지 말고 LLM 재검토나 사람 검토 경로로 보낸다. `when:` 예: `prev.Task_gate.answers.route.choice == 'publish' and prev.Task_gate.answers.route.confidence >= 0.7`.
8. **provider 선택.** 기본은 JEV(입력 $0.042/M). 다음이면 `provider: openai`(입력 $0.10/M, 캐시 읽기 $0.01/M): 같은 긴 `state` 에 판정을 여러 번·여러 task 에서 반복해 prefix 캐시 이득이 큰 경우, 질문이 수백 개로 한 요청에 묶이는 경우, JEV 키가 없는 환경. 이미지·box 판정은 JEV 만 된다. 두 provider 의 확률 분포는 다르므로 **임계값을 튜닝한 task 는 provider 와 모델 버전을 함께 고정**한다(`jev-1.14.0`, `gpt-6-luna`).
9. **fan-out 과 집계.** 항목별 판정은 `Task_decide_*` 로 펼치고 `state: "{{item.state}}"` 로 받는다. 집계자는 `wait_until: ["all Task_decide_*"]` 로 기다리며 `{{prev.Task_decide_0.answers.…}}` 를 쓸 수 있지만 인스턴스 수가 가변이면 code task 에서 `{{prev}}` 전체를 받아 처리한다. 실패한 인스턴스(빈 `state` 등 400/422)는 재시도 후 failed 로 남고 하류는 진행되므로, 집계에서 빠진 인스턴스를 세어 `partial` 을 처리한다.
10. **검증 순서.** 새 결정 task 는 ① 대표 사례 5~10개로 답과 확률을 눈으로 확인 → ② 임계값 결정 → ③ `when:` 에 연결. 확률이 전부 0.5 근처면 `state` 가 부족하거나 질문이 모호한 것이므로 자료와 지시문을 먼저 고친다.
**`provider: openai` — OpenAI Decisions API** (`POST /v1/decisions`, 2026-10-22 정식, 모델 `gpt-6-luna`)
같은 `jev:` 블록에 `provider: openai` 만 추가하면 백엔드가 요청을 변환해 보내고 응답을 JEV 형태로 되돌려 주므로,
후속 task 의 `{{prev.X.answers.<q>.choice|noul|score}}` 참조는 그대로 동작한다. 키는 `OPENAI_API_KEY` 를 쓴다.
```yaml
jev:
provider: openai
model: gpt-6-luna # 선택. 생략 또는 jev-* 이면 gpt-6-luna
prompt_cache_key: "{{stage}}:gate" # 선택. 같은 state 를 여러 task 가 반복 판정할 때 캐시 공유 (≥1,024 토큰 prefix)
state: "{{prev.Task_assess_bundle.summary}}"
questions: { ... 동일 ... }
```
| 변환 | JEV | OpenAI |
|---|---|---|
| 입력 | `state` | `input` (객체·배열은 JSON 문자열로) |
| 예/아니오 | `noul` (criteria 는 지시문에 합쳐짐) | `predicate` → 답은 `noul` 과 `probability` 둘 다 채움 |
| 선택 | `criteria {값: 설명}` | `choices [{value, description}]` |
| 점수 | `criteria [라벨…]` 1~10단계 | `levels [{label, description}]` **2~10단계** (1단계는 거부) |
| 답 | `answers` 매핑 | 매핑으로 되돌림. score 에는 `legend` 추가, 거부는 `{type: refusal}` |
| 미지원 | — | `assets`/`box`(이미지), `long_context` 헤더 |
usage 는 provider `openai`, 모델 `gpt-6-luna` 로 기록되고 캐시 읽기/쓰기 토큰도 반영된다. 가격은 입력 $0.10/M(캐시 읽기 $0.01/M), 출력 무료.
JEV($0.042/M)보다 비싸지만 요청당 질문 400개, 프롬프트 캐시가 되므로 같은 자료에 판정을 많이 묶는 task 에 유리하다. 원본 응답은 `raw` 에 그대로 남는다.
**1.14 추가 기능 — 이미지와 box 질문** (텍스트 판정에는 불필요. 도면·캡처 판정에만):
```yaml
jev:
model: jev-1.14.0
state: "아래 서류 이미지를 보고 판단하라: {{doc_img}}" # placeholder 가 이미지로 치환된다
assets:
"{{doc_img}}": {type: image, format: png, data_base64: "<base64>"} # png|jpg|jpeg, base64 인라인
questions:
has_seal: {type: noul, instructions: "직인이 찍혀 있는가"}
seal_pos: {type: box, instructions: "직인의 위치"} # box 는 Jev 1.14 이상, 답은 {top,bottom,left,right} 0~1 비율 + confidence
```
assets 나 box 가 있으면 백엔드가 `TypeSafe-Danger-Zone-Images: true` 헤더를 자동으로 붙인다. placeholder 는 `state`·`instructions`·`criteria` 어디에나 쓸 수 있고, 이미지도 입력 토큰으로 과금된다. base64 는 YAML 에 직접 넣지 말고 앞 task(code)가 만들어 `{{prev.*}}` 로 넘긴다.
### 3.5 조건부 Task (map 전용) ### 3.5 조건부 Task (map 전용)
@@ -656,6 +730,7 @@ Direct MCP 처럼 **별도 task 유형 `jev:`** 로 쓴다. 프롬프트·도구
| `{{prev.task_name}}` | 모든 task | 이전 task 의 전체 출력 (stdout JSON 자동 파싱) | | `{{prev.task_name}}` | 모든 task | 이전 task 의 전체 출력 (stdout JSON 자동 파싱) |
| `{{prev.task_name.field}}` | 모든 task | 이전 task 출력의 특정 필드 | | `{{prev.task_name.field}}` | 모든 task | 이전 task 출력의 특정 필드 |
| `{{prev.task_name.nested.field}}` | 모든 task | 중첩 필드 접근 (dot-notation) | | `{{prev.task_name.nested.field}}` | 모든 task | 중첩 필드 접근 (dot-notation) |
| `{{prev.Task_X_0}}`, `{{prev.Task_X_1}}` … | `wait_until: ["all Task_X_*"]` 집계자 | 완료된 fan-out 인스턴스 결과 (실패·스킵 인스턴스는 없음) |
| `{{stages.<stage_name>}}` | stage 간 | 이전 stage 의 output 전체 (`apply_stage_context`) | | `{{stages.<stage_name>}}` | stage 간 | 이전 stage 의 output 전체 (`apply_stage_context`) |
| `{{stages.<stage_name>.field}}` | stage 간 | 이전 stage output 의 특정 필드 | | `{{stages.<stage_name>.field}}` | stage 간 | 이전 stage output 의 특정 필드 |
| `{{map_results}}` | reduce task | map 전체 결과 (JSON 문자열) | | `{{map_results}}` | reduce task | map 전체 결과 (JSON 문자열) |
@@ -1010,7 +1085,7 @@ OpenAI 는 요청 prefix 가 같으면 서버가 자동으로 캐시하지만(
| `llm_prompt_cache_key` (없으면 자동) | `prompt_cache_key` | 라우팅 키. fan-out 샤드(`Task_X_1`, `Task_X_2`…)는 자동 키 `<stage>:<Task_X>` 를 공유해 같은 캐시를 탄다. 명시값은 그대로 전송. GPT-5.6+ 에선 집계용(선택)이고 캐시 적중 자체는 prefix 일치로 결정 | | `llm_prompt_cache_key` (없으면 자동) | `prompt_cache_key` | 라우팅 키. fan-out 샤드(`Task_X_1`, `Task_X_2`…)는 자동 키 `<stage>:<Task_X>` 를 공유해 같은 캐시를 탄다. 명시값은 그대로 전송. GPT-5.6+ 에선 집계용(선택)이고 캐시 적중 자체는 prefix 일치로 결정 |
| `cache_control.mode: auto` (기본) | `prompt_cache_options: {mode: implicit}` + 명시 breakpoint 최대 3개 | implicit 가 breakpoint 1개를 쓰므로 명시 breakpoint 는 3개까지 | | `cache_control.mode: auto` (기본) | `prompt_cache_options: {mode: implicit}` + 명시 breakpoint 최대 3개 | implicit 가 breakpoint 1개를 쓰므로 명시 breakpoint 는 3개까지 |
| `cache_control.mode: explicit` | `prompt_cache_options: {mode: explicit}` + 명시 breakpoint | 서버 자동 breakpoint 없음. breakpoint 위치가 곧 캐시 경계 — 적중률은 올라가지만 위치를 잘못 잡으면 전혀 안 맞는다 | | `cache_control.mode: explicit` | `prompt_cache_options: {mode: explicit}` + 명시 breakpoint | 서버 자동 breakpoint 없음. breakpoint 위치가 곧 캐시 경계 — 적중률은 올라가지만 위치를 잘못 잡으면 전혀 안 맞는다 |
| `cache_control.ttl: 30m` | `prompt_cache_options.ttl: "30m"` | GPT-5.6+ 는 `30m` 만 허용(최소 보존). 다른 값은 경고 후 `30m` 으로 보냄 | | `cache_control.ttl: 30m` | `prompt_cache_options.ttl: "30m"` | GPT-5.6+ 는 `30m`(기본, 쓰기 1.25x) 또는 `12h`(responses 전용, 쓰기 2.5x, 읽기 단가 동일). 다른 값은 경고 후 `30m` 으로 보냄 |
| `cache_control.prewarm: true` | `prompt_cache_options.prewarm: true` | 첫 호출에서 캐시를 미리 만들 때 | | `cache_control.prewarm: true` | `prompt_cache_options.prewarm: true` | 첫 호출에서 캐시를 미리 만들 때 |
| `cache_control.breakpoints` | 메시지 블록의 `prompt_cache_breakpoint: {mode: explicit}` | 기본 `["system", "prefix"]`. 값: `system` = 마지막 system 메시지 끝, `prefix` = **공통 부분 끝**(아래 설명), `user` = 마지막 user 메시지 끝. assistant/tool 메시지에는 찍지 않는다 | | `cache_control.breakpoints` | 메시지 블록의 `prompt_cache_breakpoint: {mode: explicit}` | 기본 `["system", "prefix"]`. 값: `system` = 마지막 system 메시지 끝, `prefix` = **공통 부분 끝**(아래 설명), `user` = 마지막 user 메시지 끝. assistant/tool 메시지에는 찍지 않는다 |
| `cache_control.retention: in_memory \| 24h` | `prompt_cache_retention` | GPT-5.6 **이전** 모델(gpt-5.4, o-series 등) 전용. 5.6+ 에선 무시 | | `cache_control.retention: in_memory \| 24h` | `prompt_cache_retention` | GPT-5.6 **이전** 모델(gpt-5.4, o-series 등) 전용. 5.6+ 에선 무시 |
@@ -1258,6 +1333,7 @@ section0.xml의 각 `<hp:p>` 태그는 `paraPrIDRef`로 header.xml의 `<hh:paraP
- [ ] Fan-out 인스턴스의 `preflight_files` 항목 중 정적 path 는 자동으로 cache 공유 영역에 inline 됨 (인스턴스별 path 는 `{{item.*}}` 사용) - [ ] Fan-out 인스턴스의 `preflight_files` 항목 중 정적 path 는 자동으로 cache 공유 영역에 inline 됨 (인스턴스별 path 는 `{{item.*}}` 사용)
- [ ] LLM-based task 에 외부 도구 호출 금지 정책이 있으면 `preflight: false` 명시 - [ ] LLM-based task 에 외부 도구 호출 금지 정책이 있으면 `preflight: false` 명시
- [ ] 분류·채점·예/아니오 판정만 필요한 단계는 LLM 대신 `jev:` task (§3.4) — 텍스트 생성 없음, 입력 토큰만 과금. 선택지 `criteria` 를 구체적으로 적고 `state`+질문 ≤ 32K 토큰 확인 - [ ] 분류·채점·예/아니오 판정만 필요한 단계는 LLM 대신 `jev:` task (§3.4) — 텍스트 생성 없음, 입력 토큰만 과금. 선택지 `criteria` 를 구체적으로 적고 `state`+질문 ≤ 32K 토큰 확인
- [ ] 결정 task 작성 규칙(§3.4): `state` 는 판정 자료만, 질문 하나에 판단 하나, choice 는 배타적 선택지+설명, score 는 낮음→높음, 임계값은 confidence 와 함께 `when:` 에, 임계값을 튜닝했으면 provider·모델 버전 고정
--- ---
@@ -1396,17 +1472,18 @@ python3 /tmp/merge_stages.py
llm_prompt_cache_key: S2:Task_B # 선택 (OpenAI). 비우면 "<stage>:<task base-name>" 자동 — fan-out 샤드가 같은 키를 공유 llm_prompt_cache_key: S2:Task_B # 선택 (OpenAI). 비우면 "<stage>:<task base-name>" 자동 — fan-out 샤드가 같은 키를 공유
cache_control: # Gemini: 네이티브 캐시. Anthropic: Messages API 마커(§6.5.3). OpenAI: prompt_cache_options + breakpoint(§6.5.2) cache_control: # Gemini: 네이티브 캐시. Anthropic: Messages API 마커(§6.5.3). OpenAI: prompt_cache_options + breakpoint(§6.5.2)
mode: auto # auto | explicit mode: auto # auto | explicit
ttl: 30m # OpenAI GPT-5.6+: "30m" 만. Anthropic: 5m | 1h. Gemini: 5m / 10m / 1h / 2h ttl: 30m # OpenAI GPT-5.6+: "30m" | "12h"(responses 전용). Anthropic: 5m | 1h. Gemini: 5m / 10m / 1h / 2h
breakpoints: [system, prefix] # OpenAI: system | prefix | user (최대 3개). Anthropic: system | prefix | user | tools (최대 4개, auto 면 3개) breakpoints: [system, prefix] # OpenAI: system | prefix | user (최대 3개). Anthropic: system | prefix | user | tools (최대 4개, auto 면 3개)
``` ```
| YAML | provider 별로 백엔드가 보내는 것 | | YAML | provider 별로 백엔드가 보내는 것 |
|---|---| |---|---|
| `llm_reasoning` | OpenAI `reasoning_effort`(completions) / `reasoning.effort`(responses), Anthropic `output_config.effort`, Google `thinkingConfig.thinkingLevel` | | `llm_reasoning` | `low\|medium\|high` 또는 숫자(예산). OpenAI `reasoning_effort`(completions) / `reasoning.effort`(responses), Anthropic `output_config.effort`(4.5 이하는 `budget_tokens`), Google 3.x `thinking_level`(모델별 허용값, §3.1 주의. 숫자는 티어로 변환) / 2.5 이하 `thinking_budget`(숫자 그대로) |
| `llm_token_limit` | OpenAI responses `max_output_tokens` / chat `max_completion_tokens`(gpt-5/6·o·reasoning) 또는 `max_tokens`, Anthropic `max_tokens`(미지정 시 16000), Gemini `max_output_tokens`. OpenAI·Anthropic 은 사고 토큰 포함 상한, Gemini 는 본문만. OpenAI·Gemini 는 미지정 시 전송 안 함 |
| `llm_prompt_cache_key` | OpenAI `prompt_cache_key`. `Task_X_1`, `Task_X_2`… 샤드는 자동으로 `<stage>:<Task_X>` 를 공유하므로 다른 묶음이 필요할 때만 지정 | | `llm_prompt_cache_key` | OpenAI `prompt_cache_key`. `Task_X_1`, `Task_X_2`… 샤드는 자동으로 `<stage>:<Task_X>` 를 공유하므로 다른 묶음이 필요할 때만 지정 |
| `cache_control.mode: auto` | OpenAI GPT-5.6+(gpt-6.x, gpt-6.1-sol): `prompt_cache_options {mode: implicit}` + 메시지 최대 3개에 명시 `prompt_cache_breakpoint` | | `cache_control.mode: auto` | OpenAI GPT-5.6+(gpt-6.x, gpt-6.1-sol): `prompt_cache_options {mode: implicit}` + 메시지 최대 3개에 명시 `prompt_cache_breakpoint` |
| `cache_control.mode: explicit` | `prompt_cache_options {mode: explicit}`. 서버 자동 breakpoint 없음 → breakpoint 위치가 적중 여부를 전부 결정 | | `cache_control.mode: explicit` | `prompt_cache_options {mode: explicit}`. 서버 자동 breakpoint 없음 → breakpoint 위치가 적중 여부를 전부 결정 |
| `cache_control.ttl` | GPT-5.6+: `30m` 만 (다른 값은 `30m` 으로 강제). Gemini/Anthropic: 지정값 그대로 | | `cache_control.ttl` | GPT-5.6+: `30m` 또는 `12h`(responses 전용, 쓰기 2.5x; 다른 값은 `30m` 으로 강제). Gemini/Anthropic: 지정값 그대로 |
| `cache_control.breakpoints` | `system` = 마지막 system 메시지 끝, `prefix` = 첫 호출 대화(시스템+프롬프트+preflight 파일) 끝, `user` = 마지막 user 메시지 끝, `tools`(Anthropic 만) = 마지막 tool 정의. OpenAI 는 assistant/tool 메시지에 찍지 않음 | | `cache_control.breakpoints` | `system` = 마지막 system 메시지 끝, `prefix` = 첫 호출 대화(시스템+프롬프트+preflight 파일) 끝, `user` = 마지막 user 메시지 끝, `tools`(Anthropic 만) = 마지막 tool 정의. OpenAI 는 assistant/tool 메시지에 찍지 않음 |
| `cache_control.retention` | OpenAI **5.6 이전**(gpt-5.4, o-series): `prompt_cache_retention in_memory \| 24h`. 5.6+ 에선 무시 | | `cache_control.retention` | OpenAI **5.6 이전**(gpt-5.4, o-series): `prompt_cache_retention in_memory \| 24h`. 5.6+ 에선 무시 |
| Anthropic `cache_control` | 네이티브 Messages API 의 `ephemeral` 마커. `auto` = system 마커 + top-level 자동 캐시, `explicit` = breakpoints 만. `llm_reasoning` 은 4.6+ adaptive thinking + effort, 4.5 이하 budget_tokens. 모델별 최소 캐시 길이(Haiku 4.5 는 4,096 토큰) 주의 — §6.5.3 | | Anthropic `cache_control` | 네이티브 Messages API 의 `ephemeral` 마커. `auto` = system 마커 + top-level 자동 캐시, `explicit` = breakpoints 만. `llm_reasoning` 은 4.6+ adaptive thinking + effort, 4.5 이하 budget_tokens. 모델별 최소 캐시 길이(Haiku 4.5 는 4,096 토큰) 주의 — §6.5.3 |
@@ -25,7 +25,8 @@
## Candidate and calculation boundary ## Candidate and calculation boundary
- Emit fact candidates, opposing candidates, defense triggers, calculation requests, dependency references, and review items only when supported by the slice. - Emit fact candidates, opposing candidates, defense triggers, calculation requests, dependency references, and review items only when supported by the slice.
- A calculation request records operands, missing operands, source references, the applicable calculator ID, and law-version needs. Stage 1 does not select an unsupported legal rate, infer a missing operand, or declare a final claim amount. - A calculation request records exactly `calculation_domain`, `completeness`, `source_refs`, and `review_code`. Record a missing operand as `completeness` `partial`, `blocked`, or `deferred` with a `review_code`. Stage 1 does not select an unsupported legal rate, infer a missing operand, or declare a final claim amount.
- Legal effect type rule (this takes precedence over any domain overlay wording): if a type in the slice's `domain_declarations.structure_type_ids` fits, use that exact id with `registered: true`. If none fits, keep the effect candidate. Do not drop it and do not force it into `general_legal_effect`. Write your own lower_snake_case `type_id` with `registered: false` and `review_code: UNREGISTERED_EFFECT_TYPE_REVIEW`. `unregistered_effect_type` is not a `type_id`.
- Sparse output is permitted only for optional empty values. Meaningful `false`, `0`, conflicts, missing-required status, and review flags must be preserved. - Sparse output is permitted only for optional empty values. Meaningful `false`, `0`, conflicts, missing-required status, and review flags must be preserved.
## Output and writer boundary ## Output and writer boundary
@@ -1126,7 +1126,7 @@
}, },
{ {
"path": "domains/_common/common_worker_contract.md", "path": "domains/_common/common_worker_contract.md",
"sha256": "f133c54c5a9353ae14efc4d7a27d9bee18872b6727713a9a107778eef8990fb1" "sha256": "4dd1bfcb12fef1a2077d670d1d87ffa67f2258b272fa7a0744ddd0692dd7367d"
}, },
{ {
"path": "law_versions/_law_source_index.json", "path": "law_versions/_law_source_index.json",
@@ -1466,11 +1466,11 @@
}, },
{ {
"path": "signals/adapters/s3_domain_seed_adapter.py", "path": "signals/adapters/s3_domain_seed_adapter.py",
"sha256": "0aa58a1dd69bf1653d444477176303ff75ab84052a3162089160669b59d5373f" "sha256": "0372ac56e068206ff0d7ee30e3d88e79fc4afec6cf256dede643f70bb5de79a5"
}, },
{ {
"path": "signals/adapters/s3_domain_seed_adapter.txt", "path": "signals/adapters/s3_domain_seed_adapter.txt",
"sha256": "0aa58a1dd69bf1653d444477176303ff75ab84052a3162089160669b59d5373f" "sha256": "0372ac56e068206ff0d7ee30e3d88e79fc4afec6cf256dede643f70bb5de79a5"
}, },
{ {
"path": "signals/adapters/s3_envelope_migration_adapter.py", "path": "signals/adapters/s3_envelope_migration_adapter.py",
@@ -1522,11 +1522,11 @@
}, },
{ {
"path": "signals/compiler/signal_compiler.py", "path": "signals/compiler/signal_compiler.py",
"sha256": "b8d4026dcc302321f6580fe1f96d168722635203a8e85d10d1e5b2d5f2561222" "sha256": "faf03415c93cf05ba464f10ba33794fd59db804e4fb427442c1bc61ce170e25b"
}, },
{ {
"path": "signals/compiler/signal_compiler.txt", "path": "signals/compiler/signal_compiler.txt",
"sha256": "b8d4026dcc302321f6580fe1f96d168722635203a8e85d10d1e5b2d5f2561222" "sha256": "faf03415c93cf05ba464f10ba33794fd59db804e4fb427442c1bc61ce170e25b"
}, },
{ {
"path": "signals/compiler/signal_gate.py", "path": "signals/compiler/signal_gate.py",
@@ -1654,11 +1654,11 @@
}, },
{ {
"path": "signals/emitters/emitter_runtime.py", "path": "signals/emitters/emitter_runtime.py",
"sha256": "160d717ef77fedfa76ab9b309894f6a711af320387a5cfe619ba166d8eb6e279" "sha256": "0aa03059d1433171cf0288e6e94bd76ff9b9d27da4f33f981f02fc9b5f1718e7"
}, },
{ {
"path": "signals/emitters/emitter_runtime.txt", "path": "signals/emitters/emitter_runtime.txt",
"sha256": "160d717ef77fedfa76ab9b309894f6a711af320387a5cfe619ba166d8eb6e279" "sha256": "0aa03059d1433171cf0288e6e94bd76ff9b9d27da4f33f981f02fc9b5f1718e7"
}, },
{ {
"path": "signals/schemas/asset_right_state_signals.schema.json", "path": "signals/schemas/asset_right_state_signals.schema.json",
@@ -1738,7 +1738,7 @@
}, },
{ {
"path": "stage1_runtime/bo_surface_projection_policy.v1.json", "path": "stage1_runtime/bo_surface_projection_policy.v1.json",
"sha256": "b3eba1d868ff543d761993396ada4910bd032a6762a8853403426655a3e9505a" "sha256": "d96e96d2178060e935c9309f0dfb59c5567d47ebbb9774d76335358724dab3c2"
}, },
{ {
"path": "stage1_runtime/domain_fanout_planner.py", "path": "stage1_runtime/domain_fanout_planner.py",
@@ -1750,23 +1750,23 @@
}, },
{ {
"path": "stage1_runtime/domain_slice_compiler.py", "path": "stage1_runtime/domain_slice_compiler.py",
"sha256": "c865eb281e201c5400d7b0d922b8d70f1df1d7de2001e66e3274fc5550a72526" "sha256": "68451f7ded3e597ca4da592d68595b58ed06919f9f48ffe20249328ad5402610"
}, },
{ {
"path": "stage1_runtime/domain_slice_compiler.txt", "path": "stage1_runtime/domain_slice_compiler.txt",
"sha256": "c865eb281e201c5400d7b0d922b8d70f1df1d7de2001e66e3274fc5550a72526" "sha256": "68451f7ded3e597ca4da592d68595b58ed06919f9f48ffe20249328ad5402610"
}, },
{ {
"path": "stage1_runtime/fact_ledger_compiler.py", "path": "stage1_runtime/fact_ledger_compiler.py",
"sha256": "f6c4b476f4974104cd57accd559dcd91b31c80391077846dc3920d443c59a996" "sha256": "81df1130a3ab170ff548665547369f8ef5a657c5a1e14183fdabe472aa490f64"
}, },
{ {
"path": "stage1_runtime/fact_ledger_compiler.txt", "path": "stage1_runtime/fact_ledger_compiler.txt",
"sha256": "f6c4b476f4974104cd57accd559dcd91b31c80391077846dc3920d443c59a996" "sha256": "81df1130a3ab170ff548665547369f8ef5a657c5a1e14183fdabe472aa490f64"
}, },
{ {
"path": "stage1_runtime/fact_ledger_policy.v1.json", "path": "stage1_runtime/fact_ledger_policy.v1.json",
"sha256": "fea0cea48d862c6c76774d6fee8ef84401a1b9fd753e86ccca76df32259523f7" "sha256": "08fad0b20e299063b502fd2a0ae1877b9a7074bdce5391110ea5d632c53787f9"
}, },
{ {
"path": "stage1_runtime/prompt_compiler.py", "path": "stage1_runtime/prompt_compiler.py",
@@ -1814,35 +1814,35 @@
}, },
{ {
"path": "stage1_runtime/seed_admission_policy.v1.json", "path": "stage1_runtime/seed_admission_policy.v1.json",
"sha256": "af048b2d1c9d01c7943658046dc3e8e9f3caee0901635dc344095982a7e05ba4" "sha256": "b41c7a4b51a0859104d7a2a5edb3b9c3db41d3f1481338fb1a0526d746f77522"
}, },
{ {
"path": "stage1_runtime/stage_a_context_builder.py", "path": "stage1_runtime/stage_a_context_builder.py",
"sha256": "68d984f9d565034c73721dc97c5aab0f9cdb8a8b46e1bf13eabd8c136ec4bcc0" "sha256": "1943493e09d674fc8b8168967087ef831c578607cfb1d6aa77e33771a0bc9f4c"
}, },
{ {
"path": "stage1_runtime/stage_a_context_builder.txt", "path": "stage1_runtime/stage_a_context_builder.txt",
"sha256": "68d984f9d565034c73721dc97c5aab0f9cdb8a8b46e1bf13eabd8c136ec4bcc0" "sha256": "1943493e09d674fc8b8168967087ef831c578607cfb1d6aa77e33771a0bc9f4c"
}, },
{ {
"path": "stage1_runtime/structure_index_compiler.py", "path": "stage1_runtime/structure_index_compiler.py",
"sha256": "c400adfb7c58e340a17e67aebcdc4a7cf92c35c422f418451c79ce7c531d201f" "sha256": "fd2f8de3df303f49a337d894c4e5017d06f24cd54799a0f8f66396394be65acb"
}, },
{ {
"path": "stage1_runtime/structure_index_compiler.txt", "path": "stage1_runtime/structure_index_compiler.txt",
"sha256": "c400adfb7c58e340a17e67aebcdc4a7cf92c35c422f418451c79ce7c531d201f" "sha256": "fd2f8de3df303f49a337d894c4e5017d06f24cd54799a0f8f66396394be65acb"
}, },
{ {
"path": "stage1_runtime/structure_index_policy.v1.json", "path": "stage1_runtime/structure_index_policy.v1.json",
"sha256": "823a7e734a7bc9433966a5629a5a0b153a067c92d8570072fa14a5c42bb722bd" "sha256": "8eeedbcae6f3e4f648aa485b8620b23f4fdc16f43e0b678f224a403e915b1689"
}, },
{ {
"path": "stage1_runtime/worker_output_validator.py", "path": "stage1_runtime/worker_output_validator.py",
"sha256": "e5b46f929082faf621731ffb8f4864ccb9bba461ab23caa56d1bcfe5b073fd9d" "sha256": "5d13a3a70cad1ee73e63c90715feb15b9fdb25e132d93031358a51305af3bed7"
}, },
{ {
"path": "stage1_runtime/worker_output_validator.txt", "path": "stage1_runtime/worker_output_validator.txt",
"sha256": "e5b46f929082faf621731ffb8f4864ccb9bba461ab23caa56d1bcfe5b073fd9d" "sha256": "5d13a3a70cad1ee73e63c90715feb15b9fdb25e132d93031358a51305af3bed7"
}, },
{ {
"path": "tools/s3_router_v2.py", "path": "tools/s3_router_v2.py",
@@ -19,24 +19,102 @@ def _liability_fanout_domains() -> set[str]:
return {item["domain_id"] for item in contract["sg08_liability_fanout_domains"]} return {item["domain_id"] for item in contract["sg08_liability_fanout_domains"]}
def _rows(value: Any) -> list[Any]:
return value if isinstance(value, list) else []
def _payload(row: dict[str, Any]) -> dict[str, Any]:
value = row.get("payload")
return value if isinstance(value, dict) else {}
def _source_fields(refs: list[str], universe: dict[str, Any]) -> tuple[list[str], list[str]]: def _source_fields(refs: list[str], universe: dict[str, Any]) -> tuple[list[str], list[str]]:
evidence = set(universe.get("evidence_ids", [])) evidence = set(universe.get("evidence_ids", []))
meeting = set(universe.get("meeting_clause_ids", [])) meeting = set(universe.get("meeting_clause_ids", []))
return sorted(set(refs) & evidence), sorted(set(refs) & meeting) return sorted(set(refs) & evidence), sorted(set(refs) & meeting)
_SEED_ROW_KEYS = ("source_id", "source_kind", "excerpt", "payload")
_EFFECT_ROW_KEYS = ("type_id", "source_refs", "registered", "review_code", "candidate_ref", "bo_absent")
_CALCULATION_ROW_KEYS = ("calculation_domain", "completeness", "source_refs", "review_code")
def _schema_row(row: dict[str, Any], keys: tuple[str, ...]) -> dict[str, Any]:
"""S0 restores raw rows. Keys outside the seed schema must not reach signal consumers.
The worker's values stay in worker_extra as JSON text, so no key inside it can act as a field.
"""
kept = {name: value for name, value in row.items() if name in keys}
extra = {name: value for name, value in row.items() if name not in keys}
if extra:
kept["worker_extra"] = json.dumps(extra, ensure_ascii=False, sort_keys=True).encode("utf-8", "backslashreplace").decode("utf-8")
return kept
def _without(row: dict[str, Any], key: str) -> dict[str, Any]:
return {name: value for name, value in row.items() if name != key}
def _candidate(domain_id: str, seed_id: str, record_type: str, source_refs: list[str], details: dict[str, Any], universe: dict[str, Any], status: str = "inferred") -> dict[str, Any]: def _candidate(domain_id: str, seed_id: str, record_type: str, source_refs: list[str], details: dict[str, Any], universe: dict[str, Any], status: str = "inferred") -> dict[str, Any]:
evidence, meeting = _source_fields(source_refs, universe) evidence, meeting = _source_fields(source_refs, universe)
return { return {
"record_type": record_type, "status": status, "domain_ids": [domain_id], "source_bo_ids": [], "record_type": record_type, "status": status, "domain_ids": [domain_id], "source_bo_ids": [],
"source_fact_ids": [], "evidence_refs": evidence, "meeting_clause_refs": meeting, "source_fact_ids": [], "evidence_refs": evidence, "meeting_clause_refs": meeting,
"negative_or_conflicting_refs": sorted(set(details.get("negative_or_conflicting_refs", []))), "negative_or_conflicting_refs": sorted({str(ref) for ref in _rows(details.get("negative_or_conflicting_refs"))}
& set(universe.get("all_source_refs", []))),
"law_version_refs": [], "confidence": "medium", "proof_grade": "client_statement" if meeting and not evidence else ("document_indirect" if evidence else "ungraded"), "law_version_refs": [], "confidence": "medium", "proof_grade": "client_statement" if meeting and not evidence else ("document_indirect" if evidence else "ungraded"),
"review_required": status in {"contested", "missing_required", "review"}, "review_required": status in {"contested", "missing_required", "review"},
"details": {"source_seed_id": seed_id, **deepcopy(details)}, "details": {"source_seed_id": seed_id, **_schema_row(deepcopy(details), _EFFECT_ROW_KEYS if record_type == "legal_effect_route" else _SEED_ROW_KEYS)},
} }
_COMPLETENESS = {"ready", "partial", "blocked", "deferred"}
_SLOT_STATUS = {"filled", "partial", "missing", "conflicted"}
# Keys seed v3 does not define on a calculation request. SG-11 carries the row as is, so the gate would halt on them.
_CALCULATION_REF_KEYS = ("source_bo_ids", "source_fact_ids", "law_version_refs", "negative_or_conflicting_refs")
_CALCULATION_GATED_KEYS = ("proof_grade", "confidence")
# Same table as check_domain_node in compiler/signal_gate: key -> universe list it must belong to.
_ENVELOPE_LIST_REFS = {
"source_bo_ids": "bo_ids", "related_bo_ids": "bo_ids", "source_fact_ids": "fact_ids",
"evidence_refs": "evidence_ids", "related_evidence_indexes": "evidence_ids",
"meeting_clause_refs": "meeting_clause_ids", "law_version_refs": "law_version_ids",
"source_refs": "all_source_refs", "negative_or_conflicting_refs": "all_source_refs",
}
_ENVELOPE_SCALAR_REFS = {"source_id": "all_source_refs", "bo_id": "bo_ids"}
def _known_refs_only(node: Any, universe: dict[str, Any], removed: list[dict[str, str]]) -> Any:
"""Copy of an envelope row without refs outside the source universe. The row itself stays.
S0 takes rows from the raw seed, and the gate checks every ref in an envelope. A bad ref must not
halt the run. Removed values go to `removed`, which the envelope keeps in extensions.unverified_refs.
"""
if isinstance(node, list):
return [_known_refs_only(item, universe, removed) for item in node]
if not isinstance(node, dict):
return deepcopy(node)
out: dict[str, Any] = {}
for key, value in node.items():
if key in _ENVELOPE_LIST_REFS and isinstance(value, list):
allowed = {str(ref) for ref in universe.get(_ENVELOPE_LIST_REFS[key], [])}
out[key] = [ref for ref in value if str(ref) in allowed]
_note_removed(removed, key, [ref for ref in value if str(ref) not in allowed])
elif key in _ENVELOPE_SCALAR_REFS and value is not None:
allowed = {str(ref) for ref in universe.get(_ENVELOPE_SCALAR_REFS[key], [])}
out[key] = value if str(value) in allowed else None
if out[key] is None:
_note_removed(removed, key, [value])
else:
out[key] = _known_refs_only(value, universe, removed)
return out
def _note_removed(removed: list[dict[str, str]], field: str, values: list[Any]) -> None:
# Keys stay "field"/"value": the gate walks extensions too and would check a real ref key.
removed.extend({"field": field, "value": str(value)} for value in values)
def adapt(inputs: dict[str, Any]) -> dict[str, Any]: def adapt(inputs: dict[str, Any]) -> dict[str, Any]:
adapted = deepcopy(inputs) adapted = deepcopy(inputs)
candidates = adapted.setdefault("signal_candidates", {}) candidates = adapted.setdefault("signal_candidates", {})
@@ -45,6 +123,8 @@ def adapt(inputs: dict[str, Any]) -> dict[str, Any]:
raw_outputs = adapted.get("domain_seed_outputs", {}) raw_outputs = adapted.get("domain_seed_outputs", {})
deprecated_envelopes = adapted.get("deprecated_domain_signal_envelopes", {}) deprecated_envelopes = adapted.get("deprecated_domain_signal_envelopes", {})
wrappers = list(raw_outputs.values()) if isinstance(raw_outputs, dict) else list(raw_outputs or []) wrappers = list(raw_outputs.values()) if isinstance(raw_outputs, dict) else list(raw_outputs or [])
# SG-01 owns these two values. A worker echo may be malformed, and R0 only reviews it.
activation = adapted["domain_activation_manifest"]["domain_activation_manifest"]
for wrapper in wrappers: for wrapper in wrappers:
if not isinstance(wrapper, dict) or not isinstance(wrapper.get("stage_b_domain_bo_seed_output"), dict): if not isinstance(wrapper, dict) or not isinstance(wrapper.get("stage_b_domain_bo_seed_output"), dict):
continue continue
@@ -58,56 +138,88 @@ def adapt(inputs: dict[str, Any]) -> dict[str, Any]:
slot_rows: list[Any] = [] slot_rows: list[Any] = []
calculation_refs: list[str] = [] calculation_refs: list[str] = []
dependencies: set[str] = set() dependencies: set[str] = set()
review_items: list[Any] = list(root.get("unknown_or_unrouted_reviews", [])) removed: list[dict[str, str]] = []
for seed in root.get("bo_seed_candidates", []): review_items: list[Any] = _known_refs_only(_rows(root.get("unknown_or_unrouted_reviews")), universe, removed)
for position, seed in enumerate(_rows(root.get("bo_seed_candidates")), start=1):
if not isinstance(seed, dict): if not isinstance(seed, dict):
continue continue
seed_id = str(seed.get("seed_id") or "unknown-seed") seed_id = str(seed.get("seed_id") or "unknown-seed")
seed_refs = [str(ref) for ref in seed.get("source_refs", [])] # R0 candidate_ref formula (worker list position). S0 stamps it in memory, bo_absent too.
for fact in seed.get("element_fact_candidates", []): candidate_ref = str(seed.get("candidate_ref") or f"{domain_id}:{position:03d}")
bo_mark = {"bo_absent": True} if seed.get("bo_absent") is True else {}
seed_refs = [str(ref) for ref in _rows(seed.get("source_refs"))]
for fact in _rows(seed.get("element_fact_candidates")):
if isinstance(fact, dict): if isinstance(fact, dict):
refs = [str(fact.get("source_id"))] if fact.get("source_id") else seed_refs refs = [str(fact.get("source_id"))] if fact.get("source_id") else seed_refs
candidates.setdefault("SG-05", []).append(_candidate(domain_id, seed_id, "domain_relation_atom", refs, fact, universe, str(fact.get("payload", {}).get("status") or "inferred"))) candidates.setdefault("SG-05", []).append(_candidate(domain_id, seed_id, "domain_relation_atom", refs, fact, universe, str(_payload(fact).get("status") or "inferred")))
if domain_id in _liability_fanout_domains(): if domain_id in _liability_fanout_domains():
candidates.setdefault("SG-08", []).append(_candidate(domain_id, seed_id, "liability_element", refs, fact, universe, str(fact.get("payload", {}).get("status") or "inferred"))) candidates.setdefault("SG-08", []).append(_candidate(domain_id, seed_id, "liability_element", refs, fact, universe, str(_payload(fact).get("status") or "inferred")))
element_rows.append(deepcopy(fact)) element_rows.append(_schema_row(_known_refs_only(fact, universe, removed), _SEED_ROW_KEYS))
for fact in seed.get("opposing_fact_candidates", []): for fact in _rows(seed.get("opposing_fact_candidates")):
if isinstance(fact, dict): if isinstance(fact, dict):
opposing_rows.append(deepcopy(fact)) opposing_rows.append(_schema_row(_known_refs_only(fact, universe, removed), _SEED_ROW_KEYS))
for defense in seed.get("defense_candidates", []): for defense in _rows(seed.get("defense_candidates")):
if isinstance(defense, dict): if isinstance(defense, dict):
refs = [str(ref) for ref in defense.get("source_refs", seed_refs)] refs = seed_refs
candidates.setdefault("SG-09", []).append(_candidate(domain_id, seed_id, "defense_trigger", refs, defense, universe, str(defense.get("status") or "inferred"))) candidates.setdefault("SG-09", []).append(_candidate(domain_id, seed_id, "defense_trigger", refs, defense, universe, "inferred" if defense.get("status") in (None, "inferred", "observed") else "review"))
defense_rows.append(deepcopy(defense)) defense_rows.append(_schema_row(_known_refs_only(defense, universe, removed), _SEED_ROW_KEYS))
for request in seed.get("calculation_requests", []): for order, request in enumerate(_rows(seed.get("calculation_requests")), start=1):
if isinstance(request, dict): if isinstance(request, dict):
adapted.setdefault("calculation_requests", []).append(deepcopy(request)) # seed v3 has no request_id; this module builds both sides of the SG-11 join.
if request.get("request_id"): stamped = deepcopy(request)
calculation_refs.append(str(request["request_id"])) for key in _CALCULATION_REF_KEYS:
for effect in seed.get("legal_effect_candidates", []): value = stamped.pop(key, None)
_note_removed(removed, key, value if isinstance(value, list) else ([] if value is None else [value]))
for key in _CALCULATION_GATED_KEYS:
stamped.pop(key, None)
evidence, meeting = _source_fields([str(ref) for ref in _rows(request.get("source_refs"))], universe)
stamped = _schema_row(_without(stamped, "bo_absent"), _CALCULATION_ROW_KEYS)
stamped.update({
"request_id": f"{candidate_ref}:{order}", "domain_ids": [domain_id],
"calculation_id": request.get("calculation_domain"),
"operand_state": request["completeness"] if isinstance(request.get("completeness"), str) and request["completeness"] in _COMPLETENESS else "partial",
"evidence_refs": evidence, "meeting_clause_refs": meeting,
"candidate_ref": candidate_ref, **bo_mark,
})
adapted.setdefault("calculation_requests", []).append(stamped)
calculation_refs.append(stamped["request_id"])
for effect in _rows(seed.get("legal_effect_candidates")):
if isinstance(effect, dict): if isinstance(effect, dict):
refs = [str(ref) for ref in effect.get("source_refs", seed_refs)] refs = [str(ref) for ref in _rows(effect.get("source_refs", seed_refs))]
status = "review" if effect.get("registered") is False else "inferred" status = "review" if effect.get("registered") is False else "inferred"
candidates.setdefault("SG-13", []).append(_candidate(domain_id, seed_id, "legal_effect_route", refs, effect, universe, status)) marked = {**_without(effect, "bo_absent"), "candidate_ref": candidate_ref, **bo_mark}
for slot in seed.get("evidence_slot_status", []): candidates.setdefault("SG-13", []).append(_candidate(domain_id, seed_id, "legal_effect_route", refs, marked, universe, status))
for slot in _rows(seed.get("evidence_slot_status")):
if not isinstance(slot, dict): if not isinstance(slot, dict):
continue continue
refs = [str(ref) for ref in slot.get("source_refs", [])] refs = [str(ref) for ref in _rows(slot.get("source_refs"))]
evidence, meeting = _source_fields(refs, universe) evidence, meeting = _source_fields(refs, universe)
# R0 repairs this before S0 unless the validator crashed or admission runs in shadow mode.
status_known = isinstance(slot.get("status"), str) and slot["status"] in _SLOT_STATUS
review_code = slot.get("review_code") if isinstance(slot.get("review_code"), str) else None
slot_rows.append({ slot_rows.append({
"slot_id": str(slot.get("slot_id") or "unknown_slot"), "status": slot.get("status", "missing"), "slot_id": str(slot.get("slot_id") or "unknown_slot"),
"status": slot["status"] if status_known else "missing",
"source_fact_ids": [], "evidence_refs": evidence, "meeting_clause_refs": meeting, "source_fact_ids": [], "evidence_refs": evidence, "meeting_clause_refs": meeting,
"negative_or_conflicting_refs": [], "review_code": slot.get("review_code"), "negative_or_conflicting_refs": [],
"review_code": review_code if status_known or review_code else "SLOT_STATUS_UNMAPPED_REVIEW",
}) })
dependencies.update(str(value) for value in seed.get("dependency_refs", [])) dependencies.update(str(value) for value in _rows(seed.get("dependency_refs")) if str(value))
review_items.extend(deepcopy(seed.get("review_items", []))) review_items.extend(_known_refs_only(_rows(seed.get("review_items")), universe, removed))
extensions: dict[str, Any] = {} extensions: dict[str, Any] = {}
if isinstance(deprecated_envelopes, dict) and domain_id in deprecated_envelopes: if isinstance(deprecated_envelopes, dict) and domain_id in deprecated_envelopes:
extensions["s3_roundtrip"] = migrate_deprecated_envelope(deprecated_envelopes[domain_id]) extensions["s3_roundtrip"] = migrate_deprecated_envelope(deprecated_envelopes[domain_id])
if removed:
unique = {(item["field"], item["value"]) for item in removed}
extensions["unverified_refs"] = [{"field": field, "value": value} for field, value in sorted(unique)]
review_items.append({
"review_code": "UNVERIFIED_REF_REVIEW", "severity": "review", "source_refs": [],
"reason": "refs dropped from this envelope, kept in extensions.unverified_refs: %d" % len(unique),
})
domains[domain_id] = {"domain_signal_envelope": { domains[domain_id] = {"domain_signal_envelope": {
"schema_version": "stage1_domain_signals.v2", "domain_id": domain_id, "schema_version": "stage1_domain_signals.v2", "domain_id": domain_id,
"domain_registry_version": root.get("registry_version", "UNKNOWN"), "domain_registry_version": activation["registry_version"],
"registry_index_sha256": root.get("registry_index_sha256", "0" * 64), "registry_index_sha256": activation["registry_index_sha256"],
"status": "READY_WITH_REVIEW" if review_items else ("READY" if root.get("bo_seed_candidates") else "NO_SUPPORT"), "status": "READY_WITH_REVIEW" if review_items else ("READY" if root.get("bo_seed_candidates") else "NO_SUPPORT"),
"element_fact_candidates": element_rows, "opposing_fact_candidates": opposing_rows, "element_fact_candidates": element_rows, "opposing_fact_candidates": opposing_rows,
"defense_candidates": defense_rows, "evidence_slot_status": slot_rows, "defense_candidates": defense_rows, "evidence_slot_status": slot_rows,
@@ -19,24 +19,102 @@ def _liability_fanout_domains() -> set[str]:
return {item["domain_id"] for item in contract["sg08_liability_fanout_domains"]} return {item["domain_id"] for item in contract["sg08_liability_fanout_domains"]}
def _rows(value: Any) -> list[Any]:
return value if isinstance(value, list) else []
def _payload(row: dict[str, Any]) -> dict[str, Any]:
value = row.get("payload")
return value if isinstance(value, dict) else {}
def _source_fields(refs: list[str], universe: dict[str, Any]) -> tuple[list[str], list[str]]: def _source_fields(refs: list[str], universe: dict[str, Any]) -> tuple[list[str], list[str]]:
evidence = set(universe.get("evidence_ids", [])) evidence = set(universe.get("evidence_ids", []))
meeting = set(universe.get("meeting_clause_ids", [])) meeting = set(universe.get("meeting_clause_ids", []))
return sorted(set(refs) & evidence), sorted(set(refs) & meeting) return sorted(set(refs) & evidence), sorted(set(refs) & meeting)
_SEED_ROW_KEYS = ("source_id", "source_kind", "excerpt", "payload")
_EFFECT_ROW_KEYS = ("type_id", "source_refs", "registered", "review_code", "candidate_ref", "bo_absent")
_CALCULATION_ROW_KEYS = ("calculation_domain", "completeness", "source_refs", "review_code")
def _schema_row(row: dict[str, Any], keys: tuple[str, ...]) -> dict[str, Any]:
"""S0 restores raw rows. Keys outside the seed schema must not reach signal consumers.
The worker's values stay in worker_extra as JSON text, so no key inside it can act as a field.
"""
kept = {name: value for name, value in row.items() if name in keys}
extra = {name: value for name, value in row.items() if name not in keys}
if extra:
kept["worker_extra"] = json.dumps(extra, ensure_ascii=False, sort_keys=True).encode("utf-8", "backslashreplace").decode("utf-8")
return kept
def _without(row: dict[str, Any], key: str) -> dict[str, Any]:
return {name: value for name, value in row.items() if name != key}
def _candidate(domain_id: str, seed_id: str, record_type: str, source_refs: list[str], details: dict[str, Any], universe: dict[str, Any], status: str = "inferred") -> dict[str, Any]: def _candidate(domain_id: str, seed_id: str, record_type: str, source_refs: list[str], details: dict[str, Any], universe: dict[str, Any], status: str = "inferred") -> dict[str, Any]:
evidence, meeting = _source_fields(source_refs, universe) evidence, meeting = _source_fields(source_refs, universe)
return { return {
"record_type": record_type, "status": status, "domain_ids": [domain_id], "source_bo_ids": [], "record_type": record_type, "status": status, "domain_ids": [domain_id], "source_bo_ids": [],
"source_fact_ids": [], "evidence_refs": evidence, "meeting_clause_refs": meeting, "source_fact_ids": [], "evidence_refs": evidence, "meeting_clause_refs": meeting,
"negative_or_conflicting_refs": sorted(set(details.get("negative_or_conflicting_refs", []))), "negative_or_conflicting_refs": sorted({str(ref) for ref in _rows(details.get("negative_or_conflicting_refs"))}
& set(universe.get("all_source_refs", []))),
"law_version_refs": [], "confidence": "medium", "proof_grade": "client_statement" if meeting and not evidence else ("document_indirect" if evidence else "ungraded"), "law_version_refs": [], "confidence": "medium", "proof_grade": "client_statement" if meeting and not evidence else ("document_indirect" if evidence else "ungraded"),
"review_required": status in {"contested", "missing_required", "review"}, "review_required": status in {"contested", "missing_required", "review"},
"details": {"source_seed_id": seed_id, **deepcopy(details)}, "details": {"source_seed_id": seed_id, **_schema_row(deepcopy(details), _EFFECT_ROW_KEYS if record_type == "legal_effect_route" else _SEED_ROW_KEYS)},
} }
_COMPLETENESS = {"ready", "partial", "blocked", "deferred"}
_SLOT_STATUS = {"filled", "partial", "missing", "conflicted"}
# Keys seed v3 does not define on a calculation request. SG-11 carries the row as is, so the gate would halt on them.
_CALCULATION_REF_KEYS = ("source_bo_ids", "source_fact_ids", "law_version_refs", "negative_or_conflicting_refs")
_CALCULATION_GATED_KEYS = ("proof_grade", "confidence")
# Same table as check_domain_node in compiler/signal_gate: key -> universe list it must belong to.
_ENVELOPE_LIST_REFS = {
"source_bo_ids": "bo_ids", "related_bo_ids": "bo_ids", "source_fact_ids": "fact_ids",
"evidence_refs": "evidence_ids", "related_evidence_indexes": "evidence_ids",
"meeting_clause_refs": "meeting_clause_ids", "law_version_refs": "law_version_ids",
"source_refs": "all_source_refs", "negative_or_conflicting_refs": "all_source_refs",
}
_ENVELOPE_SCALAR_REFS = {"source_id": "all_source_refs", "bo_id": "bo_ids"}
def _known_refs_only(node: Any, universe: dict[str, Any], removed: list[dict[str, str]]) -> Any:
"""Copy of an envelope row without refs outside the source universe. The row itself stays.
S0 takes rows from the raw seed, and the gate checks every ref in an envelope. A bad ref must not
halt the run. Removed values go to `removed`, which the envelope keeps in extensions.unverified_refs.
"""
if isinstance(node, list):
return [_known_refs_only(item, universe, removed) for item in node]
if not isinstance(node, dict):
return deepcopy(node)
out: dict[str, Any] = {}
for key, value in node.items():
if key in _ENVELOPE_LIST_REFS and isinstance(value, list):
allowed = {str(ref) for ref in universe.get(_ENVELOPE_LIST_REFS[key], [])}
out[key] = [ref for ref in value if str(ref) in allowed]
_note_removed(removed, key, [ref for ref in value if str(ref) not in allowed])
elif key in _ENVELOPE_SCALAR_REFS and value is not None:
allowed = {str(ref) for ref in universe.get(_ENVELOPE_SCALAR_REFS[key], [])}
out[key] = value if str(value) in allowed else None
if out[key] is None:
_note_removed(removed, key, [value])
else:
out[key] = _known_refs_only(value, universe, removed)
return out
def _note_removed(removed: list[dict[str, str]], field: str, values: list[Any]) -> None:
# Keys stay "field"/"value": the gate walks extensions too and would check a real ref key.
removed.extend({"field": field, "value": str(value)} for value in values)
def adapt(inputs: dict[str, Any]) -> dict[str, Any]: def adapt(inputs: dict[str, Any]) -> dict[str, Any]:
adapted = deepcopy(inputs) adapted = deepcopy(inputs)
candidates = adapted.setdefault("signal_candidates", {}) candidates = adapted.setdefault("signal_candidates", {})
@@ -45,6 +123,8 @@ def adapt(inputs: dict[str, Any]) -> dict[str, Any]:
raw_outputs = adapted.get("domain_seed_outputs", {}) raw_outputs = adapted.get("domain_seed_outputs", {})
deprecated_envelopes = adapted.get("deprecated_domain_signal_envelopes", {}) deprecated_envelopes = adapted.get("deprecated_domain_signal_envelopes", {})
wrappers = list(raw_outputs.values()) if isinstance(raw_outputs, dict) else list(raw_outputs or []) wrappers = list(raw_outputs.values()) if isinstance(raw_outputs, dict) else list(raw_outputs or [])
# SG-01 owns these two values. A worker echo may be malformed, and R0 only reviews it.
activation = adapted["domain_activation_manifest"]["domain_activation_manifest"]
for wrapper in wrappers: for wrapper in wrappers:
if not isinstance(wrapper, dict) or not isinstance(wrapper.get("stage_b_domain_bo_seed_output"), dict): if not isinstance(wrapper, dict) or not isinstance(wrapper.get("stage_b_domain_bo_seed_output"), dict):
continue continue
@@ -58,56 +138,88 @@ def adapt(inputs: dict[str, Any]) -> dict[str, Any]:
slot_rows: list[Any] = [] slot_rows: list[Any] = []
calculation_refs: list[str] = [] calculation_refs: list[str] = []
dependencies: set[str] = set() dependencies: set[str] = set()
review_items: list[Any] = list(root.get("unknown_or_unrouted_reviews", [])) removed: list[dict[str, str]] = []
for seed in root.get("bo_seed_candidates", []): review_items: list[Any] = _known_refs_only(_rows(root.get("unknown_or_unrouted_reviews")), universe, removed)
for position, seed in enumerate(_rows(root.get("bo_seed_candidates")), start=1):
if not isinstance(seed, dict): if not isinstance(seed, dict):
continue continue
seed_id = str(seed.get("seed_id") or "unknown-seed") seed_id = str(seed.get("seed_id") or "unknown-seed")
seed_refs = [str(ref) for ref in seed.get("source_refs", [])] # R0 candidate_ref formula (worker list position). S0 stamps it in memory, bo_absent too.
for fact in seed.get("element_fact_candidates", []): candidate_ref = str(seed.get("candidate_ref") or f"{domain_id}:{position:03d}")
bo_mark = {"bo_absent": True} if seed.get("bo_absent") is True else {}
seed_refs = [str(ref) for ref in _rows(seed.get("source_refs"))]
for fact in _rows(seed.get("element_fact_candidates")):
if isinstance(fact, dict): if isinstance(fact, dict):
refs = [str(fact.get("source_id"))] if fact.get("source_id") else seed_refs refs = [str(fact.get("source_id"))] if fact.get("source_id") else seed_refs
candidates.setdefault("SG-05", []).append(_candidate(domain_id, seed_id, "domain_relation_atom", refs, fact, universe, str(fact.get("payload", {}).get("status") or "inferred"))) candidates.setdefault("SG-05", []).append(_candidate(domain_id, seed_id, "domain_relation_atom", refs, fact, universe, str(_payload(fact).get("status") or "inferred")))
if domain_id in _liability_fanout_domains(): if domain_id in _liability_fanout_domains():
candidates.setdefault("SG-08", []).append(_candidate(domain_id, seed_id, "liability_element", refs, fact, universe, str(fact.get("payload", {}).get("status") or "inferred"))) candidates.setdefault("SG-08", []).append(_candidate(domain_id, seed_id, "liability_element", refs, fact, universe, str(_payload(fact).get("status") or "inferred")))
element_rows.append(deepcopy(fact)) element_rows.append(_schema_row(_known_refs_only(fact, universe, removed), _SEED_ROW_KEYS))
for fact in seed.get("opposing_fact_candidates", []): for fact in _rows(seed.get("opposing_fact_candidates")):
if isinstance(fact, dict): if isinstance(fact, dict):
opposing_rows.append(deepcopy(fact)) opposing_rows.append(_schema_row(_known_refs_only(fact, universe, removed), _SEED_ROW_KEYS))
for defense in seed.get("defense_candidates", []): for defense in _rows(seed.get("defense_candidates")):
if isinstance(defense, dict): if isinstance(defense, dict):
refs = [str(ref) for ref in defense.get("source_refs", seed_refs)] refs = seed_refs
candidates.setdefault("SG-09", []).append(_candidate(domain_id, seed_id, "defense_trigger", refs, defense, universe, str(defense.get("status") or "inferred"))) candidates.setdefault("SG-09", []).append(_candidate(domain_id, seed_id, "defense_trigger", refs, defense, universe, "inferred" if defense.get("status") in (None, "inferred", "observed") else "review"))
defense_rows.append(deepcopy(defense)) defense_rows.append(_schema_row(_known_refs_only(defense, universe, removed), _SEED_ROW_KEYS))
for request in seed.get("calculation_requests", []): for order, request in enumerate(_rows(seed.get("calculation_requests")), start=1):
if isinstance(request, dict): if isinstance(request, dict):
adapted.setdefault("calculation_requests", []).append(deepcopy(request)) # seed v3 has no request_id; this module builds both sides of the SG-11 join.
if request.get("request_id"): stamped = deepcopy(request)
calculation_refs.append(str(request["request_id"])) for key in _CALCULATION_REF_KEYS:
for effect in seed.get("legal_effect_candidates", []): value = stamped.pop(key, None)
_note_removed(removed, key, value if isinstance(value, list) else ([] if value is None else [value]))
for key in _CALCULATION_GATED_KEYS:
stamped.pop(key, None)
evidence, meeting = _source_fields([str(ref) for ref in _rows(request.get("source_refs"))], universe)
stamped = _schema_row(_without(stamped, "bo_absent"), _CALCULATION_ROW_KEYS)
stamped.update({
"request_id": f"{candidate_ref}:{order}", "domain_ids": [domain_id],
"calculation_id": request.get("calculation_domain"),
"operand_state": request["completeness"] if isinstance(request.get("completeness"), str) and request["completeness"] in _COMPLETENESS else "partial",
"evidence_refs": evidence, "meeting_clause_refs": meeting,
"candidate_ref": candidate_ref, **bo_mark,
})
adapted.setdefault("calculation_requests", []).append(stamped)
calculation_refs.append(stamped["request_id"])
for effect in _rows(seed.get("legal_effect_candidates")):
if isinstance(effect, dict): if isinstance(effect, dict):
refs = [str(ref) for ref in effect.get("source_refs", seed_refs)] refs = [str(ref) for ref in _rows(effect.get("source_refs", seed_refs))]
status = "review" if effect.get("registered") is False else "inferred" status = "review" if effect.get("registered") is False else "inferred"
candidates.setdefault("SG-13", []).append(_candidate(domain_id, seed_id, "legal_effect_route", refs, effect, universe, status)) marked = {**_without(effect, "bo_absent"), "candidate_ref": candidate_ref, **bo_mark}
for slot in seed.get("evidence_slot_status", []): candidates.setdefault("SG-13", []).append(_candidate(domain_id, seed_id, "legal_effect_route", refs, marked, universe, status))
for slot in _rows(seed.get("evidence_slot_status")):
if not isinstance(slot, dict): if not isinstance(slot, dict):
continue continue
refs = [str(ref) for ref in slot.get("source_refs", [])] refs = [str(ref) for ref in _rows(slot.get("source_refs"))]
evidence, meeting = _source_fields(refs, universe) evidence, meeting = _source_fields(refs, universe)
# R0 repairs this before S0 unless the validator crashed or admission runs in shadow mode.
status_known = isinstance(slot.get("status"), str) and slot["status"] in _SLOT_STATUS
review_code = slot.get("review_code") if isinstance(slot.get("review_code"), str) else None
slot_rows.append({ slot_rows.append({
"slot_id": str(slot.get("slot_id") or "unknown_slot"), "status": slot.get("status", "missing"), "slot_id": str(slot.get("slot_id") or "unknown_slot"),
"status": slot["status"] if status_known else "missing",
"source_fact_ids": [], "evidence_refs": evidence, "meeting_clause_refs": meeting, "source_fact_ids": [], "evidence_refs": evidence, "meeting_clause_refs": meeting,
"negative_or_conflicting_refs": [], "review_code": slot.get("review_code"), "negative_or_conflicting_refs": [],
"review_code": review_code if status_known or review_code else "SLOT_STATUS_UNMAPPED_REVIEW",
}) })
dependencies.update(str(value) for value in seed.get("dependency_refs", [])) dependencies.update(str(value) for value in _rows(seed.get("dependency_refs")) if str(value))
review_items.extend(deepcopy(seed.get("review_items", []))) review_items.extend(_known_refs_only(_rows(seed.get("review_items")), universe, removed))
extensions: dict[str, Any] = {} extensions: dict[str, Any] = {}
if isinstance(deprecated_envelopes, dict) and domain_id in deprecated_envelopes: if isinstance(deprecated_envelopes, dict) and domain_id in deprecated_envelopes:
extensions["s3_roundtrip"] = migrate_deprecated_envelope(deprecated_envelopes[domain_id]) extensions["s3_roundtrip"] = migrate_deprecated_envelope(deprecated_envelopes[domain_id])
if removed:
unique = {(item["field"], item["value"]) for item in removed}
extensions["unverified_refs"] = [{"field": field, "value": value} for field, value in sorted(unique)]
review_items.append({
"review_code": "UNVERIFIED_REF_REVIEW", "severity": "review", "source_refs": [],
"reason": "refs dropped from this envelope, kept in extensions.unverified_refs: %d" % len(unique),
})
domains[domain_id] = {"domain_signal_envelope": { domains[domain_id] = {"domain_signal_envelope": {
"schema_version": "stage1_domain_signals.v2", "domain_id": domain_id, "schema_version": "stage1_domain_signals.v2", "domain_id": domain_id,
"domain_registry_version": root.get("registry_version", "UNKNOWN"), "domain_registry_version": activation["registry_version"],
"registry_index_sha256": root.get("registry_index_sha256", "0" * 64), "registry_index_sha256": activation["registry_index_sha256"],
"status": "READY_WITH_REVIEW" if review_items else ("READY" if root.get("bo_seed_candidates") else "NO_SUPPORT"), "status": "READY_WITH_REVIEW" if review_items else ("READY" if root.get("bo_seed_candidates") else "NO_SUPPORT"),
"element_fact_candidates": element_rows, "opposing_fact_candidates": opposing_rows, "element_fact_candidates": element_rows, "opposing_fact_candidates": opposing_rows,
"defense_candidates": defense_rows, "evidence_slot_status": slot_rows, "defense_candidates": defense_rows, "evidence_slot_status": slot_rows,
@@ -49,13 +49,14 @@ def _sha(data: bytes) -> str:
def _domain_envelopes(inputs: dict[str, Any], sg01: dict[str, Any]) -> dict[str, dict[str, Any]]: def _domain_envelopes(inputs: dict[str, Any], sg01: dict[str, Any]) -> dict[str, dict[str, Any]]:
manifest = sg01["domain_activation_manifest"] manifest = sg01["domain_activation_manifest"]
active = sorted(set(manifest.get("active_domain_ids", []))) # 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", {}) supplied = inputs.get("domain_signal_envelopes", {})
legacy_actio = inputs.get("legacy_signals", {}).get("actio_case_signals", {}) legacy_actio = inputs.get("legacy_signals", {}).get("actio_case_signals", {})
out: dict[str, dict[str, Any]] = {} out: dict[str, dict[str, Any]] = {}
registry_sha = str(manifest.get("registry_index_sha256") or "0" * 64) 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"]} extension_domains = {item["domain_id"]: item["extension_key"] for item in _EXECUTION["e13_extension_domains"]}
for domain_id in active: for domain_id in runnable:
provided = deepcopy(supplied.get(domain_id)) if isinstance(supplied, dict) else None provided = deepcopy(supplied.get(domain_id)) if isinstance(supplied, dict) else None
if isinstance(provided, dict): if isinstance(provided, dict):
envelope = provided envelope = provided
@@ -49,13 +49,14 @@ def _sha(data: bytes) -> str:
def _domain_envelopes(inputs: dict[str, Any], sg01: dict[str, Any]) -> dict[str, dict[str, Any]]: def _domain_envelopes(inputs: dict[str, Any], sg01: dict[str, Any]) -> dict[str, dict[str, Any]]:
manifest = sg01["domain_activation_manifest"] manifest = sg01["domain_activation_manifest"]
active = sorted(set(manifest.get("active_domain_ids", []))) # 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", {}) supplied = inputs.get("domain_signal_envelopes", {})
legacy_actio = inputs.get("legacy_signals", {}).get("actio_case_signals", {}) legacy_actio = inputs.get("legacy_signals", {}).get("actio_case_signals", {})
out: dict[str, dict[str, Any]] = {} out: dict[str, dict[str, Any]] = {}
registry_sha = str(manifest.get("registry_index_sha256") or "0" * 64) 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"]} extension_domains = {item["domain_id"]: item["extension_key"] for item in _EXECUTION["e13_extension_domains"]}
for domain_id in active: for domain_id in runnable:
provided = deepcopy(supplied.get(domain_id)) if isinstance(supplied, dict) else None provided = deepcopy(supplied.get(domain_id)) if isinstance(supplied, dict) else None
if isinstance(provided, dict): if isinstance(provided, dict):
envelope = provided envelope = provided
@@ -100,7 +100,10 @@ def _calculation_candidates(inputs: dict[str, Any]) -> list[dict[str, Any]]:
if not isinstance(request, dict): if not isinstance(request, dict):
continue continue
status = str(request.get("operand_state") or request.get("status") or "partial").lower() status = str(request.get("operand_state") or request.get("status") or "partial").lower()
item_status = "observed" if status == "ready" else ("missing_required" if status == "blocked" else "review") # A worker request (it carries completeness) that lacks an operand is a review item, not a halt.
# details.operand_state keeps "blocked" for the Part 4 gates.
blocking = status == "blocked" and "completeness" not in request
item_status = "observed" if status == "ready" else ("missing_required" if blocking else "review")
out.append({ out.append({
"signal_id": request.get("request_id") or f"calculation-request-{index:04d}", "signal_id": request.get("request_id") or f"calculation-request-{index:04d}",
"record_type": "calculation_requirement", "record_type": "calculation_requirement",
@@ -100,7 +100,10 @@ def _calculation_candidates(inputs: dict[str, Any]) -> list[dict[str, Any]]:
if not isinstance(request, dict): if not isinstance(request, dict):
continue continue
status = str(request.get("operand_state") or request.get("status") or "partial").lower() status = str(request.get("operand_state") or request.get("status") or "partial").lower()
item_status = "observed" if status == "ready" else ("missing_required" if status == "blocked" else "review") # A worker request (it carries completeness) that lacks an operand is a review item, not a halt.
# details.operand_state keeps "blocked" for the Part 4 gates.
blocking = status == "blocked" and "completeness" not in request
item_status = "observed" if status == "ready" else ("missing_required" if blocking else "review")
out.append({ out.append({
"signal_id": request.get("request_id") or f"calculation-request-{index:04d}", "signal_id": request.get("request_id") or f"calculation-request-{index:04d}",
"record_type": "calculation_requirement", "record_type": "calculation_requirement",
@@ -28,13 +28,13 @@
{"target": "BOType", "sources": ["bo_type"], "rule": "그대로", "guard": "slice.allowed_legal_effect_bo_types 밖이면 review", "review_issue_type": "legal_effect_uncertain"}, {"target": "BOType", "sources": ["bo_type"], "rule": "그대로", "guard": "slice.allowed_legal_effect_bo_types 밖이면 review", "review_issue_type": "legal_effect_uncertain"},
{"target": "JuristicAct.label", "sources": ["juristic_act_type"], "rule": "그대로, 빈 값이면 null", "review_issue_type": null}, {"target": "JuristicAct.label", "sources": ["juristic_act_type"], "rule": "그대로, 빈 값이면 null", "review_issue_type": null},
{"target": "ActionType", "sources": ["extensions.domain_payload.action_type"], "rule": "enum 안이면 그대로", "undetermined_default": "사실행위(factual acts)", "review_issue_type": "schema_field_fallback", "note": "registry 근거 없음. 기본값은 선언이며 추정이 아니다 — 적용 시 반드시 검토로 올린다."}, {"target": "ActionType", "sources": ["extensions.domain_payload.action_type"], "rule": "enum 안이면 그대로", "undetermined_default": "사실행위(factual acts)", "review_issue_type": "schema_field_fallback", "note": "registry 근거 없음. 기본값은 선언이며 추정이 아니다 — 적용 시 반드시 검토로 올린다."},
{"target": "Action", "sources": ["extensions.domain_payload.action_summary", "legal_effect_candidates[].type_id", "bo_type"], "rule": "앞선 출처부터 쓴다. type_id 는 사전순 최소를 골라 '<bo_type>:<type_id>' 로 만든다. bo_type 은 v3 필수 필드이므로 마지막 출처는 항상 성립한다.", "review_issue_type": "schema_field_fallback", "review_when": "출처가 action_summary 가 아닐 때", "note": "값은 registry token 이지 서술문이 아니다. F0 의 기존 대체 체인(seed.Action → action_summary → Action_proposal)은 방어선으로 유지되고, 투영기가 채우면 첫 출처에서 끝난다. Stage 2 는 review_handoff 의 action_source 를 함께 읽는다."}, {"target": "Action", "sources": ["extensions.domain_payload.action_summary", "legal_effect_candidates[].type_id", "bo_type"], "rule": "앞선 출처부터 쓴다. type_id 는 사전순 최소를 골라 '<bo_type>:<type_id>' 로 만든다. 마지막 출처는 '<bo_type>:effect_unspecified' 다. bo_type 만 쓰면 S2_00 이 PLACEHOLDER 로 빼서 BO 가 S2_10 에 가지 않는다. bo_type 은 v3 필수 필드이므로 마지막 출처는 항상 성립한다.", "review_issue_type": "schema_field_fallback", "review_when": "출처가 action_summary 가 아닐 때", "note": "값은 registry token 또는 그 대체 표지이지 서술문이 아니다. F0 의 기존 대체 체인(seed.Action → action_summary → Action_proposal)은 방어선으로 유지되고, 투영기가 채우면 첫 출처에서 끝난다. Stage 2 는 review_handoff 의 action_source 를 함께 읽는다."},
{"target": "Legal_Keywords", "sources": ["legal_effect_candidates[].type_id"], "rule": "중복 제거 후 사전순", "review_issue_type": null}, {"target": "Legal_Keywords", "sources": ["legal_effect_candidates[].type_id"], "rule": "중복 제거 후 사전순", "review_issue_type": null},
{"target": "core_field_base.BehaviorTime", "sources": ["time_facts[]"], "rule": "fact_type 사전순 최소 항목의 value. 서로 다른 value 가 둘 이상이면 골라 쓰되 review 로 올린다.", "review_issue_type": "amount_or_date_uncertain"}, {"target": "core_field_base.BehaviorTime", "sources": ["time_facts[]"], "rule": "fact_type 사전순 최소 항목의 value. 서로 다른 value 가 둘 이상이면 골라 쓰되 review 로 올린다.", "review_issue_type": "amount_or_date_uncertain"},
{"target": "core_field_base.TimeText", "sources": ["time_facts[]"], "rule": "BehaviorTime 과 같은 항목의 value", "review_issue_type": null}, {"target": "core_field_base.TimeText", "sources": ["time_facts[]"], "rule": "BehaviorTime 과 같은 항목의 value", "review_issue_type": null},
{"target": "core_field_base.Object", "sources": ["object_refs[]"], "rule": "사전순 최소", "review_issue_type": null}, {"target": "core_field_base.Object", "sources": ["object_refs[]"], "rule": "사전순 최소", "review_issue_type": null},
{"target": "core_field_base.StatementType", "sources": ["bo_type"], "rule": "그대로", "review_issue_type": null}, {"target": "core_field_base.StatementType", "sources": ["bo_type"], "rule": "그대로", "review_issue_type": null},
{"target": "amount", "sources": ["amount_facts[]"], "rule": "amount_type 사전순 최소, 동률이면 decimal_value 사전순 최소. value_text 와 numeric_value 는 decimal_value 원문 기준, currency 는 그대로.", "review_when": "서로 다른 decimal_value 가 둘 이상", "review_issue_type": "amount_or_date_uncertain"}, {"target": "amount", "sources": ["amount_facts[].source_refs 의 value_id", "stage1_tmp/task_c_bo/value_facts_catalog.json"], "rule": "worker 숫자는 쓰지 않는다. value_id 하나로 정본 레코드를 찾고(RESOLVED), value_type=MONEY·amount_value 있음·per 없음 가운데 amount_selection 단계표 순서로 하나를 고른다. value_text=amount_text, numeric_value=amount_value, currency=currency, value_id 를 함께 싣는다.", "review_when": "value_id 가 없거나 둘 이상, 또는 서로 다른 amount_value 가 둘 이상", "review_issue_type": "amount_or_date_uncertain"},
{"target": "registry_component_ids", "sources": ["registry_component_ids"], "rule": "그대로", "note": "meeting_only_evidence_gap 판정이 이 값을 본다. 떨어뜨리면 그 검사가 전건 참이 된다.", "review_issue_type": null} {"target": "registry_component_ids", "sources": ["registry_component_ids"], "rule": "그대로", "note": "meeting_only_evidence_gap 판정이 이 값을 본다. 떨어뜨리면 그 검사가 전건 참이 된다.", "review_issue_type": null}
], ],
"not_projected": { "not_projected": {
@@ -50,6 +50,7 @@
"additive_keys": ["source_review_code", "action_source"], "additive_keys": ["source_review_code", "action_source"],
"additive_reason": "handoff 문서에는 선언된 required_keys 가 없다. 원본 review_code 를 잃지 않기 위해 덧붙이기로만 확장한다." "additive_reason": "handoff 문서에는 선언된 required_keys 가 없다. 원본 review_code 를 잃지 않기 위해 덧붙이기로만 확장한다."
}, },
"amount_selection": {"added": "2026-10-30 가액금액_반영후_part_2_개정계획서.md §3.3 d (추가형 — 이 키를 읽지 않는 이전 판본 R0 도 그대로 돈다)", "eligible": "value_type == MONEY 이고 amount_value 가 있고 per 가 없는 레코드. per 가 있는 레코드(월세 등)는 value_refs 에만 남긴다.", "tier_labels": ["T1 주금액", "T2 합계", "T3 부수", "T4 변제·소멸", "T5 평가", "마지막"], "tiers": [["LOAN_PRINCIPAL", "AMOUNT_DISBURSED", "PRICE_TOTAL", "DEPOSIT", "FACE_VALUE", "INVESTMENT", "CONTRACT_SUM_OTHER", "TRANSACTION_PRICE", "DAMAGE_CLAIMED", "GIFT_OR_BEQUEST_VALUE", "MAX_SECURED_AMOUNT", "SECURED_DEBT_STATED", "REGISTERED_DEBT_AMOUNT", "GUARANTEE_LIMIT", "ATTACHMENT_CLAIM_AMOUNT"], ["SUM_TOTAL"], ["INTEREST_AMOUNT", "LATE_DAMAGES_AMOUNT", "PENALTY", "FEE", "PRICE_INSTALLMENT"], ["PAYMENT_MADE", "REFUND", "SETOFF_AMOUNT", "WAIVER_AMOUNT", "APPROPRIATION", "COURT_DEPOSIT"], ["MARKET_PRICE", "APPRAISAL_VALUE", "PUBLIC_HOUSING_PRICE", "TAX_BASE_VALUE", "TAXATION_STANDARD"], ["OTHER"]], "unlisted_kind": "표에 없는 value_kind 는 마지막 단계(OTHER 와 같은 자리)로 본다.", "sum_total_kind": "SUM_TOTAL", "sum_total_includes_relation": "INCLUDES", "sum_total_rule": "SUM_TOTAL 이 다른 레코드를 INCLUDES 로 가리킬 때만 T1 보다 앞선다.", "domain_overrides": {"E-10": ["MAX_SECURED_AMOUNT", "SECURED_DEBT_STATED", "REGISTERED_DEBT_AMOUNT"], "E-08": ["DEPOSIT"], "E-16": ["FACE_VALUE"], "E-15": ["GIFT_OR_BEQUEST_VALUE"]}, "domain_overrides_note": "domain_id 별로 맨 앞에 둘 value_kind 목록(E-10 담보물권·E-08 임대차·E-16 어음·E-15 상속). registry bo_type 은 event·state 같은 범용 값이라 덮어쓰기 열쇠로 쓰지 않는다.", "tie_break": "같은 단계 안에서는 value_id 사전순"},
"f0_normalization": { "f0_normalization": {
"bo_type_membership_source": "extension_payload_key_declarations.v1.json#bo_types_union", "bo_type_membership_source": "extension_payload_key_declarations.v1.json#bo_types_union",
"bo_type_default": "event", "bo_type_default": "event",
@@ -142,6 +142,17 @@ def _term_hits(record: dict[str, Any], terms: list[str]) -> list[str]:
return [term for term in terms if term.casefold() in blob] return [term for term in terms if term.casefold() in blob]
def _adapt_entry(item: dict[str, Any]) -> dict[str, Any]:
# C-01: D0 (activation_gate) writes primary_positive_refs / screening_confidence.
# meeting_positive_refs (MTG.*) is deliberately not merged.
row = dict(item)
if "positive_refs" not in row:
row["positive_refs"] = stable_unique(as_list(item.get("primary_positive_refs")))
conf = row.get("confidence") or item.get("screening_confidence")
row["confidence"] = conf if conf in ("high", "medium", "low") else "low"
return row
def _manifest_domains(manifest: dict[str, Any]) -> tuple[dict[str, Any], dict[str, dict[str, Any]], list[str]]: def _manifest_domains(manifest: dict[str, Any]) -> tuple[dict[str, Any], dict[str, dict[str, Any]], list[str]]:
root = unwrap(manifest, ("domain_activation_manifest", "SG-01")) root = unwrap(manifest, ("domain_activation_manifest", "SG-01"))
if not isinstance(root, dict): if not isinstance(root, dict):
@@ -149,7 +160,7 @@ def _manifest_domains(manifest: dict[str, Any]) -> tuple[dict[str, Any], dict[st
# Canonical SG-01: execution_eligible entries and expected set must agree exactly. # Canonical SG-01: execution_eligible entries and expected set must agree exactly.
if isinstance(root.get("domain_entries"), list) and isinstance(root.get("expected_runnable_domain_ids"), list): if isinstance(root.get("domain_entries"), list) and isinstance(root.get("expected_runnable_domain_ids"), list):
selected = { selected = {
str(item["domain_id"]): dict(item) str(item["domain_id"]): _adapt_entry(item)
for item in root["domain_entries"] for item in root["domain_entries"]
if isinstance(item, dict) and item.get("domain_id") and item.get("execution_eligible") is True if isinstance(item, dict) and item.get("domain_id") and item.get("execution_eligible") is True
} }
@@ -142,6 +142,17 @@ def _term_hits(record: dict[str, Any], terms: list[str]) -> list[str]:
return [term for term in terms if term.casefold() in blob] return [term for term in terms if term.casefold() in blob]
def _adapt_entry(item: dict[str, Any]) -> dict[str, Any]:
# C-01: D0 (activation_gate) writes primary_positive_refs / screening_confidence.
# meeting_positive_refs (MTG.*) is deliberately not merged.
row = dict(item)
if "positive_refs" not in row:
row["positive_refs"] = stable_unique(as_list(item.get("primary_positive_refs")))
conf = row.get("confidence") or item.get("screening_confidence")
row["confidence"] = conf if conf in ("high", "medium", "low") else "low"
return row
def _manifest_domains(manifest: dict[str, Any]) -> tuple[dict[str, Any], dict[str, dict[str, Any]], list[str]]: def _manifest_domains(manifest: dict[str, Any]) -> tuple[dict[str, Any], dict[str, dict[str, Any]], list[str]]:
root = unwrap(manifest, ("domain_activation_manifest", "SG-01")) root = unwrap(manifest, ("domain_activation_manifest", "SG-01"))
if not isinstance(root, dict): if not isinstance(root, dict):
@@ -149,7 +160,7 @@ def _manifest_domains(manifest: dict[str, Any]) -> tuple[dict[str, Any], dict[st
# Canonical SG-01: execution_eligible entries and expected set must agree exactly. # Canonical SG-01: execution_eligible entries and expected set must agree exactly.
if isinstance(root.get("domain_entries"), list) and isinstance(root.get("expected_runnable_domain_ids"), list): if isinstance(root.get("domain_entries"), list) and isinstance(root.get("expected_runnable_domain_ids"), list):
selected = { selected = {
str(item["domain_id"]): dict(item) str(item["domain_id"]): _adapt_entry(item)
for item in root["domain_entries"] for item in root["domain_entries"]
if isinstance(item, dict) and item.get("domain_id") and item.get("execution_eligible") is True if isinstance(item, dict) and item.get("domain_id") and item.get("execution_eligible") is True
} }
@@ -97,6 +97,23 @@ def compact_bo(bo: dict, policy: dict) -> dict:
return out 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갈래 · 순서 그대로) # (다) — 증거력 산정 (정책 evidence_scoring_da_2 의 5갈래 · 순서 그대로)
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -398,7 +415,6 @@ def compile_fact_ledger_candidates(
handoff_root = _dict(handoff_root.get("stage1_part2_review_handoff", handoff_root)) handoff_root = _dict(handoff_root.get("stage1_part2_review_handoff", handoff_root))
handoff_items = [r for r in _list(handoff_root.get("review_items")) handoff_items = [r for r in _list(handoff_root.get("review_items"))
if isinstance(r, dict)] if isinstance(r, dict)]
p2_rules = _dict(policy.get("p2_handoff_rules"))
code_pool: dict[str, list[str]] = {} code_pool: dict[str, list[str]] = {}
gate_input_counts = {"envelope_review_items": 0, "handoff_codes": 0, gate_input_counts = {"envelope_review_items": 0, "handoff_codes": 0,
"handoff_not_a_code": 0, "handoff_domain_unresolved": 0, "handoff_not_a_code": 0, "handoff_domain_unresolved": 0,
@@ -462,12 +478,12 @@ def compile_fact_ledger_candidates(
bo_sorted = sorted(bo_records, key=lambda b: str(b.get("BO_ID") or "")) bo_sorted = sorted(bo_records, key=lambda b: str(b.get("BO_ID") or ""))
authority = build_evidence_authority(evidence_document) authority = build_evidence_authority(evidence_document)
calc_types = set(_strings(policy.get("legal_calculation_object_types"))) calc_types = set(_strings(policy.get("legal_calculation_object_types")))
na_defaults = _dict(policy.get("field_synthesis_na_15"))
rows: list[dict] = [] rows: list[dict] = []
attach_stats = {"attached_bo": 0, "unattached_bo": 0} attach_stats = {"attached_bo": 0, "unattached_bo": 0}
used_structure_ids: set[str] = set() used_structure_ids: set[str] = set()
used_sg11: set[str] = set() used_sg11: set[str] = set()
slack_min = 10 ** 9 slack_min = 10 ** 9
pack_policy = _dict(policy.get("exception_pack"))
for idx, bo in enumerate(bo_sorted, 1): for idx, bo in enumerate(bo_sorted, 1):
compact = compact_bo(bo, policy) compact = compact_bo(bo, policy)
core = compact["core"] core = compact["core"]
@@ -482,7 +498,11 @@ def compile_fact_ledger_candidates(
parties.append({"role": "counterparty", parties.append({"role": "counterparty",
"value": _text(core.get("Subject"), 160), "value": _text(core.get("Subject"), 160),
"source": "BO.core_field_base"}) "source": "BO.core_field_base"})
amount = _text(_first_value(compact.get("amount"), core.get("Amount")), 240) 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")) action = _first_value(compact.get("action"), core.get("Action"))
evidence_refs = _strings(bo.get("source_evidence_indexes")) evidence_refs = _strings(bo.get("source_evidence_indexes"))
# F0-3 — LES 조인 # F0-3 — LES 조인
@@ -494,7 +514,8 @@ def compile_fact_ledger_candidates(
attach_stats["unattached_bo"] += 1 attach_stats["unattached_bo"] += 1
reviews.append({"review_code": "FACT_ROW_UNATTACHED_REVIEW", reviews.append({"review_code": "FACT_ROW_UNATTACHED_REVIEW",
"severity": "SOFT_WARNING", "fact_id": fact_id, "severity": "SOFT_WARNING", "fact_id": fact_id,
"detail": bo_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) used_structure_ids.update(s for s in structure_ids if s in record_by_id)
domain_effects: dict[str, dict] = {} domain_effects: dict[str, dict] = {}
for record in attached: for record in attached:
@@ -524,46 +545,47 @@ def compile_fact_ledger_candidates(
# F0-5 — SG-11 조인 + operand_state 승계 (재산정 금지) # F0-5 — SG-11 조인 + operand_state 승계 (재산정 금지)
calculation_requests: list[dict] = [] calculation_requests: list[dict] = []
route_refs: list[str] = [] route_refs: list[str] = []
for record in attached: # 계산 조인은 도메인 단위라 한 도메인의 레코드마다 같은 ref 가 있다. 행에는 한 번만 싣는다.
for ref in _strings(record.get("calculation_request_refs")): for ref in sorted({ref for record in attached
route_refs.append(ref) for ref in _strings(record.get("calculation_request_refs"))}):
sg = sg11_by_signal_id.get(ref) route_refs.append(ref)
if sg is None: sg = sg11_by_signal_id.get(ref)
calculation_requests.append({"calculation_id": None, if sg is None:
"request_id": ref, calculation_requests.append({"calculation_id": None,
"provenance": {"signal_id": ref, "request_id": ref,
"dangling": True}}) "provenance": {"signal_id": ref,
reviews.append({"review_code": "CALCULATION_REF_DANGLING_REVIEW", "dangling": True}})
"severity": "SOFT_WARNING", "fact_id": fact_id, reviews.append({"review_code": "CALCULATION_REF_DANGLING_REVIEW",
"detail": ref}) "severity": "SOFT_WARNING", "fact_id": fact_id,
continue "detail": ref})
used_sg11.add(ref) continue
details = _dict(sg.get("details")) used_sg11.add(ref)
calc_id = details.get("calculation_id") details = _dict(sg.get("details"))
if not isinstance(calc_id, str) or not calc_id: calc_id = details.get("calculation_id")
calc_id = ref if not isinstance(calc_id, str) or not calc_id:
reviews.append({"review_code": "CALCULATION_ID_SUBSTITUTED_REVIEW", calc_id = ref
"severity": "SOFT_WARNING", "fact_id": fact_id, reviews.append({"review_code": "CALCULATION_ID_SUBSTITUTED_REVIEW",
"detail": ref}) "severity": "SOFT_WARNING", "fact_id": fact_id,
law_refs = sorted(set( "detail": ref})
_strings(sg.get("law_version_refs")) law_refs = sorted(set(
+ _strings(details.get("law_version_refs")) _strings(sg.get("law_version_refs"))
+ [ref2 for d in _strings(sg.get("domain_ids")) + _strings(details.get("law_version_refs"))
for ref2 in sg04_by_domain.get(d, [])])) + [ref2 for d in _strings(sg.get("domain_ids"))
calculation_requests.append({ for ref2 in sg04_by_domain.get(d, [])]))
"calculation_id": calc_id, calculation_requests.append({
"request_id": ref, "calculation_id": calc_id,
"operand_state": (sg.get("operand_state") "request_id": ref,
or details.get("operand_state")), "operand_state": (sg.get("operand_state")
"missing_operands": _strings(details.get("missing_operands")), or details.get("operand_state")),
"law_version_refs": law_refs, "missing_operands": _strings(details.get("missing_operands")),
"provenance": {"signal_id": ref, "law_version_refs": law_refs,
"structure_ids": sorted( "provenance": {"signal_id": ref,
s for s in structure_ids "structure_ids": sorted(
if ref in _strings( s for s in structure_ids
_dict(record_by_id.get(s)).get( if ref in _strings(
"calculation_request_refs")))}, _dict(record_by_id.get(s)).get(
}) "calculation_request_refs")))},
})
# (다) 증거력 # (다) 증거력
credibility, proof_strength, slack = score_evidence( credibility, proof_strength, slack = score_evidence(
evidence_refs, authority, policy, reviews, fact_id) evidence_refs, authority, policy, reviews, fact_id)
@@ -609,7 +631,10 @@ def compile_fact_ledger_candidates(
"must_consider": bool(attached), "must_consider": bool(attached),
"state_context": {"bo_type": compact.get("bo_type") "state_context": {"bo_type": compact.get("bo_type")
if isinstance(compact.get("bo_type"), str) else None, if isinstance(compact.get("bo_type"), str) else None,
"domain_ids": sorted(domain_effects)}, # 금액 표시는 FACT 에만 있다. 미부착이어도 도메인 맥락에 닿게 한다.
"domain_ids": sorted(domain_effects) or (
[str(provenance.get("source_domain"))]
if alternatives or related else [])},
"money_claim_effect": {"enabled": bool(money_ids), "money_claim_effect": {"enabled": bool(money_ids),
"structure_ids": money_ids}, "structure_ids": money_ids},
"commercial_successor_effect": {"enabled": bool(successor_ids), "commercial_successor_effect": {"enabled": bool(successor_ids),
@@ -731,6 +756,10 @@ def compile_fact_ledger_candidates(
projection_rows = [r["fact_id"] for r in rows projection_rows = [r["fact_id"] for r in rows
if domain_id in r["domain_effects"]] if domain_id in r["domain_effects"]]
entry["projected_row_count"] = len(projection_rows) 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({ fired_by_domain.setdefault(domain_id, []).append({
"gate_id": gate_id, "codes": emitted, "gate_id": gate_id, "codes": emitted,
"row_must_consider": rule["row_must_consider"], "row_must_consider": rule["row_must_consider"],
@@ -764,6 +793,11 @@ def compile_fact_ledger_candidates(
row["must_consider"] = row["must_consider"] or True row["must_consider"] = row["must_consider"] or True
row["skeleton_validation_codes"] = _dedupe_keep_order(codes + gate_codes) 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 ----------------------------------- # ---- STRUCTURE_UNATTACHED_REVIEW -----------------------------------
unattached_structures = sorted(set(record_by_id) - used_structure_ids) unattached_structures = sorted(set(record_by_id) - used_structure_ids)
for structure_id in unattached_structures: for structure_id in unattached_structures:
@@ -771,19 +805,18 @@ def compile_fact_ledger_candidates(
"severity": "SOFT_WARNING", "detail": structure_id}) "severity": "SOFT_WARNING", "detail": structure_id})
# ---- F0-9 — 예외 pack ---------------------------------------------- # ---- F0-9 — 예외 pack ----------------------------------------------
pack_policy = _dict(policy.get("exception_pack"))
char_limit = int(pack_policy.get("pack_item_char_limit") or 2000) char_limit = int(pack_policy.get("pack_item_char_limit") or 2000)
exceptions: list[dict] = [] exceptions: list[dict] = []
for row in rows: for row, bo in zip(rows, bo_sorted):
if row["legal_calculation_object"] is None: provenance = _dict(bo.get("provenance"))
continue alternatives = _list(provenance.get("amount_alternatives"))
bo = next((b for b in bo_sorted # 칸은 차 있어도 BO 금액은 없다
if str(b.get("BO_ID") or "") == row["source_bo_id"]), {}) unbodied = 0 if bo.get("amount") else len(_list(provenance.get("amount_related_values")))
core = _dict(bo.get("core_field_base")) if alternatives:
amount_candidates = [v for v in (bo.get("amount"), core.get("Amount")) payload = {"amount_candidates": alternatives,
if _nonblank(v)] "current_value_id": _dict(bo.get("amount")).get("value_id"),
if len(amount_candidates) >= 2: "action": row["action"],
payload = {"amount_candidates": [_text(v, 240) for v in amount_candidates], "legal_calculation_object": row["legal_calculation_object"],
"object_spec": row["object_spec"], "object_spec": row["object_spec"],
"calculation_request_ids": sorted( "calculation_request_ids": sorted(
str(c.get("calculation_id")) for c in str(c.get("calculation_id")) for c in
@@ -797,16 +830,19 @@ def compile_fact_ledger_candidates(
rendered = json.dumps(item, ensure_ascii=False) rendered = json.dumps(item, ensure_ascii=False)
if len(rendered) > char_limit: if len(rendered) > char_limit:
item["oversize_review"] = True item["oversize_review"] = True
reviews.append({"review_code": "CALCULATION_BASIS_INCOMPLETE_REVIEW", reviews.append({"review_code": "CALCULATION_PACK_OVERSIZE_REVIEW",
"severity": "SOFT_WARNING", "severity": "SOFT_WARNING",
"fact_id": row["fact_id"], "fact_id": row["fact_id"],
"detail": "pack item oversize %d>%d" % (len(rendered), "detail": "pack item oversize %d>%d" % (len(rendered),
char_limit)}) char_limit)})
exceptions.append(item) exceptions.append(item)
elif (not _nonblank(row["amount"])) or (not _nonblank(row["object_spec"])): 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", reviews.append({"review_code": "CALCULATION_BASIS_INCOMPLETE_REVIEW",
"severity": "SOFT_WARNING", "fact_id": row["fact_id"], "severity": "SOFT_WARNING", "fact_id": row["fact_id"],
"detail": "amount_or_object_spec_blank"}) "detail": "amount_or_object_spec_blank"
+ (" related_values=%d" % unbodied if unbodied else "")})
unreachable = {name for name, meta in unreachable = {name for name, meta in
_dict(policy.get("f1_exception_types")).items() _dict(policy.get("f1_exception_types")).items()
if _dict(meta).get("unreachable_in_v8")} if _dict(meta).get("unreachable_in_v8")}
@@ -856,9 +892,8 @@ def compile_fact_ledger_candidates(
(set(slot["review_codes"]) & les_review_codes) (set(slot["review_codes"]) & les_review_codes)
for row in rows for slot in row["domain_effects"].values()) or any( for row in rows for slot in row["domain_effects"].values()) or any(
_dict(r).get("review_required") for r in structure_records) _dict(r).get("review_required") for r in structure_records)
gate_fired_any = any(f for firings in fired_by_domain.values() for f in firings)
status = ("READY_WITH_REVIEW" status = ("READY_WITH_REVIEW"
if (reviews or exceptions or les_review_present or gate_fired_any) if (reviews or exceptions or les_review_present)
else "READY") else "READY")
counts = { counts = {
"rows": len(rows), "rows": len(rows),
@@ -97,6 +97,23 @@ def compact_bo(bo: dict, policy: dict) -> dict:
return out 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갈래 · 순서 그대로) # (다) — 증거력 산정 (정책 evidence_scoring_da_2 의 5갈래 · 순서 그대로)
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -398,7 +415,6 @@ def compile_fact_ledger_candidates(
handoff_root = _dict(handoff_root.get("stage1_part2_review_handoff", handoff_root)) handoff_root = _dict(handoff_root.get("stage1_part2_review_handoff", handoff_root))
handoff_items = [r for r in _list(handoff_root.get("review_items")) handoff_items = [r for r in _list(handoff_root.get("review_items"))
if isinstance(r, dict)] if isinstance(r, dict)]
p2_rules = _dict(policy.get("p2_handoff_rules"))
code_pool: dict[str, list[str]] = {} code_pool: dict[str, list[str]] = {}
gate_input_counts = {"envelope_review_items": 0, "handoff_codes": 0, gate_input_counts = {"envelope_review_items": 0, "handoff_codes": 0,
"handoff_not_a_code": 0, "handoff_domain_unresolved": 0, "handoff_not_a_code": 0, "handoff_domain_unresolved": 0,
@@ -462,12 +478,12 @@ def compile_fact_ledger_candidates(
bo_sorted = sorted(bo_records, key=lambda b: str(b.get("BO_ID") or "")) bo_sorted = sorted(bo_records, key=lambda b: str(b.get("BO_ID") or ""))
authority = build_evidence_authority(evidence_document) authority = build_evidence_authority(evidence_document)
calc_types = set(_strings(policy.get("legal_calculation_object_types"))) calc_types = set(_strings(policy.get("legal_calculation_object_types")))
na_defaults = _dict(policy.get("field_synthesis_na_15"))
rows: list[dict] = [] rows: list[dict] = []
attach_stats = {"attached_bo": 0, "unattached_bo": 0} attach_stats = {"attached_bo": 0, "unattached_bo": 0}
used_structure_ids: set[str] = set() used_structure_ids: set[str] = set()
used_sg11: set[str] = set() used_sg11: set[str] = set()
slack_min = 10 ** 9 slack_min = 10 ** 9
pack_policy = _dict(policy.get("exception_pack"))
for idx, bo in enumerate(bo_sorted, 1): for idx, bo in enumerate(bo_sorted, 1):
compact = compact_bo(bo, policy) compact = compact_bo(bo, policy)
core = compact["core"] core = compact["core"]
@@ -482,7 +498,11 @@ def compile_fact_ledger_candidates(
parties.append({"role": "counterparty", parties.append({"role": "counterparty",
"value": _text(core.get("Subject"), 160), "value": _text(core.get("Subject"), 160),
"source": "BO.core_field_base"}) "source": "BO.core_field_base"})
amount = _text(_first_value(compact.get("amount"), core.get("Amount")), 240) 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")) action = _first_value(compact.get("action"), core.get("Action"))
evidence_refs = _strings(bo.get("source_evidence_indexes")) evidence_refs = _strings(bo.get("source_evidence_indexes"))
# F0-3 — LES 조인 # F0-3 — LES 조인
@@ -494,7 +514,8 @@ def compile_fact_ledger_candidates(
attach_stats["unattached_bo"] += 1 attach_stats["unattached_bo"] += 1
reviews.append({"review_code": "FACT_ROW_UNATTACHED_REVIEW", reviews.append({"review_code": "FACT_ROW_UNATTACHED_REVIEW",
"severity": "SOFT_WARNING", "fact_id": fact_id, "severity": "SOFT_WARNING", "fact_id": fact_id,
"detail": bo_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) used_structure_ids.update(s for s in structure_ids if s in record_by_id)
domain_effects: dict[str, dict] = {} domain_effects: dict[str, dict] = {}
for record in attached: for record in attached:
@@ -524,46 +545,47 @@ def compile_fact_ledger_candidates(
# F0-5 — SG-11 조인 + operand_state 승계 (재산정 금지) # F0-5 — SG-11 조인 + operand_state 승계 (재산정 금지)
calculation_requests: list[dict] = [] calculation_requests: list[dict] = []
route_refs: list[str] = [] route_refs: list[str] = []
for record in attached: # 계산 조인은 도메인 단위라 한 도메인의 레코드마다 같은 ref 가 있다. 행에는 한 번만 싣는다.
for ref in _strings(record.get("calculation_request_refs")): for ref in sorted({ref for record in attached
route_refs.append(ref) for ref in _strings(record.get("calculation_request_refs"))}):
sg = sg11_by_signal_id.get(ref) route_refs.append(ref)
if sg is None: sg = sg11_by_signal_id.get(ref)
calculation_requests.append({"calculation_id": None, if sg is None:
"request_id": ref, calculation_requests.append({"calculation_id": None,
"provenance": {"signal_id": ref, "request_id": ref,
"dangling": True}}) "provenance": {"signal_id": ref,
reviews.append({"review_code": "CALCULATION_REF_DANGLING_REVIEW", "dangling": True}})
"severity": "SOFT_WARNING", "fact_id": fact_id, reviews.append({"review_code": "CALCULATION_REF_DANGLING_REVIEW",
"detail": ref}) "severity": "SOFT_WARNING", "fact_id": fact_id,
continue "detail": ref})
used_sg11.add(ref) continue
details = _dict(sg.get("details")) used_sg11.add(ref)
calc_id = details.get("calculation_id") details = _dict(sg.get("details"))
if not isinstance(calc_id, str) or not calc_id: calc_id = details.get("calculation_id")
calc_id = ref if not isinstance(calc_id, str) or not calc_id:
reviews.append({"review_code": "CALCULATION_ID_SUBSTITUTED_REVIEW", calc_id = ref
"severity": "SOFT_WARNING", "fact_id": fact_id, reviews.append({"review_code": "CALCULATION_ID_SUBSTITUTED_REVIEW",
"detail": ref}) "severity": "SOFT_WARNING", "fact_id": fact_id,
law_refs = sorted(set( "detail": ref})
_strings(sg.get("law_version_refs")) law_refs = sorted(set(
+ _strings(details.get("law_version_refs")) _strings(sg.get("law_version_refs"))
+ [ref2 for d in _strings(sg.get("domain_ids")) + _strings(details.get("law_version_refs"))
for ref2 in sg04_by_domain.get(d, [])])) + [ref2 for d in _strings(sg.get("domain_ids"))
calculation_requests.append({ for ref2 in sg04_by_domain.get(d, [])]))
"calculation_id": calc_id, calculation_requests.append({
"request_id": ref, "calculation_id": calc_id,
"operand_state": (sg.get("operand_state") "request_id": ref,
or details.get("operand_state")), "operand_state": (sg.get("operand_state")
"missing_operands": _strings(details.get("missing_operands")), or details.get("operand_state")),
"law_version_refs": law_refs, "missing_operands": _strings(details.get("missing_operands")),
"provenance": {"signal_id": ref, "law_version_refs": law_refs,
"structure_ids": sorted( "provenance": {"signal_id": ref,
s for s in structure_ids "structure_ids": sorted(
if ref in _strings( s for s in structure_ids
_dict(record_by_id.get(s)).get( if ref in _strings(
"calculation_request_refs")))}, _dict(record_by_id.get(s)).get(
}) "calculation_request_refs")))},
})
# (다) 증거력 # (다) 증거력
credibility, proof_strength, slack = score_evidence( credibility, proof_strength, slack = score_evidence(
evidence_refs, authority, policy, reviews, fact_id) evidence_refs, authority, policy, reviews, fact_id)
@@ -609,7 +631,10 @@ def compile_fact_ledger_candidates(
"must_consider": bool(attached), "must_consider": bool(attached),
"state_context": {"bo_type": compact.get("bo_type") "state_context": {"bo_type": compact.get("bo_type")
if isinstance(compact.get("bo_type"), str) else None, if isinstance(compact.get("bo_type"), str) else None,
"domain_ids": sorted(domain_effects)}, # 금액 표시는 FACT 에만 있다. 미부착이어도 도메인 맥락에 닿게 한다.
"domain_ids": sorted(domain_effects) or (
[str(provenance.get("source_domain"))]
if alternatives or related else [])},
"money_claim_effect": {"enabled": bool(money_ids), "money_claim_effect": {"enabled": bool(money_ids),
"structure_ids": money_ids}, "structure_ids": money_ids},
"commercial_successor_effect": {"enabled": bool(successor_ids), "commercial_successor_effect": {"enabled": bool(successor_ids),
@@ -731,6 +756,10 @@ def compile_fact_ledger_candidates(
projection_rows = [r["fact_id"] for r in rows projection_rows = [r["fact_id"] for r in rows
if domain_id in r["domain_effects"]] if domain_id in r["domain_effects"]]
entry["projected_row_count"] = len(projection_rows) 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({ fired_by_domain.setdefault(domain_id, []).append({
"gate_id": gate_id, "codes": emitted, "gate_id": gate_id, "codes": emitted,
"row_must_consider": rule["row_must_consider"], "row_must_consider": rule["row_must_consider"],
@@ -764,6 +793,11 @@ def compile_fact_ledger_candidates(
row["must_consider"] = row["must_consider"] or True row["must_consider"] = row["must_consider"] or True
row["skeleton_validation_codes"] = _dedupe_keep_order(codes + gate_codes) 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 ----------------------------------- # ---- STRUCTURE_UNATTACHED_REVIEW -----------------------------------
unattached_structures = sorted(set(record_by_id) - used_structure_ids) unattached_structures = sorted(set(record_by_id) - used_structure_ids)
for structure_id in unattached_structures: for structure_id in unattached_structures:
@@ -771,19 +805,18 @@ def compile_fact_ledger_candidates(
"severity": "SOFT_WARNING", "detail": structure_id}) "severity": "SOFT_WARNING", "detail": structure_id})
# ---- F0-9 — 예외 pack ---------------------------------------------- # ---- F0-9 — 예외 pack ----------------------------------------------
pack_policy = _dict(policy.get("exception_pack"))
char_limit = int(pack_policy.get("pack_item_char_limit") or 2000) char_limit = int(pack_policy.get("pack_item_char_limit") or 2000)
exceptions: list[dict] = [] exceptions: list[dict] = []
for row in rows: for row, bo in zip(rows, bo_sorted):
if row["legal_calculation_object"] is None: provenance = _dict(bo.get("provenance"))
continue alternatives = _list(provenance.get("amount_alternatives"))
bo = next((b for b in bo_sorted # 칸은 차 있어도 BO 금액은 없다
if str(b.get("BO_ID") or "") == row["source_bo_id"]), {}) unbodied = 0 if bo.get("amount") else len(_list(provenance.get("amount_related_values")))
core = _dict(bo.get("core_field_base")) if alternatives:
amount_candidates = [v for v in (bo.get("amount"), core.get("Amount")) payload = {"amount_candidates": alternatives,
if _nonblank(v)] "current_value_id": _dict(bo.get("amount")).get("value_id"),
if len(amount_candidates) >= 2: "action": row["action"],
payload = {"amount_candidates": [_text(v, 240) for v in amount_candidates], "legal_calculation_object": row["legal_calculation_object"],
"object_spec": row["object_spec"], "object_spec": row["object_spec"],
"calculation_request_ids": sorted( "calculation_request_ids": sorted(
str(c.get("calculation_id")) for c in str(c.get("calculation_id")) for c in
@@ -797,16 +830,19 @@ def compile_fact_ledger_candidates(
rendered = json.dumps(item, ensure_ascii=False) rendered = json.dumps(item, ensure_ascii=False)
if len(rendered) > char_limit: if len(rendered) > char_limit:
item["oversize_review"] = True item["oversize_review"] = True
reviews.append({"review_code": "CALCULATION_BASIS_INCOMPLETE_REVIEW", reviews.append({"review_code": "CALCULATION_PACK_OVERSIZE_REVIEW",
"severity": "SOFT_WARNING", "severity": "SOFT_WARNING",
"fact_id": row["fact_id"], "fact_id": row["fact_id"],
"detail": "pack item oversize %d>%d" % (len(rendered), "detail": "pack item oversize %d>%d" % (len(rendered),
char_limit)}) char_limit)})
exceptions.append(item) exceptions.append(item)
elif (not _nonblank(row["amount"])) or (not _nonblank(row["object_spec"])): 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", reviews.append({"review_code": "CALCULATION_BASIS_INCOMPLETE_REVIEW",
"severity": "SOFT_WARNING", "fact_id": row["fact_id"], "severity": "SOFT_WARNING", "fact_id": row["fact_id"],
"detail": "amount_or_object_spec_blank"}) "detail": "amount_or_object_spec_blank"
+ (" related_values=%d" % unbodied if unbodied else "")})
unreachable = {name for name, meta in unreachable = {name for name, meta in
_dict(policy.get("f1_exception_types")).items() _dict(policy.get("f1_exception_types")).items()
if _dict(meta).get("unreachable_in_v8")} if _dict(meta).get("unreachable_in_v8")}
@@ -856,9 +892,8 @@ def compile_fact_ledger_candidates(
(set(slot["review_codes"]) & les_review_codes) (set(slot["review_codes"]) & les_review_codes)
for row in rows for slot in row["domain_effects"].values()) or any( for row in rows for slot in row["domain_effects"].values()) or any(
_dict(r).get("review_required") for r in structure_records) _dict(r).get("review_required") for r in structure_records)
gate_fired_any = any(f for firings in fired_by_domain.values() for f in firings)
status = ("READY_WITH_REVIEW" status = ("READY_WITH_REVIEW"
if (reviews or exceptions or les_review_present or gate_fired_any) if (reviews or exceptions or les_review_present)
else "READY") else "READY")
counts = { counts = {
"rows": len(rows), "rows": len(rows),
@@ -69,7 +69,7 @@
"type": "compact.bo_type 단독 (LES types[0] 폴백 금지)", "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", "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": "core_field_base 단독 — Performer -> role: actor · Subject -> role: counterparty · 값은 text(party, 160) · source: 'BO.core_field_base'. 구 signal 경로 폐지",
"amount": "text(first_value(bo.amount, core_field_base.Amount), 240) or None — 키 오름차순 JSON(ensure_ascii=False) -> 공백열 단일 공백 정규화 -> 240자 절단 -> 빈 문자열이면 None", "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) — 정규화 계층 통과 후의 소문자 키", "action": "first_value(compact.action, core_field_base.Action) — 정규화 계층 통과 후의 소문자 키",
"evidence_refs": "BO source_evidence_indexes 단독 — LES 증거는 합집합하지 않는다(합집합하면 v.8 에서 깨진다). LES 증거는 domain_effects 쪽에만 싣는다", "evidence_refs": "BO source_evidence_indexes 단독 — LES 증거는 합집합하지 않는다(합집합하면 v.8 에서 깨진다). LES 증거는 domain_effects 쪽에만 싣는다",
"derived_fact": "action 복제 단독 — 구본 4항 서술 분기는 삭제 확정(deprecation 절)" "derived_fact": "action 복제 단독 — 구본 4항 서술 분기는 삭제 확정(deprecation 절)"
@@ -82,11 +82,11 @@
}, },
"legal_centrality": "부착 있으면 high · 없으면 medium", "legal_centrality": "부착 있으면 high · 없으면 medium",
"legal_effect_roles": "부착 레코드 role_projection 정렬 합집합 · 기본 []", "legal_effect_roles": "부착 레코드 role_projection 정렬 합집합 · 기본 []",
"claim_chain_ref": "{claim_group_ids: [], liability_group_ids: [], signal_count: 부착 route signal 수} — 구 그룹 ID 는 v.8 에 존재하지 않으므로 상시 빈 배열", "claim_chain_ref": "{claim_group_ids: [], liability_group_ids: [], signal_count: 부착 계산 요청 ref 수} — 구 그룹 ID 는 v.8 에 존재하지 않으므로 상시 빈 배열",
"linked_structures": "{structure_ids: 정렬 합집합} · 기본 {structure_ids: []}", "linked_structures": "{structure_ids: 정렬 합집합} · 기본 {structure_ids: []}",
"must_not_drop_in_claim_types": "부착 레코드 module 정렬 합집합 · 기본 []", "must_not_drop_in_claim_types": "부착 레코드 module 정렬 합집합 · 기본 []",
"must_consider": "1차 = 부착 존재 여부(bool) · 게이트 행 투영이 OR 로 갱신한다 — (나)∩(라) 겸용 필드", "must_consider": "1차 = 부착 존재 여부(bool) · 게이트 행 투영이 OR 로 갱신한다 — (나)∩(라) 겸용 필드",
"state_context": "{bo_type, domain_ids: domain_effects 키 정렬} · 기본 {bo_type, domain_ids: []}", "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: 해당 정렬 목록}", "money_claim_effect": "{enabled: module 'money_claim' 부착 여부, structure_ids: 해당 정렬 목록}",
"commercial_successor_effect": "{enabled: module 'commercial_successor' 부착 여부, structure_ids: 해당 정렬 목록}", "commercial_successor_effect": "{enabled: module 'commercial_successor' 부착 여부, structure_ids: 해당 정렬 목록}",
"actio_roles": "module 'actio' 부착 레코드의 role_projection 정렬 합집합 · 기본 []", "actio_roles": "module 'actio' 부착 레코드의 role_projection 정렬 합집합 · 기본 []",
@@ -181,13 +181,13 @@
"str_condition_disposition": "GATE_PREDICATE_SPEC_UNIMPLEMENTED_REVIEW — 술어 명세를 코드로 옮기는 것은 판정식 창작이다(D-P4-b=(가))", "str_condition_disposition": "GATE_PREDICATE_SPEC_UNIMPLEMENTED_REVIEW — 술어 명세를 코드로 옮기는 것은 판정식 창작이다(D-P4-b=(가))",
"orphan_rule_disposition": "GATE_RULE_NOT_IN_REGISTRY", "orphan_rule_disposition": "GATE_RULE_NOT_IN_REGISTRY",
"unknown_or_missing_policy_default": "fail_open_to_review", "unknown_or_missing_policy_default": "fail_open_to_review",
"block_semantics": "blocks_final_drafting: true 는 Stage 1 기록을 막지 않는다. 행은 기록되고 final_writer_status 가 READY_WITH_REVIEW 가 되며 차단 표지는 Stage 2 로 전달된다.", "block_semantics": "blocks_final_drafting: true 는 Stage 1 기록을 막지 않는다. 행은 기록되고 final_writer_status 가 READY_WITH_REVIEW 가 되며 발화는 handoff GATE_FIRED_REVIEW(HARD_WARNING)로 남는다. S2_00 은 이를 건수로만 넘긴다.",
"row_projection": { "row_projection": {
"target_rows": "발화 게이트의 도메인 d 에 대해 R(d) = { row | d ∈ row.domain_effects 키 }", "target_rows": "발화 게이트의 도메인 d 에 대해 R(d) = { row | d ∈ row.domain_effects 키 }",
"codes": "R(d) 전 행의 skeleton_validation_codes 에 합집합 부착(순서 규칙은 skeleton_checks)", "codes": "R(d) 전 행의 skeleton_validation_codes 에 합집합 부착(순서 규칙은 skeleton_checks)",
"must_consider": "row_effect.must_consider 보유 규칙 발화 시 R(d) 전 행 OR 갱신(기존 True 미소실)", "must_consider": "row_effect.must_consider 보유 규칙 발화 시 R(d) 전 행 OR 갱신(기존 True 미소실)",
"preserve_seed": "on_true.preserve_seed 는 행 필드가 아니라 writer report 게이트별 발화 목록에만 기록", "preserve_seed": "on_true.preserve_seed 는 행 필드가 아니라 writer report 게이트별 발화 목록에만 기록",
"empty_target": "R(d) 공집합이면 행에 닿지 않고 writer report 에만 계수(침묵 아님)" "empty_target": "R(d) 공집합이면 행에 닿지 않고 writer report 와 handoff GATE_FIRED_REVIEW 에 계수(침묵 아님)"
}, },
"normalization_axes_17": { "normalization_axes_17": {
"rule_array_keys": [ "rule_array_keys": [
@@ -283,15 +283,17 @@
"exception_pack": { "exception_pack": {
"surviving_type": "legal_calculation_required", "surviving_type": "legal_calculation_required",
"review_code": "CALCULATION_BASIS_INCOMPLETE_REVIEW", "review_code": "CALCULATION_BASIS_INCOMPLETE_REVIEW",
"trigger": "구본 866·899-925행 승계 — calculation_required AND amount 후보 2개 이상(bo.amount·core.Amount 양쪽 비공백)이면 pack 적재 + conflict_flags [CALCULATION_BASIS_CONFLICT] · elif amount 또는 object_spec 공백이면 pack 미적재 + CALCULATION_BASIS_INCOMPLETE_REVIEW 검토(if/elif 배타)", "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}", "exception_id_format": "FX-{n:03d}",
"pack_item_char_limit": 2000, "pack_item_char_limit": 2000,
"oversize_disposition": "자동 차단이 아니라 exception_id 유지한 채 review", "oversize_disposition": "자동 차단이 아니라 exception_id 유지한 채 CALCULATION_PACK_OVERSIZE_REVIEW",
"unreachable_in_v8": { "unreachable_in_v8": {
"unresolved_asset_cluster_projection": "asset_cluster 계열이 Part 3 v.8 에서 소멸(P2·P3·LES 스키마·컴파일러 0회)", "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)" "unresolved_structure_role_projection": "registry structure_types 73/73 이 module·role_projection 전건 선언(결손 0)"
}, },
"unreachable_disposition": "pack 에 실리면 PART4_UNREACHABLE_EXCEPTION_TYPE 경성 실패" "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": { "adjudication": {
"accepted_status": [ "accepted_status": [
@@ -299,12 +301,9 @@
"READY_NO_EXCEPTIONS", "READY_NO_EXCEPTIONS",
"READY_WITH_BLOCKS" "READY_WITH_BLOCKS"
], ],
"allowed_patch_fields": [ "note": "F1 은 행 금액을 바꾸지 않는다. 계산 근거 판정은 amount JSON 의 conflict.selected_value_id 에만 남는다. Part 2 R1 과 같은 원칙이다 — 값이 다른 정본은 별개 사실일 수 있다. LLM 출력 이상은 멈추지 않고 UNRESOLVED 표시와 CALCULATION_BASIS_CONFLICT_REVIEW 로 내린다."
"amount"
],
"note": "허용 필드 밖 수정은 PART4_PATCH_REJECTED. F1 의 유일 생존 부류가 계산 근거 다중성 판정이므로 패치 가능 필드는 amount 하나다."
}, },
"global_status_rule": "blocked item · rejected patch · deterministic review · LES 승계 검토(review_codes 2종 ∪ review_required 플래그) · gate review code 중 하나라도 있으면 READY_WITH_REVIEW, 아니면 READY (동결 계약 승계 — 사이드카 3방언 값은 경고로만 기록)", "global_status_rule": "금액 예외(SELECTED 포함) · deterministic review · LES 승계 검토(review_codes 2종 ∪ review_required 플래그) · gate review code 중 하나라도 있으면 READY_WITH_REVIEW, 아니면 READY (동결 계약 승계 — 사이드카 3방언 값은 경고로만 기록)",
"les_inherited_review_codes": [ "les_inherited_review_codes": [
"UNREGISTERED_EFFECT_TYPE_REVIEW", "UNREGISTERED_EFFECT_TYPE_REVIEW",
"PART3_REGISTRY_SIDECAR_MISMATCH" "PART3_REGISTRY_SIDECAR_MISMATCH"
@@ -349,10 +348,13 @@
"EVIDENCE_REF_NOT_IN_EVIDENCE_UNIVERSE", "EVIDENCE_REF_NOT_IN_EVIDENCE_UNIVERSE",
"EMPTY_DERIVED_FACT", "EMPTY_DERIVED_FACT",
"NO_EVIDENCE_REFS", "NO_EVIDENCE_REFS",
"NO_LINKED_LEGAL_EFFECT_STRUCTURE" "NO_LINKED_LEGAL_EFFECT_STRUCTURE",
"CALCULATION_REQUEST_UNATTACHED_REVIEW",
"CALCULATION_PACK_OVERSIZE_REVIEW"
], ],
"hard_failure_codes": [ "hard_failure_codes": [
"PART4_ASSET_DEPLOYMENT_INCOMPLETE", "PART4_ASSET_DEPLOYMENT_INCOMPLETE",
"PART4_RUNTIME_MANIFEST_INVALID",
"MODULE_MIRROR_UNREGISTERED", "MODULE_MIRROR_UNREGISTERED",
"MODULE_MIRROR_HASH_MISMATCH", "MODULE_MIRROR_HASH_MISMATCH",
"PART4_POLICY_INVALID", "PART4_POLICY_INVALID",
@@ -366,11 +368,8 @@
"PART4_EFFECT_CONSERVATION_BROKEN", "PART4_EFFECT_CONSERVATION_BROKEN",
"PART4_CALC_CONSERVATION_BROKEN", "PART4_CALC_CONSERVATION_BROKEN",
"PART4_CALC_SOURCE_CONSERVATION_BROKEN", "PART4_CALC_SOURCE_CONSERVATION_BROKEN",
"PART4_COVERAGE_BROKEN",
"PART4_PATCH_REJECTED",
"PART4_BO_CONSERVATION_BROKEN", "PART4_BO_CONSERVATION_BROKEN",
"PART4_FACT_ID_SEQUENCE_BROKEN", "PART4_FACT_ID_SEQUENCE_BROKEN",
"PART4_ADJUDICATION_MISSING",
"PART4_DOMAIN_EFFECT_NOT_ACTIVE", "PART4_DOMAIN_EFFECT_NOT_ACTIVE",
"PART4_LEDGER_SCHEMA_INVALID", "PART4_LEDGER_SCHEMA_INVALID",
"PART4_UNREACHABLE_EXCEPTION_TYPE", "PART4_UNREACHABLE_EXCEPTION_TYPE",
@@ -397,5 +396,10 @@
"commercial_successor_effect": "commercial_successor", "commercial_successor_effect": "commercial_successor",
"actio_fields": "actio", "actio_fields": "actio",
"note": "구 4필드 별칭이 참조하는 module 어휘. 코드에 리터럴을 두지 않는다(정적 검사 11) — registry structure_types[].module 이 원천이고 이 선언은 그중 별칭 파생이 쓰는 세 값을 고정한다." "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 이다."
} }
@@ -1,7 +1,7 @@
{ {
"schema_version": "stage1_seed_admission_policy.v1", "schema_version": "stage1_seed_admission_policy.v1",
"status": "ACTIVE", "status": "ACTIVE",
"purpose": "R0 가 이미 수행하는 전체 스키마 검증(worker_output_validator -> schema_subset_validator)의 결과를 등급으로 나누어 처리하는 규칙을 코드 밖에 선언한다. 구조 위반은 막고, 어휘·형태 위반은 정본으로 정규화하거나 정당한 자유 공간으로 수확한 뒤 검토로 남긴다. 값을 지어내지 않는다 — 표에 없는 낱말과 대조 불가능한 참조는 복구하지 않고 격리한다.", "purpose": "R0 가 이미 수행하는 전체 스키마 검증(worker_output_validator -> schema_subset_validator)의 결과를 등급으로 나누어 처리하는 규칙을 코드 밖에 선언한다. 구조 위반은 막고, 어휘·형태 위반은 정본으로 정규화하거나 정당한 자유 공간으로 수확한 뒤 검토로 남긴다. 값을 지어내지 않는다 — 표에 없는 낱말과 대조 불가능한 참조는 복구하지 않고 격리한다. 예외는 enum_unmapped_fallback 에 선언한 슬롯 status 하나다.",
"authority": { "authority": {
"seed_contract": "task_c_bo_stage_b_domain_bo_seed.v3", "seed_contract": "task_c_bo_stage_b_domain_bo_seed.v3",
"validator": "Default_Agent/stage1_runtime/worker_output_validator.txt", "validator": "Default_Agent/stage1_runtime/worker_output_validator.txt",
@@ -45,6 +45,7 @@
"CALCULATION_REVIEW_MISSING": "review", "CALCULATION_REVIEW_MISSING": "review",
"CALCULATION_DOMAIN_NOT_DECLARED": "review", "CALCULATION_DOMAIN_NOT_DECLARED": "review",
"EVIDENCE_SLOT_NOT_DECLARED": "review", "EVIDENCE_SLOT_NOT_DECLARED": "review",
"STRUCTURE_TYPE_NOT_DECLARED": "review",
"UNKNOWN_VALUE_REVIEW_MISSING": "review", "UNKNOWN_VALUE_REVIEW_MISSING": "review",
"WORKER_BO_TYPE_UNREGISTERED": "review", "WORKER_BO_TYPE_UNREGISTERED": "review",
"WORKER_DEPENDENCY_UNREGISTERED": "review", "WORKER_DEPENDENCY_UNREGISTERED": "review",
@@ -88,6 +89,10 @@
"empty": "NO_SUPPORT" "empty": "NO_SUPPORT"
}, },
"bo_seed_candidates[].evidence_slot_status[].status": { "bo_seed_candidates[].evidence_slot_status[].status": {
"filled": "filled",
"partial": "partial",
"missing": "missing",
"conflicted": "conflicted",
"supported": "filled", "supported": "filled",
"proven": "filled", "proven": "filled",
"sufficient": "filled", "sufficient": "filled",
@@ -179,6 +184,12 @@
}, },
"enum_case_fold": true, "enum_case_fold": true,
"enum_unmapped_disposition": "repair_evict", "enum_unmapped_disposition": "repair_evict",
"enum_unmapped_fallback": {
"bo_seed_candidates[].evidence_slot_status[].status": {
"value": "missing",
"review_code": "SLOT_STATUS_UNMAPPED_REVIEW"
}
},
"required_derivation": { "required_derivation": {
"bo_seed_candidates[].element_fact_candidates[].source_id": { "bo_seed_candidates[].element_fact_candidates[].source_id": {
"rule": "first_universe_member_of_sibling_array", "rule": "first_universe_member_of_sibling_array",
@@ -314,6 +325,10 @@
"rule": "from_context", "rule": "from_context",
"key": "r0_membership_key" "key": "r0_membership_key"
}, },
"bo_seed_candidates[].evidence_slot_status[].status": {
"rule": "constant",
"value": "missing"
},
"bo_seed_candidates[].evidence_slot_status[].slot_id": { "bo_seed_candidates[].evidence_slot_status[].slot_id": {
"rule": "rename_sibling", "rule": "rename_sibling",
"sibling_candidates": [ "sibling_candidates": [
@@ -294,6 +294,16 @@ def _build_event_candidate_map(event_obj: Any) -> dict[str, Any]:
"fraction_ref": cand.get("fraction_ref"), "fraction_ref": cand.get("fraction_ref"),
"confidence": cand.get("confidence"), "confidence": cand.get("confidence"),
} }
# C-03: creditor/debtor direction and support directness only. The shared source universe
# is near its 260,000-char preflight limit; full support_locators/legal_keywords/location
# pushed it over on the 2026-11-04 run (100 events). Keys are omitted when empty.
direction = cand.get("obligation_direction")
if isinstance(direction, dict) and any(direction.values()):
record["obligation_direction"] = direction
directness = [{"directness": loc.get("directness")}
for loc in cand.get("support_locators") or [] if isinstance(loc, dict)]
if directness:
record["support_locators"] = directness
by_candidate_id[cid] = record by_candidate_id[cid] = record
by_evidence_index.setdefault(evidence_index, []).append(cid) by_evidence_index.setdefault(evidence_index, []).append(cid)
for ref in refs: for ref in refs:
@@ -294,6 +294,16 @@ def _build_event_candidate_map(event_obj: Any) -> dict[str, Any]:
"fraction_ref": cand.get("fraction_ref"), "fraction_ref": cand.get("fraction_ref"),
"confidence": cand.get("confidence"), "confidence": cand.get("confidence"),
} }
# C-03: creditor/debtor direction and support directness only. The shared source universe
# is near its 260,000-char preflight limit; full support_locators/legal_keywords/location
# pushed it over on the 2026-11-04 run (100 events). Keys are omitted when empty.
direction = cand.get("obligation_direction")
if isinstance(direction, dict) and any(direction.values()):
record["obligation_direction"] = direction
directness = [{"directness": loc.get("directness")}
for loc in cand.get("support_locators") or [] if isinstance(loc, dict)]
if directness:
record["support_locators"] = directness
by_candidate_id[cid] = record by_candidate_id[cid] = record
by_evidence_index.setdefault(evidence_index, []).append(cid) by_evidence_index.setdefault(evidence_index, []).append(cid)
for ref in refs: for ref in refs:
@@ -29,6 +29,7 @@ REVIEW_CROSS_DOMAIN = "PART3_EFFECT_TYPE_CROSS_DOMAIN"
REVIEW_CALC_DANGLING = "PART3_CALCULATION_REF_DANGLING" REVIEW_CALC_DANGLING = "PART3_CALCULATION_REF_DANGLING"
REVIEW_BO_UNATTACHED = "PART3_BO_UNATTACHED" REVIEW_BO_UNATTACHED = "PART3_BO_UNATTACHED"
REVIEW_BO_UNRESOLVED = "PART3_BO_DOMAIN_UNRESOLVED" REVIEW_BO_UNRESOLVED = "PART3_BO_DOMAIN_UNRESOLVED"
REVIEW_ROUTE_NO_BO = "PART3_ROUTE_CANDIDATE_NOT_IN_BO"
SG13_ROUTE_RECORD_TYPE = "legal_effect_route" SG13_ROUTE_RECORD_TYPE = "legal_effect_route"
@@ -199,6 +200,7 @@ def compile_structure_seeds(activation_manifest: Any,
for position, row in enumerate(index_entries) for position, row in enumerate(index_entries)
if isinstance(row.get("domain_id"), str)} if isinstance(row.get("domain_id"), str)}
known_domain_ids = set(index_position) known_domain_ids = set(index_position)
residual_domains = {row.get("domain_id") for row in index_entries if row.get("kind") == "residual"}
review_items: list[dict[str, Any]] = [] review_items: list[dict[str, Any]] = []
audit: dict[str, Any] = {"sidecar_dialects": {}, "input_gaps": [], audit: dict[str, Any] = {"sidecar_dialects": {}, "input_gaps": [],
@@ -309,9 +311,6 @@ def compile_structure_seeds(activation_manifest: Any,
record["registered_declared"] = item["registered"] record["registered_declared"] = item["registered"]
if domain_id == e13_domain and e13_extension_key: if domain_id == e13_domain and e13_extension_key:
record["extension_key"] = e13_extension_key record["extension_key"] = e13_extension_key
if domain_id == "E-00":
# E-00 특칙 — 잔여 수집기 유래 구조는 검토 필수(신전략서 §4.2).
record["review_required"] = True
records[(domain_id, type_id)] = record records[(domain_id, type_id)] = record
# ---------------- L0-2b · 슬라이스 투영 정합 ---------------- # ---------------- L0-2b · 슬라이스 투영 정합 ----------------
@@ -395,6 +394,14 @@ def compile_structure_seeds(activation_manifest: Any,
"type_id": type_id, "signal_id": route.get("signal_id"), "type_id": type_id, "signal_id": route.get("signal_id"),
"detail": "registered_false_route_attached", "detail": "registered_false_route_attached",
}) })
if details.get("bo_absent") is True:
# BO 가 없는 후보의 route 도 붙인다. 지우지 않고 표시한다(전략서 v.2 축 C).
if REVIEW_ROUTE_NO_BO not in record["review_codes"]:
record["review_codes"].append(REVIEW_ROUTE_NO_BO)
record["review_required"] = True
review(REVIEW_ROUTE_NO_BO, "SOFT_WARNING", key[0], {
"type_id": type_id, "signal_id": route.get("signal_id"),
})
declared_flag = record.get("registered_declared") declared_flag = record.get("registered_declared")
if isinstance(declared_flag, bool) and isinstance(registered, bool) \ if isinstance(declared_flag, bool) and isinstance(registered, bool) \
and declared_flag != registered: and declared_flag != registered:
@@ -467,14 +474,26 @@ def compile_structure_seeds(activation_manifest: Any,
continue continue
keywords = _strings(bo.get("Legal_Keywords")) keywords = _strings(bo.get("Legal_Keywords"))
attached_here = False attached_here = False
for domain_id in resolved: # 도메인을 건너 병합된 BO — 유형마다 그 유형을 낸 도메인에만 붙인다. F0 가 provenance 에 남긴다.
for type_id in keywords: absorbed_sources = [_dict(row) for row in provenance.get("absorbed_sources") or []]
record = records.get((domain_id, type_id)) own_keywords = _strings(provenance.get("source_keywords")) if absorbed_sources else keywords
if record is not None: pairs = [(domain_id, type_id) for domain_id in resolved for type_id in own_keywords]
attached_here = True for source in absorbed_sources:
if isinstance(bo_id, str) and bo_id not in record["source_bo_ids"]: pairs.extend((domain_id, type_id)
record["source_bo_ids"].append(bo_id) for domain_id in resolve_source_domains(source.get("source_domain"), alias_targets, known_domain_ids)
record["source_bo_ids"].sort() for type_id in _strings(source.get("Legal_Keywords")))
if absorbed_sources:
# 그 도메인이 선언하지 않은 유형의 route 는 L0-4 가 선언 도메인에 붙였다. BO 도 같은 곳에 붙인다.
pairs = [target for key in pairs for target in
([key] if key in records else
[(d, key[1]) for d in declaring_domains.get(key[1], []) if (d, key[1]) in records])]
for key in pairs:
record = records.get(key)
if record is not None:
attached_here = True
if isinstance(bo_id, str) and bo_id not in record["source_bo_ids"]:
record["source_bo_ids"].append(bo_id)
record["source_bo_ids"].sort()
if attached_here: if attached_here:
bo_attached.append(bo_id if isinstance(bo_id, str) else "") bo_attached.append(bo_id if isinstance(bo_id, str) else "")
else: else:
@@ -497,6 +516,9 @@ def compile_structure_seeds(activation_manifest: Any,
record["review_codes"].sort() record["review_codes"].sort()
if record["review_codes"]: if record["review_codes"]:
record["review_required"] = True record["review_required"] = True
# 잔여 수집기 특칙 — 붙은 것이 있을 때만 검토 필수다. 빈 구조에는 검토할 것이 없다.
if record["domain_id"] in residual_domains and (record["routes"] or record["source_bo_ids"]):
record["review_required"] = True
status = "READY_WITH_REVIEW" if review_items else "READY" status = "READY_WITH_REVIEW" if review_items else "READY"
bundle = { bundle = {
@@ -29,6 +29,7 @@ REVIEW_CROSS_DOMAIN = "PART3_EFFECT_TYPE_CROSS_DOMAIN"
REVIEW_CALC_DANGLING = "PART3_CALCULATION_REF_DANGLING" REVIEW_CALC_DANGLING = "PART3_CALCULATION_REF_DANGLING"
REVIEW_BO_UNATTACHED = "PART3_BO_UNATTACHED" REVIEW_BO_UNATTACHED = "PART3_BO_UNATTACHED"
REVIEW_BO_UNRESOLVED = "PART3_BO_DOMAIN_UNRESOLVED" REVIEW_BO_UNRESOLVED = "PART3_BO_DOMAIN_UNRESOLVED"
REVIEW_ROUTE_NO_BO = "PART3_ROUTE_CANDIDATE_NOT_IN_BO"
SG13_ROUTE_RECORD_TYPE = "legal_effect_route" SG13_ROUTE_RECORD_TYPE = "legal_effect_route"
@@ -199,6 +200,7 @@ def compile_structure_seeds(activation_manifest: Any,
for position, row in enumerate(index_entries) for position, row in enumerate(index_entries)
if isinstance(row.get("domain_id"), str)} if isinstance(row.get("domain_id"), str)}
known_domain_ids = set(index_position) known_domain_ids = set(index_position)
residual_domains = {row.get("domain_id") for row in index_entries if row.get("kind") == "residual"}
review_items: list[dict[str, Any]] = [] review_items: list[dict[str, Any]] = []
audit: dict[str, Any] = {"sidecar_dialects": {}, "input_gaps": [], audit: dict[str, Any] = {"sidecar_dialects": {}, "input_gaps": [],
@@ -309,9 +311,6 @@ def compile_structure_seeds(activation_manifest: Any,
record["registered_declared"] = item["registered"] record["registered_declared"] = item["registered"]
if domain_id == e13_domain and e13_extension_key: if domain_id == e13_domain and e13_extension_key:
record["extension_key"] = e13_extension_key record["extension_key"] = e13_extension_key
if domain_id == "E-00":
# E-00 특칙 — 잔여 수집기 유래 구조는 검토 필수(신전략서 §4.2).
record["review_required"] = True
records[(domain_id, type_id)] = record records[(domain_id, type_id)] = record
# ---------------- L0-2b · 슬라이스 투영 정합 ---------------- # ---------------- L0-2b · 슬라이스 투영 정합 ----------------
@@ -395,6 +394,14 @@ def compile_structure_seeds(activation_manifest: Any,
"type_id": type_id, "signal_id": route.get("signal_id"), "type_id": type_id, "signal_id": route.get("signal_id"),
"detail": "registered_false_route_attached", "detail": "registered_false_route_attached",
}) })
if details.get("bo_absent") is True:
# BO 가 없는 후보의 route 도 붙인다. 지우지 않고 표시한다(전략서 v.2 축 C).
if REVIEW_ROUTE_NO_BO not in record["review_codes"]:
record["review_codes"].append(REVIEW_ROUTE_NO_BO)
record["review_required"] = True
review(REVIEW_ROUTE_NO_BO, "SOFT_WARNING", key[0], {
"type_id": type_id, "signal_id": route.get("signal_id"),
})
declared_flag = record.get("registered_declared") declared_flag = record.get("registered_declared")
if isinstance(declared_flag, bool) and isinstance(registered, bool) \ if isinstance(declared_flag, bool) and isinstance(registered, bool) \
and declared_flag != registered: and declared_flag != registered:
@@ -467,14 +474,26 @@ def compile_structure_seeds(activation_manifest: Any,
continue continue
keywords = _strings(bo.get("Legal_Keywords")) keywords = _strings(bo.get("Legal_Keywords"))
attached_here = False attached_here = False
for domain_id in resolved: # 도메인을 건너 병합된 BO — 유형마다 그 유형을 낸 도메인에만 붙인다. F0 가 provenance 에 남긴다.
for type_id in keywords: absorbed_sources = [_dict(row) for row in provenance.get("absorbed_sources") or []]
record = records.get((domain_id, type_id)) own_keywords = _strings(provenance.get("source_keywords")) if absorbed_sources else keywords
if record is not None: pairs = [(domain_id, type_id) for domain_id in resolved for type_id in own_keywords]
attached_here = True for source in absorbed_sources:
if isinstance(bo_id, str) and bo_id not in record["source_bo_ids"]: pairs.extend((domain_id, type_id)
record["source_bo_ids"].append(bo_id) for domain_id in resolve_source_domains(source.get("source_domain"), alias_targets, known_domain_ids)
record["source_bo_ids"].sort() for type_id in _strings(source.get("Legal_Keywords")))
if absorbed_sources:
# 그 도메인이 선언하지 않은 유형의 route 는 L0-4 가 선언 도메인에 붙였다. BO 도 같은 곳에 붙인다.
pairs = [target for key in pairs for target in
([key] if key in records else
[(d, key[1]) for d in declaring_domains.get(key[1], []) if (d, key[1]) in records])]
for key in pairs:
record = records.get(key)
if record is not None:
attached_here = True
if isinstance(bo_id, str) and bo_id not in record["source_bo_ids"]:
record["source_bo_ids"].append(bo_id)
record["source_bo_ids"].sort()
if attached_here: if attached_here:
bo_attached.append(bo_id if isinstance(bo_id, str) else "") bo_attached.append(bo_id if isinstance(bo_id, str) else "")
else: else:
@@ -497,6 +516,9 @@ def compile_structure_seeds(activation_manifest: Any,
record["review_codes"].sort() record["review_codes"].sort()
if record["review_codes"]: if record["review_codes"]:
record["review_required"] = True record["review_required"] = True
# 잔여 수집기 특칙 — 붙은 것이 있을 때만 검토 필수다. 빈 구조에는 검토할 것이 없다.
if record["domain_id"] in residual_domains and (record["routes"] or record["source_bo_ids"]):
record["review_required"] = True
status = "READY_WITH_REVIEW" if review_items else "READY" status = "READY_WITH_REVIEW" if review_items else "READY"
bundle = { bundle = {
@@ -39,12 +39,12 @@
}, },
"bo_attachment": { "bo_attachment": {
"alias_resolution": "provenance.source_domain 이 registry 도메인 ID 면 [그 값], 아니면 legacy_alias_targets[값] 목록(다중 타깃 실재 — 단일 primary 개념 없음), 어디에도 없으면 PART3_BO_DOMAIN_UNRESOLVED 검토로 격리.", "alias_resolution": "provenance.source_domain 이 registry 도메인 ID 면 [그 값], 아니면 legacy_alias_targets[값] 목록(다중 타깃 실재 — 단일 primary 개념 없음), 어디에도 없으면 PART3_BO_DOMAIN_UNRESOLVED 검토로 격리.",
"join": "해소된 모든 도메인 d 에 대해 t ∈ BO.Legal_Keywords 인 구조 레코드 (d, t) 에 source_bo_ids 로 부착을 시도한다.", "join": "해소된 모든 도메인 d 에 대해 t ∈ BO.Legal_Keywords 인 구조 레코드 (d, t) 에 source_bo_ids 로 부착을 시도한다. provenance.absorbed_sources 가 있으면 남는 도메인은 provenance.source_keywords 로, 흡수 도메인은 그 항목의 Legal_Keywords 로 시도하고, 그 도메인이 선언하지 않은 유형은 선언 도메인에 붙인다.",
"silence_forbidden": "Legal_Keywords 가 비었거나 어느 (d, t) 에도 닿지 않는 BO 는 PART3_BO_UNATTACHED 검토로 싣는다.", "silence_forbidden": "Legal_Keywords 가 비었거나 어느 (d, t) 에도 닿지 않는 BO 는 PART3_BO_UNATTACHED 검토로 싣는다.",
"purpose": "원본 review_code 와 마찬가지로 — BO 연결을 잃지 않기 위해서다. SG 층의 source_bo_ids 가 비어 있어도 이 조인이 BO↔구조 연결을 세운다." "purpose": "원본 review_code 와 마찬가지로 — BO 연결을 잃지 않기 위해서다. SG 층의 source_bo_ids 가 비어 있어도 이 조인이 BO↔구조 연결을 세운다."
}, },
"sg11_join": { "sg11_join": {
"key": "SG-11 레코드의 signal_id (worker request_id 승계값 — details.request_id 는 보장되지 않는 키라 쓰지 않는다)", "key": "SG-11 레코드의 signal_id (s3_domain_seed_adapter 가 <candidate_ref>:<k> 로 만든 request_id)",
"counterpart": "domain_signal_envelope.calculation_refs", "counterpart": "domain_signal_envelope.calculation_refs",
"unlinked_rule": "봉투 참조에 연결되지 않은 SG-11 레코드는 구조에 싣지 않되 영수증에 미연결 계수로 형식화 기록한다.", "unlinked_rule": "봉투 참조에 연결되지 않은 SG-11 레코드는 구조에 싣지 않되 영수증에 미연결 계수로 형식화 기록한다.",
"dangling_rule": "봉투에 있는데 SG-11 에 없는 참조는 PART3_CALCULATION_REF_DANGLING 검토." "dangling_rule": "봉투에 있는데 SG-11 에 없는 참조는 PART3_CALCULATION_REF_DANGLING 검토."
@@ -75,9 +75,13 @@
"PART3_EFFECT_TYPE_CROSS_DOMAIN", "PART3_EFFECT_TYPE_CROSS_DOMAIN",
"PART3_CALCULATION_REF_DANGLING", "PART3_CALCULATION_REF_DANGLING",
"PART3_BO_UNATTACHED", "PART3_BO_UNATTACHED",
"PART3_BO_DOMAIN_UNRESOLVED" "PART3_BO_DOMAIN_UNRESOLVED",
"PART3_ROUTE_CANDIDATE_NOT_IN_BO",
"PART3_SIGNAL_MANIFEST_BLOCKED"
], ],
"hard_error_codes": [ "hard_error_codes": [
"PART3_READ_SET_MISMATCH",
"PART3_SG01_COPY_MISMATCH",
"PART3_ASSET_DEPLOYMENT_INCOMPLETE", "PART3_ASSET_DEPLOYMENT_INCOMPLETE",
"PART3_POLICY_INVALID", "PART3_POLICY_INVALID",
"PART3_STRUCTURE_SCHEMA_STALE", "PART3_STRUCTURE_SCHEMA_STALE",
@@ -93,6 +97,6 @@
"PART3_EXPECTED_RUNNABLE_EMPTY", "PART3_EXPECTED_RUNNABLE_EMPTY",
"PART3_SIDECAR_ABSENT_FOR_DECLARING_DOMAIN" "PART3_SIDECAR_ABSENT_FOR_DECLARING_DOMAIN"
], ],
"e00_rule": "E-00(잔여 수집기)에서 온 구조 레코드는 review_required true 를 강제한다.", "e00_rule": "registry 색인 kind 가 residual 인 도메인의 구조 레코드는 route 나 BO 가 붙었을 때 review_required true 를 강제한다.",
"sidecar_absence_rule": "structure_types 선언이 0 인 도메인(오늘 EC-00 하나)의 사이드카 부재는 정상 — 스킵하고 영수증에 기록한다. 선언이 있는 도메인의 부재·미등재는 경성 실패다." "sidecar_absence_rule": "structure_types 선언이 0 인 도메인(오늘 EC-00 하나)의 사이드카 부재는 정상 — 스킵하고 영수증에 기록한다. 선언이 있는 도메인의 부재·미등재는 경성 실패다."
} }
@@ -259,6 +259,7 @@ def validate_worker_output(
allowed_calc = {str(v) for v in (declarations.get("calculation_domains") or [])} allowed_calc = {str(v) for v in (declarations.get("calculation_domains") or [])}
allowed_slots = {str(v) for v in (declarations.get("element_slot_ids") or [])} allowed_slots = {str(v) for v in (declarations.get("element_slot_ids") or [])}
allowed_slots |= {str(v) for v in (declarations.get("opposing_fact_slot_ids") or [])} allowed_slots |= {str(v) for v in (declarations.get("opposing_fact_slot_ids") or [])}
allowed_types = {str(v) for v in (declarations.get("structure_type_ids") or [])}
declared_candidates = root.get("bo_seed_candidates") declared_candidates = root.get("bo_seed_candidates")
declared_candidates = declared_candidates if isinstance(declared_candidates, list) else [] declared_candidates = declared_candidates if isinstance(declared_candidates, list) else []
for index, candidate in enumerate(declared_candidates): for index, candidate in enumerate(declared_candidates):
@@ -274,6 +275,19 @@ def validate_worker_output(
"path": "$.bo_seed_candidates[%d].calculation_requests[%d].calculation_domain" % (index, order), "path": "$.bo_seed_candidates[%d].calculation_requests[%d].calculation_domain" % (index, order),
"message": "선언 밖 계산 도메인: %s" % code, "message": "선언 밖 계산 도메인: %s" % code,
}) })
# 미등록 효과는 registered:false 로 남기는 것이 정상이다. 표시와 선언이 어긋날 때만 경고한다.
effects = candidate.get("legal_effect_candidates")
for order, effect in enumerate(effects if isinstance(effects, list) else []):
type_id = effect.get("type_id") if isinstance(effect, dict) else None
registered = effect.get("registered") if isinstance(effect, dict) else None
if isinstance(type_id, str) and type_id and allowed_types and (
(registered is True and type_id not in allowed_types)
or (registered is False and type_id in allowed_types)):
warnings.append({
"code": "STRUCTURE_TYPE_NOT_DECLARED",
"path": "$.bo_seed_candidates[%d].legal_effect_candidates[%d].type_id" % (index, order),
"message": "registered=%s 와 선언 어휘가 어긋난다: %s" % (registered, type_id),
})
slots = candidate.get("evidence_slot_status") slots = candidate.get("evidence_slot_status")
for order, slot in enumerate(slots if isinstance(slots, list) else []): for order, slot in enumerate(slots if isinstance(slots, list) else []):
slot_id = slot.get("slot_id") if isinstance(slot, dict) else None slot_id = slot.get("slot_id") if isinstance(slot, dict) else None
@@ -259,6 +259,7 @@ def validate_worker_output(
allowed_calc = {str(v) for v in (declarations.get("calculation_domains") or [])} allowed_calc = {str(v) for v in (declarations.get("calculation_domains") or [])}
allowed_slots = {str(v) for v in (declarations.get("element_slot_ids") or [])} allowed_slots = {str(v) for v in (declarations.get("element_slot_ids") or [])}
allowed_slots |= {str(v) for v in (declarations.get("opposing_fact_slot_ids") or [])} allowed_slots |= {str(v) for v in (declarations.get("opposing_fact_slot_ids") or [])}
allowed_types = {str(v) for v in (declarations.get("structure_type_ids") or [])}
declared_candidates = root.get("bo_seed_candidates") declared_candidates = root.get("bo_seed_candidates")
declared_candidates = declared_candidates if isinstance(declared_candidates, list) else [] declared_candidates = declared_candidates if isinstance(declared_candidates, list) else []
for index, candidate in enumerate(declared_candidates): for index, candidate in enumerate(declared_candidates):
@@ -274,6 +275,19 @@ def validate_worker_output(
"path": "$.bo_seed_candidates[%d].calculation_requests[%d].calculation_domain" % (index, order), "path": "$.bo_seed_candidates[%d].calculation_requests[%d].calculation_domain" % (index, order),
"message": "선언 밖 계산 도메인: %s" % code, "message": "선언 밖 계산 도메인: %s" % code,
}) })
# 미등록 효과는 registered:false 로 남기는 것이 정상이다. 표시와 선언이 어긋날 때만 경고한다.
effects = candidate.get("legal_effect_candidates")
for order, effect in enumerate(effects if isinstance(effects, list) else []):
type_id = effect.get("type_id") if isinstance(effect, dict) else None
registered = effect.get("registered") if isinstance(effect, dict) else None
if isinstance(type_id, str) and type_id and allowed_types and (
(registered is True and type_id not in allowed_types)
or (registered is False and type_id in allowed_types)):
warnings.append({
"code": "STRUCTURE_TYPE_NOT_DECLARED",
"path": "$.bo_seed_candidates[%d].legal_effect_candidates[%d].type_id" % (index, order),
"message": "registered=%s 와 선언 어휘가 어긋난다: %s" % (registered, type_id),
})
slots = candidate.get("evidence_slot_status") slots = candidate.get("evidence_slot_status")
for order, slot in enumerate(slots if isinstance(slots, list) else []): for order, slot in enumerate(slots if isinstance(slots, list) else []):
slot_id = slot.get("slot_id") if isinstance(slot, dict) else None slot_id = slot.get("slot_id") if isinstance(slot, dict) else None
@@ -0,0 +1,63 @@
# Gemini LLM 사용 시 `thinking_level` 설정 관련 질의응답
## 요구사항
stage_1_part_1_v.8.yml`의 LLM 작업 sub-task들 중 Gemini 모델을 사용하는 작업들은 아래와 같다.
`Task_A0_domain_screener_01`
`Task_B1_map_doc_*`
`Task_B2_map_events_*`
`Task_B1r_map_doc_*`
`Task_B2r_map_events_*`
`Task_B12_gate_llm_adjudicator`
`Task_V1_value_facts_*`
각 sub-task별 Gemini 모델은 그대로 유지하고, token budget은 항상 high로 잡고, `thinking_level`은 모델별로 다음과 같이 설정하고자 한다.
`Task_A0_domain_screener_01` -> medium
`Task_B1_map_doc_*` -> medium
`Task_B2_map_events_*` -> medium
`Task_B1r_map_doc_*` -> high
`Task_B2r_map_events_*` -> high
`Task_B12_gate_llm_adjudicator` -> low
`Task_V1_value_facts_*` -> low
Gemini 모델을 사용하는 sub-task의 prompt의 어떤 위치에 어떤 방식으로 위 요구사항을 반영할 수 있는가? 두 문단 이내로 설명하라.
## 답변
**이 요구사항은 프롬프트에 넣을 수 있는 내용이 아닙니다**. `thinking_level`과 출력 토큰 한도는 모델 호출의 API 파라미터(`GenerateContentConfig`)라서, 프롬프트에 글로 써 두어도 모델은 그 값을 지키지 않습니다. 또 "사고 과정 작성" 같은 문구가 본문에 섞이면 V1에서처럼 응답에 사고 과정이 노출될 위험만 커집니다. 반영할 곳은 각 task의 YAML 키입니다. 사고 수준은 `llm_reasoning`에 medium, high, low를 적고, 출력 한도는 `llm_token_limit`에 적습니다. 브리지는 이미 `llm_token_limit`을 Gemini `max_output_tokens`로 보내고 있으므로(773행), "token budget을 항상 high"로 두려면 7개 task 모두에 `llm_token_limit: 65536`(Gemini 3.x 상한)을 넣으면 됩니다. 지금 이 키는 V1에만 32,000으로 있고, 나머지 task에는 없습니다. `thinking_level` 값은 지정하신 대로 넣으면 됩니다. A0_01·B1·B2는 medium, B1r·B2r은 high, B12·V1은 low입니다. 지금 YAML과 비교하면 V1만 medium에서 low로 바뀌고, 나머지는 이미 같은 값입니다.
다만 YAML만 바꿔서는 `thinking_level`이 실제로 전송되지 않습니다. 배포 브리지의 770행은 `llm_reasoning`을 여전히 `ThinkingConfig(thinking_budget=숫자)`로 바꿔 보냅니다. 그래서 YAML에 medium이라고 적어도 모델에는 숫자 예산 8,192가 가고, 지난번 사고 토큰 초과의 원인으로 추정한 경로가 그대로 남습니다. 백엔드에서 두 가지를 고쳐야 합니다. 첫째, Gemini 3.x 모델에서는 `llm_reasoning` 값을 `ThinkingConfig(thinking_level=값)`으로 보내야 하고, 둘을 함께 보내면 오류가 나므로 `thinking_budget`은 빼야 합니다. 둘째, `usage_metadata.thoughts_token_count`를 로그에 남겨 실제 사고량을 확인할 수 있게 해야 합니다. 이 수정은 백엔드 코드 변경과 배포가 필요하므로 승인이 있어야 합니다. 프롬프트에서는 한 가지만 하면 됩니다. 앞서 제안한 출력 규칙("출력은 JSON 하나, 첫 글자는 `{`, 사고 과정·설명 금지")을 각 프롬프트의 `<COMMON_CACHE_PREFIX_*>` 안쪽 고정 지시부 끝에 넣는 것입니다. 이것은 사고량을 정하는 장치가 아니라, 사고가 길어져도 본문에 섞이지 않게 막는 보조 장치입니다.
---
## 요구사항
위 답변에 근거하여 질문한다. `llm_reasoning`에 medium, high, low를 적는 것이 `thinking_level` 값을 지정하는 것과 정확히 동일(equivalent)한가? 예, 아니오로 답하라. 만일 답이 '아니오'라면, `thinking_level` 값을 파라미터값으로 yaml에 작성하는 방법을 한 문단 내로 설명하라. 답이 '예'라면 설명은 생략한다.
## 답변
**아니오.** 같지 않습니다.
`llm_reasoning: medium`을 적어도 배포 브리지(770행)가 이 값을 숫자 예산 `thinking_budget=8192`로 바꿔 보냅니다. low는 1,024, high는 32,768이 됩니다. Gemini API 쪽에서도 하위 호환용 숫자 예산과 `thinking_level`은 서로 다른 파라미터입니다.
`thinking_level`을 YAML에 적을 방법도 지금은 없습니다. 배포 백엔드(`agent.py`)가 task 설정에서 읽는 모델 관련 키는 아홉 개뿐입니다.
- `llm_provider`
- `llm_model`
- `llm_reasoning`
- `llm_endpoint`
- `llm_verbosity`
- `llm_token_limit`
- `llm_prompt_cache_key`
- `llm_history_continuous`
- `llm_result_envelope`
여기에 `thinking_level`이나 임의의 생성 설정을 그대로 넘겨주는 키는 없습니다. YAML에 `thinking_level: medium`을 새로 적어도 무시됩니다.
YAML에서 값으로 지정하려면 백엔드를 먼저 고쳐야 합니다(승인이 필요한 코드 변경과 배포입니다). 방법은 둘 중 하나입니다.
- **(가) 새 키 추가:** `agent.py`가 `config.get("llm_thinking_level")`을 읽어 Bridge에 넘기게 하고, `bridge.py`의 Gemini 경로가 이 값이 있을 때 `types.ThinkingConfig(thinking_level=값)`만 보내게 합니다. 이 경우 `thinking_budget`은 빼야 합니다. 둘을 함께 보내면 오류가 나기 때문입니다.
- **(나) 기존 키 재해석:** 브리지가 Gemini 3.x 모델에서는 `llm_reasoning` 값을 숫자로 바꾸지 않고 `thinking_level`로 그대로 보내게 합니다.
(가)로 고치면 YAML에는 각 Gemini task에 `llm_thinking_level: medium`처럼 적습니다. (나)로 고치면 지금처럼 `llm_reasoning: medium`이라고 적은 값이 그대로 `thinking_level`이 됩니다. 이 경우 YAML은 바꿀 필요가 없고, 그때부터 두 방식이 같아집니다.
@@ -0,0 +1,50 @@
# Stage 1 Part 1 LLM sub-task 추론 수준(reasoning level) 현황과 제안
- **대상:** `1. Stage_1/v.8/stage_1_part_1_v.8.yml`(sha256 `41663b8f…`). YAML은 수정하지 않았다.
- **실측 근거:** 2026-11-03 세션 `2ef6f8fc`의 성공 실행(`Testrun/Nov_03/결과보고서_v2_part_1.md`). 총 12분 50초, $1.61.
- **백엔드 근거:** 배포 브리지 `llm_bridge/bridge.py`를 읽기 전용으로 확인했다.
- Gemini(native): `llm_reasoning`을 `thinking_budget`으로 바꾼다. low 1,024 · medium 8,192 · high 32,768토큰이다(768행). `llm_token_limit`은 `max_output_tokens`가 된다.
- OpenAI chat.completions: `reasoning_effort=<값>`으로 보낸다(194~195행).
- **"최적"의 정의:** sub-task의 목적을 달성하는 가장 낮은 추론 수준이다. 다만 전체 시간은 임계 경로(A0_01 → Task_A)만 줄인다.
## 1. 현행 설정과 실측
| sub-task | 목적 | 모델 | reasoning (thinking 예산) | 기타 | 호출 | 평균 / 최대 시간 | 호출당 출력(추론 포함) | 임계 경로 |
|---|---|---|---|---|---:|---|---:|---|
| Task_A0_domain_screener_01 | 상담록과 단서 사전으로 26개 법리 도메인의 활성 후보·근거·검토 항목 초안(JSON) | gemini-3.8-flash | **medium** (8,192) | verbosity low | 1 | 276s | 7,437 | **예** |
| Task_A_client_goal | 의뢰인 목표, 당사자, 피고 자격, 쟁점, 원고 적격, 점유·지배 지도(client_goal.json, 11.7만 자) | gpt-6.1-sol | **high** | verbosity 기본(medium) | 1 | 472s | 40,677 | **예** |
| Task_B1_map_doc_* | 증거문서 1건의 색인(문서 성격, 권위, 증거 구성요소 슬롯) | gemini-3.8-flash | **high** (32,768) | verbosity medium, 동시 12 | 30 | 108s / 179s | 2,066 | 아니오(약 2분 여유) |
| Task_B2_map_events_* | 증거문서 1건의 사건·행위 후보, 채권 방향(obligee·obligor) | gemini-3.8-flash | **high** (32,768) | verbosity medium, 동시 12 | 30 | 166s / 323s | 4,287 | 아니오 |
| Task_B1r_map_doc_* | B1 고장 part만 1회 재생성 | gemini-3.8-flash | **high** | 동시 12 | 0(미발동) | — | — | 발동 시 B 경로 |
| Task_B2r_map_events_* | B2 고장 part만 1회 재생성 | gemini-3.8-flash | **high** | 동시 12 | 0(미발동) | — | — | 발동 시 B 경로 |
| Task_B12_gate_llm_adjudicator | B2 게이트 예외 14건에 SOFT·HARD·DISMISS·ESCALATE 판정 | gemini-3.5-flash-lite | **low** (1,024) | verbosity low | 1 | 16s | 3,226 | 아니오 |
| Task_V1_value_facts_* | 증거문서 1건의 금액·면적 등 값 사실 추출(원문 인용) | gemini-3.8-flash | **medium** (8,192) | token_limit 32,000, 동시 8 | 30 | 79s / 237s | 835 | 아니오 |
- 임계 경로 = A0_01 276s + 코드 약 10s + Task_A 472s + 코드 약 9s ≈ 769s(전체 시간).
- B 사슬은 08:15:50에, V 사슬은 08:11:14에 끝나 T9를 기다렸다. 그래서 B·V를 빠르게 해도 지금은 전체 시간이 줄지 않는다.
## 2. 제안
| sub-task | 현행 | **제안** | 근거 | 기대 효과 | 위험 · 확인 방법 |
|---|---|---|---|---|---|
| A0_01 | medium | **low** | 하는 일은 단서 사전과 상담록을 맞대는 라우팅이다. 근거 인용·보존 등식·도메인 집합은 A0_02 코드가 검증하고 실패하면 BLOCKED가 된다. 11-03 2차 실행에서 207초를 생각하고 9토큰을 냈듯이 사고 시간이 대부분이다 | 임계 경로 276s의 상당 부분. 크기는 UNVERIFIED | 후보 누락·과선언. A0_01은 재시도가 없어 헛 실패 한 번이 전체 BLOCKED다. 같은 입력으로 low·medium을 각 3회 돌려 후보 집합·검토 항목이 같은지 비교한 뒤 확정한다 |
| Task_A | high | **medium** | 최대 비용·시간 task다. 출력 40,677토큰 중 결과 본문(11.7만 자)이 대부분이라 시간은 생성량이 정한다. 추론 토큰 몫만 줄어든다 | 472s 중 추론 몫(크기 UNVERIFIED). This is an inference without much evidence: 대략 10~25% | 피고 자격·당사자 판단은 Part 2~4와 S2_00 피고 게이트의 입력이다(10-11 오칠성·나일오 과선언 사례). 같은 입력으로 high·medium의 `defendant_qualification`·`parties`·`claim_type_candidates`를 비교한다. 차이가 나면 high를 유지한다 |
| B1 | high | **medium** | 문서 1건 단위의 구조화 추출이다. 게이트(B1 결정적 게이트·B12)와 복구 사슬이 뒤를 받친다. 호출당 출력이 2천 토큰이라 32K 예산은 과하다 | B 사슬 시간·비용 감소. 지금은 임계 경로가 아니라 전체 시간에는 영향 없음 | suspect·REVIEW 증가 여부를 B1 게이트 `suspect_count`(현 6)와 복구 발동 수로 본다 |
| B2 | high | **medium** | 사건 후보와 채권 방향은 B1보다 판단이 많지만 규칙형이다(event_kind 매핑 양성 조건). 최대 323s로 B 사슬의 병목이다 | B 사슬 단축. A 사슬을 줄이면 B가 새 임계 경로가 될 수 있어 함께 줄여야 효과가 난다 | `exception_count`(현 14)·HARD_WARNING·dedup 변화 비교. 나빠지면 high로 되돌린다 |
| B1r·B2r | high | **high 유지** | 1차 시도가 실패한 문서만 1회 다시 만든다. 드물게 돌고(이번 0회), 다시 실패하면 그대로 남는다 | — | — |
| B12 | low | **low 유지** | 16초, 예외 14건 분류다. 이미 최저 수준이다 | — | — |
| V1 | medium | **low** + 응답 형식 점검 | 원문에 적힌 값을 인용해 옮기는 추출이다. gate가 원문 대조로 검증한다. 이번 실행에서 4건이 `max_tokens`로 잘렸고, 그중 2건은 응답 본문에 사고 과정("Wait! …")이 그대로 들어갔다. 더 생각해서 더 좋아진 사례가 아니다 | V 사슬 시간 감소(현 최대 237s). 전체 시간에는 영향 없음 | low에서 실패 4건(E-007·E-011·E-013·E-024)이 줄어드는지 본다. 잘림 원인이 사고 토큰인지는 UNVERIFIED다(아래 §3) |
**적용 순서 권고**
1. **V1 low, B1·B2 medium.** 임계 경로 밖이라 전체 시간 위험이 없다. 비용이 줄고 품질 변화를 게이트 수치로 바로 볼 수 있다.
2. **A0_01 low.** 3회 비교에서 후보 집합이 같으면 확정한다.
3. **Task_A medium.** 피고 자격·당사자 비교에서 차이가 없을 때만 확정한다.
2와 3을 함께 적용하면, B2 최대 323s가 포함된 B 사슬(약 10분 38초)이 새 임계 경로가 될 수 있다. 그래서 1의 B2 medium이 전체 시간 단축의 전제다.
## 3. 확인하지 못한 것
- **Gemini 3.x가 `thinking_budget`을 어떻게 처리하는가.** 브리지는 2.x식 `thinking_budget`만 보낸다. 3.x의 `thinking_level`과 실제로 대응하는지, 예산이 상한으로 지켜지는지는 확인하지 못했다(UNVERIFIED).
- V1은 사고 예산 8,192에 출력 상한 32,000인데도 약 3,000자에서 `max_tokens`로 끝났다. 예산이 지켜지지 않았거나, 사고가 본문으로 새어 나온 것으로 보인다. This is an inference without much evidence.
- **추론 수준별 실제 시간·품질 차이.** 이 문서의 기대 효과는 모두 추정이다. 위 비교 실행으로만 확정할 수 있다.
- **GPT-6.1 Sol의 `reasoning_effort` 허용값.** chat.completions에서 low·medium·high 외의 값(minimal 등)을 받는지 확인하지 않았다.
@@ -0,0 +1,36 @@
# Stage 1 - Part 1 캐시 최적화 개정 및 코드 오류 수정 방안
## 1. B1·B2 캐시 최적화 방안
**검증 결과, 직전 방안의 큰 방향은 맞지만 네 가지를 고쳐야 합니다.** ① V1은 본보기가 아닙니다. V1은 `<DYNAMIC_TAIL_*>`가 없어 프롬프트 전체가 캐시되는데, 백엔드가 원문도 그대로 보내 고정부를 두 번 전송합니다. 11-02 V1 30회의 입력은 약 3만 토큰이었고, 적중 14,618토큰과 비적중 14,833~16,682토큰으로 나뉘었습니다. 그래서 B1·B2는 TAIL 태그를 유지해야 합니다. ② 고칠 변수는 22·30곳이 아니라 TAIL 앞 12·17곳입니다. 이 중 3곳씩은 `{{item.*}}` 표기이고, 값이 바뀌는 곳은 B1 9곳, B2 14곳입니다. ③ B1의 `{{item.source_document_ref}}`는 TAIL 앞에만 있어서, 그대로 고정 문구로 바꾸면 값이 사라집니다. TAIL에 추가해야 합니다. ④ COMMON 닫는 태그는 들여써도 경계로 인식됩니다. 지우는 대신 앞줄 끝에 `</OUTPUT_COMPACTNESS></COMMON_CACHE_PREFIX_STAGE_1>`처럼 붙이면 태그 쌍을 유지하면서 경계만 없앨 수 있습니다.
**개정 구조는 호출마다 같은 부분을 모두 앞으로, 바뀌는 값만 맨 끝으로 보내는 형태입니다.** 앞부분 순서는 `COMMON → ROLE_PREFIX → STATIC_BLOCK → CHECKLIST·RUNTIME_FILES·FINAL_REMINDERS → RUNTIME_OUTPUT_OVERRIDE`입니다. 체크리스트 등 고정 문구를 TAIL 앞으로 옮기면 약 2,000자가 더 캐시에 들어갑니다. override는 계속 지시문의 마지막에 두어 우선순위를 유지합니다. 이 앞부분의 `{{item.*}}`는 모두 "`RUNTIME_PARAMETERS`의 `shard_doc_path`"처럼 고정 문구로 바꿉니다. TAIL에는 `<RUNTIME_PARAMETERS>` 블록만 남기고, B1은 값 5개(`assigned_ordinal`·`evidence_index_candidate`·`source_document_ref`·`shard_doc_path`·`b1_output_path`), B2는 값 5개(`assigned_ordinal`·`evidence_index_candidate`·`shard_doc_path`·`b1_output_path`·`b2_output_path`)를 넣습니다. `preflight_files`는 바꾸지 않습니다. 백엔드가 정적 파일인 `client_meeting.md`와 B1의 `evidence_component_union.md`를 TAIL 앞에 넣고, 동적 파일인 shard와 B1 part는 TAIL 뒤 `[Preflight]` 메시지로 보내기 때문입니다.
**예상 효과는 호출당 B1 약 24,500토큰, B2 약 21,100토큰 적중이고, 입력 대비 적중률은 B1 약 96%, B2 약 87%입니다.** 11-02의 호출당 2,353토큰보다 크게 늘어난 수치지만, 문자 수에 V1에서 얻은 약 0.5토큰/자를 곱한 추정치입니다. 동시 12개 호출에서는 캐시가 최대 12개까지 중복 생성될 수 있습니다(V1은 동시 8개에 8회). 적중에는 지장이 없고 저장 비용만 조금 늘므로 예열 task는 넣지 않고, 필요하면 브리지의 캐시 생성에 잠금을 추가합니다. TTL 20분과 `high`는 유지합니다. 적용 전에는 서로 다른 item 두 개로 렌더링해 TAIL 앞 내용이 완전히 같은지 비교하고, 적용 후에는 온라인 로그의 `cached_tokens`와 `user_prefix_len`으로 실제 값을 확인합니다. 이 변경은 지시 내용을 바꾸지 않지만 프롬프트 재배치라서, 이전의 "프롬프트 내용 그대로" 조건은 풀어야 합니다.
## 2. `Task_V1_value_facts_*` 캐시 최적화 방안
프롬프트 끝 `</VALUE_FACTS_EXTRACTION>` 뒤, 줄 맨 앞에 `<DYNAMIC_TAIL_TASK_V1_VALUE_FACTS>` 블록을 추가합니다. 블록 안에는 고정 문구 한 줄만 넣고 닫습니다. 그러면 정적 어휘 파일이 태그 앞에 들어가 캐시 내용은 지금과 같고, 첫 메시지는 tail만 남아 이중 전송이 사라집니다. 메시지 구성도 B1·B2가 이미 쓰는 형태입니다. TTL 20분, 동시 8개, `medium`, `preflight_files`는 그대로 둡니다.
세 작업 중 이것만 입력 토큰 자체가 줄어듭니다. 11-02의 30회 합계는 입력 896,343토큰, 적중 438,540토큰, 적중률 48.9%였습니다. 수정 후에는 회당 입력이 약 43만~44만 토큰 줄고, 적중률은 약 94~96%가 됩니다. 프롬프트 해시 봉인은 YAML과 자산 어디에도 없어 재봉인이 필요 없습니다. 캐시가 8개 중복 생성되는 문제는 YAML로 고칠 수 없고 절감 폭도 작아 예열 task는 넣지 않습니다.
## 3. `Task_A_client_goal` 캐시 최적화 방안
"도구 유지 + `preflight: true`"는 기각합니다. 도구를 노출한 상태에서는 파일이 프롬프트와 위조된 `read_docs` 결과에 이중으로 들어가기 때문입니다. 대신 A0처럼 1회 호출로 바꿉니다. `preflight: true`, `expose_tools: false`, `llm_result_envelope: true`로 설정하고 TAIL 뒤에 override를 붙입니다. `client_goal.json`은 새 capture task(A0c 복제)가 저장하고, 순서는 Task_A → capture → T9로 바꿉니다. `preflight: false`는 옛 96,000바이트 상한 때문이었는데 그 상한은 2026-08-20에 삭제됐으므로, 변경 근거를 YAML 머리말에 적습니다. `llm_token_limit`은 지정하지 않습니다.
이 변경의 주된 이유는 비용보다 안정성입니다. 도구 루프는 응답이 `terminate`로 끝나야 멈추는데, Task_A는 다른 완료 문구를 출력하라고 지시받아 최악의 경우 8회 × 3호출까지 갈 수 있습니다. 입력 비용 절감은 약 30~50%로 봅니다(직전에 언급한 "240k→40k"는 근거가 없어 철회합니다). `cache_control`은 일단 유지합니다. 제거해도 쓰기 1.25배를 피한다는 보장이 없고, `breakpoints: []`는 기본값으로 되돌아가기 때문입니다. 첫 실행의 `cache_write_tokens`를 본 뒤 판단합니다. `client_goal`은 1건뿐이라 빈 응답이 치명적입니다. `max_iterations: 2`와 "JSON 다음 줄에 `terminate`" 지시를 함께 넣어 빈 응답만 1회 재호출하되, 이 조합은 하네스로 먼저 확인합니다.
## 4. `Task_B12_gate_llm_adjudicator` 캐시 최적화 방안
`expose_tools: false`, `max_iterations: 1`, envelope로 바꾸고 capture task가 decisions 파일을 저장합니다. 순서는 B12 → capture → finalizer입니다. 정적 경로인 pack은 preflight로 프롬프트에 들어가므로, 도구로 다시 읽거나 재전송할 일이 없습니다. 정상 입력은 회당 약 11,000토큰으로 추정합니다. `exception_count == 0`이면 override로 `{"no_suspects": true, ...}` JSON을 출력하게 합니다.
**`cache_control`은 지우면 안 됩니다.** 제가 낸 초안의 "1회 호출이라 제거"는 기각합니다. Gemini 브리지는 `cache_control`이 없어도 첫 메시지를 tail로 잘라내고, 앞부분을 복원하는 코드는 캐시 생성 실패 분기에만 있습니다. 그래서 `llm_reasoning`만 남으면 프롬프트 앞부분이 경고 없이 모델에 전달되지 않습니다. `ttl: 5m`으로 유지합니다. 호출 자체는 B2 게이트의 `nexts` 조건 `when: "output.exception_count > 0"`으로 제한합니다. 게이트가 실패하거나 예외가 0건이면 B12가 SKIPPED 되고 capture와 finalizer는 계속 돌며, 판정이 빠진 항목은 `ESCALATE_TO_REVIEW`로 처리됩니다. 11-02처럼 pack 없이 약 32만 토큰을 쓰는 일도 막습니다.
## 5. `stage1_tmp` 오류 해결 및 자동 복구 코드
**해결은 누락된 part를 게이트 전에 자동으로 다시 만드는 복구 경로를 추가하는 것입니다.** 백엔드 재시도는 예외가 날 때만 작동하고, 빈 응답은 LLM task의 예외가 아닙니다. capture가 예외를 내도 capture만 재실행되므로 LLM은 다시 호출되지 않습니다. 그래서 `all Task_B1c_*` 뒤에 코드 task `Task_B1r_repair_planner`를 둡니다. 이 task는 `evidence_shard_plan.json`의 모든 ordinal을 돌며 part가 없거나, JSON 객체가 아니거나, `evidence_index_proposed`가 `E-NNN`과 다른 것만 `dynamic_fanout`으로 냅니다. 뒤이어 `Task_B1r_map_doc_*`(B1과 바이트가 같은 프롬프트, 1회 호출)와 `Task_B1rc_capture_*`가 해당 건만 다시 만듭니다. B2도 같은 3단계를 `all Task_B2c_*`와 B1 복구 뒤에 두고, B1을 복구한 ordinal을 함께 재처리합니다. 고장이 없으면 빈 fan-out이 되어 바로 통과합니다(`agent.py`에서 확인). 복구는 1회로 제한하고, 게이트는 복구 task 뒤에서 기다리도록 바꿉니다. task는 21개에서 27개로 늘어납니다.
**복구 후에도 실패하면 원인을 남기고 하류를 멈춥니다.** 게이트의 `raise` 앞에 `write_file`로 `stage1_tmp/quality_gate/B1_failure.json`을 저장해 `missing_ordinals`와 `parse_failures`를 기록합니다. 이렇게 하면 실패해도 폴더와 원인이 남습니다. 백엔드는 부모가 실패해도 자식을 실행하므로, 차단은 코드로 해야 합니다. B2 게이트는 시작할 때 manifest나 `B1_failure.json`을 확인해 `BLOCKED_UPSTREAM`을 명확히 보고하고, B12는 위의 `nexts` 조건으로 건너뜁니다. T9 handoff도 이 실패 파일을 확인해 `BLOCKED`로 기록하게 합니다. 재실행 때 옛 실패 파일이나 precheck가 남지 않도록 게이트 첫 단계에서 덮어써야 합니다.
@@ -0,0 +1,174 @@
# Stage 1 Part 1 실패분석서 (2026-11-02 실행)
- 대상 실행: workspace `11월_1일_구성`(`3d5eb245…`), 세션 `eb309861-72ad-420b-a154-cd0a5fbd1536`
- 실행 시각: 13:25:17~13:38:53 UTC, 사용자 취소로 종료(`STOPPED`)
- 대상 YAML: `stage_1_part_1_v.8.yml`
- 근거: `agent-backend` 로그, DB `task_runs`·`task_iterations`·`token_usage_logs`, 서버 파일 목록(모두 읽기 전용 조회)
## 1. 결론
실패 두 건은 서로 다른 원인에서 나왔다.
1. **`Task_B12_gate_audit_finalizer` 실패의 근본 원인은 `Task_B1_map_doc_1`이다.** 이 인스턴스가 반복 상한 8회를 다 쓰고도 `evidence_indexed_parts/E-002.json`을 쓰지 않았는데, 백엔드는 이를 성공으로 기록했다. 그 결과 B1 게이트가 멈췄고, 게이트 산출물이 없어 B2 게이트와 B12 finalizer가 차례로 실패했다.
2. **`Task_A_client_goal`은 실패한 것이 아니라 시작조차 못 했다.** 선행 작업 `Task_A0_domain_screener_01`이 13분 36초 동안 끝나지 않았기 때문이다. A0는 호출 한 번에 300~400초가 걸렸고, 첫 시도는 6분 25초 뒤 연결이 끊겨 처음부터 다시 돌았다.
권장 조치는 두 가지다.
- A0의 `llm_reasoning`을 `medium`으로 낮추고, 불필요한 도구 왕복을 없앤다.
- B1·B2를 V1과 같은 "도구 없는 1회 호출 + 코드 저장" 구조로 바꾼다.
YAML과 서버는 이번 분석에서 변경하지 않았다.
## 2. 사건 시간표 (UTC)
| 시각 | 사건 |
|---|---|
| 13:24:43 | `client_meeting.md`, `evidence_all.json` 업로드 |
| 13:25:17 | 실행 시작. A0와 shard planner가 동시에 시작 |
| 13:25:22 | shard planner 성공, B1 30개 fan-out |
| 13:25:26 | V0 성공, V1 30개 fan-out |
| 13:29:04 | `Task_B1_map_doc_1` 종료(8회 반복, 파일 미작성, `READY`) |
| 13:31:43 | A0 1차 시도 실패(`[Errno 104] Connection reset by peer`, 385초 경과) |
| 13:31:48 | A0 2차 시도 시작(처음부터) |
| 13:33:43~55 | B1 게이트 2회 실패(`missing_ordinals: ["002"]`) |
| 13:33:58 | V2 완료(`READY_WITH_REVIEW`, 30문서 104레코드) |
| 13:37:32~43 | B2 게이트 2회 실패 |
| 13:37:43~13:38:06 | B12 LLM 판정기 실행, 입력 팩이 없는데도 `READY` |
| 13:38:06~17 | B12 finalizer 2회 실패 |
| 13:38:29 | A0 2차 시도의 첫 호출이 393초 만에 완료, 출력 200토큰 |
| 13:38:52 | 사용자 취소 |
| 13:43:39 | 취소 뒤에도 A0 호출 완료(309초, 출력 없음), 3회차 시작 |
## 3. B12 finalizer 실패 분석
### 3.1 실패 연쇄
| 순서 | 작업 | 결과 | 직접 원인 |
|---|---|---|---|
| 1 | `Task_B1_map_doc_1` | `READY`(실제로는 미완료) | `E-002.json`을 쓰지 않음 |
| 2 | `Task_B1_quality_gate_evidence_indexed` | `FAILED` | `B1 input parts missing or unparsable`, 최종 파일 미작성 (YAML:4194) |
| 3 | `Task_B2_quality_gate_event_candidates` | `FAILED` | `Empty content: stage1_tmp/quality_gate/finalized_evidence_id_manifest.json` |
| 4 | `Task_B12_gate_llm_adjudicator` | `READY`(무의미한 실행) | `B12_exception_pack.json`이 없음 |
| 5 | `Task_B12_gate_audit_finalizer` | `FAILED` | `Empty content: stage1_tmp/quality_gate/B1_precheck.json` |
3·5번의 `Empty content`는 파일이 비었다는 뜻이 아니다. `read_docs`가 `Document not found`를 돌려준 경우에도 코드가 이렇게 표시한다. 서버 확인 결과 `stage1_tmp/` 폴더 자체가 없다.
### 3.2 `E-002` 누락
- 서버의 `evidence_indexed_parts/`에는 30개 중 29개만 있고 `E-002.json`만 없다.
- `E-002`는 폐쇄 가족관계증명서이며 입력 shard는 정상이다(`evidence_shards/E-002.json`, preflight 3개 파일 로드 성공).
- `Task_B1_map_doc_1`의 DB 기록은 다음과 같다.
| 회차 | 소요(초) | 종료 사유 | 도구 호출 | 응답 글자 수 | 누적 입력 토큰 |
|---|---:|---|---:|---:|---:|
| 1 | 42 | `tool_use` | 2 | 145 | 120,631 |
| 2 | 34 | `tool_use` | 2 | 145 | 133,403 |
| 3 | 23 | `tool_use` | 2 | 1 | 142,896 |
| 4 | 27 | `tool_use` | 2 | 1 | 197,329 |
| 5 | 42 | `tool_use` | 2 | 1 | 280,094 |
| 6 | 28 | `tool_use` | 2 | 1 | 301,891 |
| 7 | 9 | `tool_use` | 2 | 1 | 310,126 |
| 8 | 10 | `tool_use` | 2 | 1 | 327,639 |
8회 모두 `is_complete=false`인데 도구만 호출하다 끝났다. 로그에서 `E-002`를 지정한 `write_file`은 13:31:44의 한 건뿐이고, 그것은 B2 쪽의 `evidence_event_candidate_parts/E-002.json` 쓰기다.
이 시간대에 프롬프트가 허용하지 않은 파일 읽기가 있었다.
- `Default_Agent/domains/E-15/structure_types.json`
- `Default_Agent/stage1_runtime/worker_output_validator.py`
- `Default_Agent/value_facts/v4/golden/차용증_오민한_강용원_01_2023.gold.json`
- `Default_Agent/signals/emitters/emitter_runtime.py`
이 읽기의 시각이 B1_1의 회차와 토큰 급증 구간(특히 4회차, 70,139 → 107,578)에 맞는다. 다만 도구 호출 내용은 DB에 암호화되어 있고 로그에는 작업 이름이 없으므로, 이것이 B1_1의 호출이라는 판단은 시각 대조에 따른 추정이다(확신도 Moderate). 왜 `E-002`에서만 탐색이 이어졌는지는 확인하지 못했다(`UNVERIFIED`).
### 3.3 왜 빨리 잡히지 않았는가
- **백엔드가 미완료를 성공으로 기록했다.** 반복 상한을 소진해도 `Task 'Task_B1_map_doc_1' completed successfully`로 끝난다.
- **실패한 부모 뒤의 자식이 계속 실행되었다.** B1 게이트 실패 뒤 V2와 B2 게이트가 돌았고, B2 게이트 실패 뒤 B12 LLM이 돌았다. 게이트가 "downstream 진행 금지"라고 출력해도 실제로 막지 못한다.
- **B2는 B1 결과 없이 진행했다.** B2_1은 `evidence_indexed_parts/E-002.json`이 없다는 응답을 받고도 사건 후보를 썼다.
- **오류 문구가 근본 원인을 가린다.** B12 finalizer의 메시지만 봐서는 `E-002` 누락을 알 수 없다.
## 4. `Task_A_client_goal` 지연 분석
### 4.1 의존 관계
`Task_A_client_goal`은 `A0_01 → A0_02 → A0_03` 뒤에만 시작한다(YAML:8004~8022). 이번 세션에서 A0_01이 끝나지 않았으므로 A0_02, A0_03, Task_A는 모두 대기 상태로 남았다. 서버에 `routing/` 폴더와 `client_goal.json`이 없는 것도 이 때문이다. D0와 handoff도 A0_02·Task_A를 기다리므로 Part 1 전체가 이 한 작업에 묶였다.
### 4.2 A0 실측
| 시각 | 모델 | 조건 | 소요(초) | 출력 토큰 |
|---|---|---|---:|---:|
| 10-06~10-11 | Flash-Lite | 상담기록 있음 | 3~49 | 0~7,191 |
| 11-02 13:15~13:20 | 3.8 Flash `high` | 상담기록 없음(직전 실패 실행) | 16~147 | 519~647 |
| 11-02 13:31 | 3.8 Flash `high` | 1차 시도 | 385초 뒤 연결 끊김 | 없음 |
| 11-02 13:38 | 3.8 Flash `high` | 2차 시도 1회차 | 401 | 420 |
| 11-02 13:43 | 3.8 Flash `high` | 2차 시도 2회차 | 309 | 0 |
13:38의 호출 하나를 보면 393초가 걸렸지만 출력은 200토큰이고, 결과는 도구 호출 1건이었다.
### 4.3 지연 원인
1. **`high`의 사고 예산이 크다(주 원인 후보).** 브리지는 `high`를 `thinking_budget=32768`, `medium`을 8192로 바꾼다(`llm_bridge/bridge.py`). 예산은 도구 호출만 내는 회차에도 적용된다. 출력은 적은데 시간만 긴 양상과 맞지만, 로그에 사고 토큰이 없어 직접 증명하지는 못했다. This is an inference without much evidence.
2. **A0가 도구를 쓰도록 되어 있어 호출이 여러 번 필요하다.** 프롬프트는 이미 preflight로 받은 파일의 존재를 `list_docs`로 다시 확인하게 한다(YAML:237, 429). 이 단계마다 긴 사고가 반복된다.
3. **요청 시간 제한이 없고 스트리밍도 아니다.** `generate_content`는 비스트리밍이고, 브리지에서 타임아웃 설정을 찾지 못했다. 응답이 올 때까지 무한정 기다리며, 끊기면 그동안의 작업을 잃는다.
4. **연결이 끊기면 처음부터 다시 한다.** 13:31:43에 A0, 13:31:44에 B1_29가 같은 오류로 끊겼다. 재시도로 복구는 되었지만 A0는 6분 25초를 잃었다. 끊김의 원인은 로그만으로 알 수 없다(`UNVERIFIED`).
5. **병렬 부하가 겹쳤을 수 있다.** 같은 시간대에 Gemini 호출이 최대 30건 동시에 돌았다. 호출 지연은 중앙값 9.4초, 상위 10% 118.8초였다. 429 오류는 없었지만 부하 영향을 배제하지는 못한다. A0 단독 실행과 비교해야 1번과 구분된다.
## 5. 해결 방안
### 5.1 다음 실행 전 YAML 수정
| 번호 | 대상 | 수정 | 기대 효과 |
|---|---|---|---|
| F1 | `Task_A0_domain_screener_01` (YAML:114) | `llm_reasoning: medium` | 사고 예산 32,768 → 8,192. `최적LLM후보_stage_1.md`의 A0 권고와도 같다 |
| F2 | A0 프롬프트 (YAML:237, 429) | `list_docs` 확인 단계를 없애고 바로 `write_file` 하게 한다 | 호출 횟수 감소 |
| F3 | A0 | `max_iterations: 3` | 탐색이 길어져도 빨리 끝남 |
| F4 | B1·B2 | V1 구조로 전환: `expose_tools: false`, `max_iterations: 1`, `llm_result_envelope: true`, 저장은 코드 작업 `Task_B1c_*`·`Task_B2c_*`가 담당 | 모델이 파일을 안 쓰거나 다른 파일을 읽는 일이 구조적으로 사라짐 |
| F5 | B1 (YAML:2640) | F4를 미루는 경우에도 `llm_reasoning: medium` 적용 | 호출 지연과 비용 감소 |
**F4를 권하는 이유는 이번 실행의 V1 실측이다.**
| 구분 | 실패·누락 | 인스턴스당 반복 | 입력 토큰 | 추정 비용 |
|---|---|---:|---:|---:|
| V1 | 30건 중 0건 | 전부 1회 | 약 90만 | $0.47 |
| B1 | 30건 중 1건 | 1~8회 | 약 770만 | $5.88 |
| B2 | 30건 중 0건 | 1~3회 | 약 570만 | $4.77 |
B1·B2는 V1보다 프롬프트와 출력이 크므로 같은 수치를 기대할 수는 없다. 다만 도구가 없으면 B1_1 같은 실패는 일어날 수 없다. F4의 배선은 다음과 같다.
- B2는 같은 ordinal의 `B1c`를 기다린다.
- B1 게이트는 `all Task_B1c_*`를 기다린다.
- 저장 코드는 응답이 불완전하면 그 문서를 실패로 남기고, 게이트가 ordinal을 보고한다.
- 동적 preflight가 앞에 있어 캐시가 깨지는 순서도 함께 고친다. 이번 실행의 캐시 적중은 입력의 약 7.6%에 그쳤다.
일정이 급하면 F1~F3, F5만 적용해 재실행할 수 있다. 다만 B1 누락은 원인이 밝혀지지 않았으므로 재발할 수 있다.
### 5.2 백엔드 개선 (별도 승인 필요)
| 번호 | 내용 |
|---|---|
| B-1 | 반복 상한을 소진하고 `is_complete=false`이면 `READY`가 아니라 `FAILED`로 기록 |
| B-2 | 부모가 `FAILED`이면 자식을 실행하지 않고 건너뛰되, `all X_*` 대기가 멈추지 않게 처리 |
| B-3 | Gemini 호출에 요청 타임아웃을 두거나 스트리밍으로 전환 |
| B-4 | 취소 시 진행 중인 LLM 스레드도 종료. 이번에는 취소 5분 뒤에도 A0가 새 회차를 시작했다 |
| B-5 | preflight 대상 파일이 없으면 즉시 실패 처리 |
### 5.3 재실행 절차
1. 취소된 A0 스레드가 끝났는지 확인한다. 13:46:31 UTC 조회 시점에도 3회차 응답이 기록되지 않았다.
2. `evidence_indexed_parts/`와 `evidence_event_candidate_parts/`를 비운다. planner의 stale 검사는 범위 밖 번호(`< 1` 또는 `> n`)만 잡으므로, 같은 번호의 옛 파일은 다음 실행에서 인스턴스가 실패해도 정상처럼 남을 수 있다.
3. F1~F4를 적용한 YAML을 업로드하고, 파싱·`ast` 검사를 통과시킨다.
4. Part 1을 재실행하고 아래를 확인한다.
- A0 1회 호출이 60초 안팎인지. 벗어나면 A0 단독 실행으로 4.3의 1번과 5번을 구분한다.
- `evidence_indexed_parts`에 30개가 모두 있는지.
- `stage1_tmp/quality_gate/B1_precheck.json`, `routing/domain_screening.json`, `client_goal.json`이 생겼는지.
- handoff까지 완료되고 V3가 실행되는지.
## 6. 다음 단계에서 예상되는 장애
Part 2는 현재 상태로는 멈출 가능성이 높다. `pre_loads.tar.gz`(2026-08-23)의 `runtime_manifest.json`은 sha `8964593a…`이고, 로컬 정본은 `ca806ca9…`이다. 465개 항목 중 17개의 해시가 다르다. 새 workspace의 manifest는 파일 시각이 workspace 생성 시각과 같아 pre_loads 본으로 판단되지만, 서버 파일이 암호화되어 있어 내용을 직접 대조하지는 않았다.
Part 1이 대조하는 모듈 5개는 두 manifest의 해시가 같아 이번 실행에는 영향이 없다. Part 2 A0는 manifest sha를 대조하므로(`PART2_RUNTIME_MANIFEST_STALE`), Part 2 실행 전에 로컬 정본 `runtime_manifest.json`을 `Default_Agent/`에 올려야 한다.
## 7. 비용과 검증 범위
- 세션 추정 비용은 약 $11.32다(`token_usage_logs` 기준, 입력 약 1,473만 토큰). 조회 시점까지의 값이며, 진행 중이던 A0 3회차 호출은 포함되지 않는다.
- V 사슬 산출물 `value_facts.json`은 생성되었고 게이트는 `READY_WITH_REVIEW`다. 다만 B1 게이트가 실패한 상태에서 돌았고 handoff도 없어 Stage 2 수용 조건을 충족하지 않는다. 재실행으로 다시 만들어야 한다.
- 위 수정안은 아직 적용하거나 시험하지 않았다. 효과 수치는 이번 실행 관측에 근거한 기대치다.
@@ -0,0 +1,112 @@
# Stage 1 Part 1 결과보고서 (2026-11-03 2차 실행)
- 대상: `1. Stage_1/v.8/stage_1_part_1_v.8.yml`(sha256 `9c425a21…`, task 29). 실행 코드에서 이번 개정분(`PART_PENDING`·`UPSTREAM_NO_OUTPUT`)을 확인했다.
- 실행: workspace `11월_1일_구성`, 세션 `e278fe64`, 2026-11-03 04:45:39~04:58:01 UTC(12분 22초)
- 근거: `agent-backend` 로그(`docker logs`), localdocs MCP `read_docs`로 읽은 작업공간 파일. 모두 읽기 전용으로 확인했다.
## 1. 결론
**백엔드 기준으로는 성공, 업무 기준으로는 실패(BLOCKED)다.**
- 백엔드는 199개 task를 모두 `completed successfully`로 기록했다. 오류 코드, 재시도, 취소는 0건이다.
- 그러나 Part 1의 최종 판정 `quality_gates/stage1_part1_soft_gate_handoff.json`은 `handoff_status: BLOCKED`, `stage2_auto_progression_allowed: false`다. A0 게이트(`SCREENING_DRAFT_UNREADABLE`) 하나 때문이다.
**원인은 A0_01 프롬프트와 배포 자산의 불일치다.**
- A0_01(Gemini 3.8 flash)은 207초 동안 생각한 뒤 9토큰만 답했다. 답은 `FAILED: activation_cue_digest`였다.
- 프롬프트 FAILURE_POLICY(297행)는 "단어 사전 머리말에 `registry_version`이 없으면 중단"하라고 한다. 그런데 배포된 `activation_cue_digest.md`(11-01 13:26 배포)에는 이 머리말이 없다. 도메인 절 26개는 맞다.
- 반대로 A0_02 코드(1132~1150행)는 머리말이 없어도 경고만 남긴다. 정본은 `_registry_index.json`이라는 이유다. 모델은 프롬프트를 글자 그대로 따랐다.
- 같은 사전으로 돈 지난 실행들은 통과했다. 이 판정은 모델이 실행마다 다르게 내리는 지점이다.
**11-03 오후 수정 3건은 의도대로 동작했다.** Task_A 성공, part 표식 잔존 0, capture 오류 구분 정상(§4).
## 2. 실행 구조와 결과 (DAG · IO)
```
IN ─┬─► A0_01 (LLM, Gemini) ─► A0c ──► A0_02 ──────► A0_03 ──────► Task_A (LLM, GPT-6.1 Sol) ─► Ac
│ 207s · 응답 9토큰 │ ✗CAPTURE ✗FAILED ✓READY* ✓486s · 108,987자 ✓CAPTURED
│ ▼ (screening 미작성) (지난 screening 사용) │
│ domain_screening_draft.json = 표식 candidate_profile_vocabulary.md client_goal.json
│ │
└─► Evidence planner ✓ (READY · shard 30 · PART_PENDING 60개 기록) │
├─► B1 ×30 ─► B1c ×30 ─┬─► B2 ×30 ─► B2c ×30 ─┐ │
│ ✓ 30/30 │ ✓ 30/30 │ │
│ ▼ ▼ │
│ B1r (repair 0, 빈 fan-out) B2r (repair 0, 빈 fan-out) │
│ ▼ ▼ │
│ B1 게이트 ✓PASS ─────────────► B2 게이트 ✓PASS · exception 14 │
│ evidence_indexed.json evidence_event_candidates.json │
│ │ ▼ when exception_count>0 │
│ │ B12 (LLM, flash-lite) ✓ ─► B12c ✓ ─► finalizer ✓ │
│ │ ▼ │
│ │ D0 ✓READY_WITH_REVIEW* ◄── (A0_02 대기) │
│ │ domain_activation_manifest.json │
│ │ ▼ │
│ │ handoff writer ◄─────────────────────────────────────┘
│ │ ✗ BLOCKED (A0 게이트) → stage1_part1_soft_gate_handoff.json
└─► V0 ✓ ─► V1 ×30 ✓ ─► V1c ×30 ✓ ─► V2 ✓READY_WITH_REVIEW ─► V3 ✗BLOCKED ─► OUT
value_facts.json (GATE_NOT_CLEARED)
```
`*`는 이번 실행이 아니라 지난 실행(02:40 UTC)의 `routing/domain_screening.json`을 입력으로 쓴 산출물이다.
| 구간 | task 수 | 결과 | 주요 수치 |
|---|---:|---|---|
| A0 사슬 | 4 | **실패**. 03만 READY | 01 응답 39자. 02 `DRAFT_UNREADABLE` |
| Task_A·Ac | 2 | 성공 | `client_goal.json` 123,207자, JSON 정상, 최상위 키 14개 |
| B1 사슬 | 63 | 성공 | final 30, suspect 6, repair 0 |
| B2 사슬 | 63 | 성공 | 후보 131, dedup 0, exception 14, repair 0 |
| B12 사슬 | 3 | 성공 | 판정 14건(SOFT_WARNING_REVIEW 12 · ESCALATE 1 · DISMISS 1). B1 SOFT · B2 HARD_WARNING, hard 0 |
| D0 | 1 | 성공* | 도메인 26, runnable 15, active 13, review 7, unrouted 1 |
| V 사슬 | 63 | V2 성공, V3 BLOCKED | 문서 30(ok 28 · review 2), records 99. V3는 `party_aliases.json`의 `GATE_NOT_CLEARED` 때문에 막혔다 |
| handoff | 1 | **BLOCKED** | hard gate 1(`A0-GATE-SCREENING_DRAFT_UNREADABLE`) |
## 3. 결과물이 YAML 의도대로 생성되었는가
| 결과물 | 생성 | 판정 |
|---|---|---|
| `evidence_shard_plan.json`, `evidence_shards/` 30, `value_facts_input_plan.json`, `value_facts_inputs/` 30 | ✓ | 의도대로 |
| `evidence_indexed_parts/` 30 → `evidence_indexed.json` | ✓ | 의도대로. 60개 part 모두 JSON이고 `PART_PENDING`은 0개 남았다 |
| `evidence_event_candidate_parts/` 30 → `evidence_event_candidates.json` | ✓ | 의도대로 |
| `quality_gates/B1_*`·`B2_*`·`value_facts_gate.json`, `stage1_tmp/quality_gate/` 9개 | ✓ | 의도대로. 복구 계획은 DONE·빈 fan-out이다 |
| `value_facts.json`·`value_facts_parts/` 30 | ✓ | 의도대로 |
| `routing/domain_screening_draft.json` | 표식 | **의도와 다르다.** 96바이트 `CAPTURE_FAILED MODEL_NOT_JSON_OBJECT: FAILED: activation_cue_digest`. 실패 시 표식을 쓰는 동작 자체는 설계대로다 |
| `routing/domain_screening.json` | 미갱신 | **의도와 다르다.** 02:40의 지난 파일이 남았다 |
| `candidate_profile_vocabulary.md`, `client_goal.json`, `domain_activation_manifest.json` | ✓* | 형식은 정상이다. 다만 지난 screening 위에서 만들어졌다. 입력(`client_meeting.md`·`evidence_all.json` 11-02, 사전 11-01)이 같아 내용은 쓸 만할 수 있다. 그러나 이번 실행이 봉인한 결과는 아니다 |
| `party_aliases.json`, `value_facts_party_links.json` | 오류본 | 게이트 미통과로 빈 값과 오류 코드가 기록됐다. 설계대로 막힌 것이다 |
| `stage1_part1_soft_gate_handoff.json` | BLOCKED | 게이트가 의도대로 오류를 잡았다 |
## 4. 11-03 오후 수정분 검증
| 수정 | 실측 | 판정 |
|---|---|---|
| ① Task_A `llm_verbosity` 삭제 | chat.completions 1회 호출, 486초. prompt 35,999 · completion 44,192 · cache_write 35,996. 비용 $0.532. `text` 인자 오류 0건 | 해결 |
| ② capture `UPSTREAM_NO_OUTPUT` | upstream 실패가 없어 발동하지 않았다. A0c는 응답이 있었으므로 `MODEL_NOT_JSON_OBJECT`로 올바르게 구분했다 | 정상. 발동 경로는 아직 실측되지 않았다 |
| ③ planner `PART_PENDING` | 표식 60개를 기록한 뒤 capture가 모두 덮었다. 남은 표식 0 | 해결 |
| §3.5 미검증 경로 | B2r 빈 fan-out, B2 게이트 `exception_count`, B12 조건부 실행(1회 호출), B12c→finalizer→D0, handoff BLOCKED 기록, V3 | 모두 실행으로 확인 |
## 5. 비용·캐시
| task | 호출 | 입력 | 적중률 | 출력 | 평균 / 최대 시간 |
|---|---:|---:|---:|---:|---|
| B1 | 30 | 692,498 | 94.4% | 60,190 | 106s / 166s |
| B2 | 30 | 646,860 | 84.7% | 127,207 | 163s / 358s |
| V1 | 30 | 461,973 | 94.9% | 25,408 | 64s / 228s |
| A0_01 | 1 | 24,906 | 8.2% | 9 | 207s |
| Task_A | 1 | 35,999 | 0%(첫 호출, write 35,996) | 44,192 | 486s |
| B12 | 1 | 약 1만 | 0% | — | 15s |
- **전체:** 93회 호출, `[USAGE]` 비용 합계 $1.60. 그중 Task_A가 $0.53, B2가 약 $0.59다.
- **B12 캐시:** prefix가 866토큰으로 Gemini 최소 1,024토큰보다 작아 캐시 생성이 실패했다(400). 비캐시 호출로 정상 진행됐다. 해가 없으므로 조치가 필요 없다.
- **임계 경로:** A 사슬(A0_01 207초 + Task_A 486초)이 B 사슬(B2 끝 04:57:19)과 거의 같은 시각에 끝났다. 실행 시간은 두 LLM 호출이 정한다.
- **집계 방법:** task별 수치는 동시에 실행된 `[BRIDGE]` 줄을 완료 순서대로 짝지은 근사치다. 다만 B1과 V1은 오전 실행과 입력량이 같다.
## 6. 조치 권고
1. **[치명] A0_01 FAILURE_POLICY(297행) 수정.** `registry_version` 머리말 요구를 지우고 "도메인 절 26개" 검사만 남긴다. A0_02 코드는 이미 머리말이 없어도 경고만 남기며, 정본은 `_registry_index.json`이다. 사전에 머리말을 추가해 재봉인하는 방안은 자산 sha 연쇄 갱신이 필요해 권하지 않는다.
2. **[주요] A0_02 실패 시 지난 screening을 무효화한다.** `FAILED`이면 `routing/domain_screening.json`에 비JSON 표식을 쓰게 한다. 그러면 A0_03·Task_A·D0가 지난 파일로 진행하지 않는다. 이번에는 handoff 게이트가 막았지만, 중간 산출물 3개가 지난 입력으로 생성됐다. ③ `PART_PENDING`과 같은 방식이다.
3. 위 두 가지를 반영한 뒤 Part 1을 재실행해 handoff `READY` 계열을 확인한다. 그다음 Part 2를 실행한다. Part 2 전에 runtime_manifest 정본 업로드가 필요하다.
## 7. 확인하지 못한 것
- A0_01이 지난 실행들에서는 같은 규칙을 왜 통과했는가. 지난 응답 원문이 로그에 남아 있지 않다(컨테이너 04:43 재시작). This is an inference without much evidence: 모델의 규칙 적용이 실행마다 달라지는 것으로 추정한다.
- Task_A 출력 123,207자가 의도한 분량인가. 실제 verbosity 기본값은 UNVERIFIED이며, 지난 정상 실행의 `client_goal.json` 크기와 비교하지 않았다.
- `client_goal.json`·D0 manifest 내용의 법률적 정확성. 이번 보고서는 형식과 흐름만 검증했다.
@@ -0,0 +1,103 @@
# Stage 1 Part 1 결과보고서 v2 (2026-11-03 3차 실행)
- 대상: `1. Stage_1/v.8/stage_1_part_1_v.8.yml`(sha256 `41663b8f…`, task 29, 4pm 추가개정 반영본)
- 실행 코드에서 이번 개정분을 확인했다: `*_PENDING` 표식, A0_03 `upstream_screening`.
- 실행: workspace `11월_1일_구성`, 세션 `2ef6f8fc`, 2026-11-03 08:05:12 ~ 08:18:01 UTC
- 업로드는 08:04:31이다.
- 그 앞 07:55 세션 `71795340`은 옛 YAML(V 사슬 없음)로 돈 별개 실행이라 제외했다.
- 근거
- `agent-backend` 로그: `docker logs`, 28,148행. `[USAGE]`·`[PROCESS_MESSAGES]`·코드 task stdout을 썼다.
- localdocs `read_docs`로 읽은 작업공간 파일
- 모두 읽기 전용으로 확인했다.
## 1. 최종 성공 여부 — **성공**
| 판정 기준 | 결과 |
|---|---|
| 백엔드 | task 199개 전부 `task_complete`, `execution_complete`. 코드 task 106건 모두 `error_code=0`, 재시도·실패 0 |
| Part 1 판정 (`quality_gates/stage1_part1_soft_gate_handoff.json`) | **`READY_WITH_REVIEW`**, `stage2_auto_progression_allowed: true`, hard gate 0, digest_guard 7키 유효 |
| 검토 항목 | 26건(D0 활성화 검토 17 포함). 최종 작성 차단 항목 1건 |
| 지난 실행 파일 차단(4pm 개정) | 표식 4종(`HANDOFF/SCREENING/VOCABULARY/MANIFEST_PENDING`)이 모두 정본으로 덮였다. 잔존 0 |
`READY_WITH_REVIEW`는 Stage 2로 넘어가도 되지만 변호사 검토 항목이 남아 있다는 뜻이다. 실패가 아니다.
**4pm 개정의 온라인 확인 항목(전략서 M7-3)도 해결됐다.**
- (a) A0_03에 렌더링된 `{{prev}}`는 `{"Task_A0_domain_screener_02": {…stdout…, "json_output": {…}}}` 형태였다. 코드가 `written: true`를 정상으로 읽었다.
- (b) A0_02가 쓴 `screening_sha256`과 A0_03이 읽은 값이 `e75d3f33…`로 같았다. `SCREENING_SHA_UNCONFIRMED` 경고는 없었다. 따라서 이 검사를 경고에서 `fail`로 올려도 된다.
## 2. 총 런타임 — **12분 49.8초** (769.8초)
- `session_started` 08:05:12.006 → `execution_complete` 08:18:01.846
- 코드 task 106건은 건당 약 3.1~3.9초, 합계 약 6분이다. 대부분 병렬로 돌아 실제 경과 시간 기여는 작다.
## 3. LLM API 비용 — **$1.61** (93회 호출)
| task | 모델 | 호출 | 입력 | 캐시 적중 | 적중률 | 출력(추론 포함) | 캐시 쓰기 | 비용 |
|---|---|---:|---:|---:|---:|---:|---:|---:|
| B1 | gemini-3.8-flash | 30 | 692,498 | 653,850 | 94.4% | 61,987 | — | $0.311 |
| B2 | gemini-3.8-flash | 30 | 648,647 | 548,160 | 84.5% | 128,600 | — | $0.599 |
| V1 | gemini-3.8-flash | 30 | 461,973 | 438,540 | 94.9% | 25,046 | — | $0.144 |
| A0_01 | gemini-3.8-flash | 1 | 24,922 | 2,049 | 8.2% | 7,437 | — | $0.045 |
| B12 | gemini-3.5-flash-lite | 1 | 11,013 | 0 | 0% | 3,226 | — | $0.011 |
| Task_A | gpt-6.1-sol | 1 | 36,937 | 0 | 0% | 40,677 | 36,934 | $0.499 |
| **합계** | | **93** | **1,875,990** | **1,642,599** | **87.6%** | **266,973** | **36,934** | **$1.609** |
- **토큰 총량:** 입력 187.6만 + 출력 26.7만 = **214.3만**. 입력 중 164.3만(87.6%)이 캐시 적중이다.
- 적중분은 입력 합계에서 빠지지 않고 할인 단가만 적용된다.
- **모델별 비용:** gemini-3.8-flash $1.099(91회), gpt-6.1-sol $0.499(1회), gemini-3.5-flash-lite $0.011(1회).
- **비용 산출 근거:** 백엔드 `[USAGE] Saved` 기록의 합이다. 위 값은 백엔드 단가표 기준이며, 공급자 청구서와는 대조하지 않았다.
- **집계 방법:** task별 값은 동시에 실행된 호출을 완료 순서대로 짝지은 값이다. 모델별 합계는 정확하다.
- **11-03 2차 실행($1.60)과 거의 같다.** B1과 V1은 입력량까지 같다.
- **캐시 생성:** 44회. 만료 캐시 재생성 11회는 직전 실행 캐시가 만료된 뒤의 정상 재시도다. B12 prefix는 1,024토큰 미만이라 캐시를 만들지 못했고(1회 실패), 영향은 없다.
## 4. 세부 작업 결과물의 형식
| 구간 | 결과물 | 판정 |
|---|---|---|
| A0 사슬 | `domain_screening_draft.json`(A0c CAPTURED, 16,724자) → `domain_screening.json`(READY_WITH_REVIEW, 후보 15, 검토 5) → `candidate_profile_vocabulary.md`(READY, 절 15) | **정상.** A0_02 경고는 사전 머리말 부재 `DIGEST_HEADER_ABSENT`뿐이고, 의도된 경고다. vocabulary 머리말의 sha가 screening과 일치한다 |
| Task_A·Ac | `client_goal.json` 116,582자, 정상 JSON, 최상위 키 14개. parties: 원고 2·피고 7·제3자 13 | **정상** |
| B1 사슬 | `evidence_indexed_parts/` 30 → `evidence_indexed.json`. 게이트 PASS, final 30, suspect 6, 복구 0 | **정상** |
| B2 사슬 | `evidence_event_candidate_parts/` 30 → `evidence_event_candidates.json`. 게이트 PASS, 후보 126, exception 14, 복구 0 | **정상** |
| B12 사슬 | 판정 14건(SOFT_WARNING_REVIEW 6 · DISMISS 5 · HARD_WARNING_REVIEW 2 · ESCALATE 1). finalizer: B1 SOFT · B2 HARD_WARNING, hard 0, review 9 | **정상.** 조건부 실행(exception > 0)이 의도대로 돌았다 |
| D0 | `domain_activation_manifest.json` READY_WITH_REVIEW. 도메인 26, active 10, supporting 1, 검토 17, unrouted 1, 자기검증 PASS | **정상** |
| handoff·alias | 판정 READY_WITH_REVIEW, `party_aliases.json`(canonical 22, alias 1, 후보 3, 승계 2, error 없음) | **정상** |
| V 사슬 | `value_facts.json` records 90, gate READY_WITH_REVIEW(문서 30: ok 26 · review 3 · failed 1). V3 links 76(resolved 67) | **부분 미흡**(아래) |
| 형식 공통 | 지정 경로의 JSON 산출물과 part 60개가 모두 파싱된다. 표식 잔존 0 | 정상 |
**V1 미흡 4건**
- E-007·E-011·E-013은 `finish_reason: max_tokens`로 잘렸다.
- E-007과 E-011은 응답 본문에 모델의 영어 사고 과정("Wait! …")이 그대로 들어가, JSON 없이 끝났다. E-011은 `MODEL_PARSE_FAILED`, E-007은 REVIEW다.
- E-013은 ```` ```json ```` 코드펜스로 시작한 뒤 중간에 잘려 REVIEW다.
- E-024는 `stop`으로 끝났지만 배열·객체가 닫히지 않아 REVIEW다.
- 게이트가 네 건을 모두 걸러 `value_facts.json`에는 들어가지 않았다. 설계대로 처리됐다.
- 다만 금액 기록이 빠진 문서가 4개다. `llm_token_limit: 32000`인데도 약 3,000자에서 `max_tokens`가 난 것은, 추론 토큰이 출력 한도를 먼저 쓴 것으로 보인다. This is an inference without much evidence.
## 5. 런타임이 12분 50초인 이유
**결론: 실행 시간은 순차로 이어진 LLM 호출 두 개가 정한다. A0_01(276초)과 Task_A(472초)이며, 둘이 합해 748초로 전체의 97%다.**
```
08:05:12 ─ A0_01 (Gemini, 276s) ─ 08:09:48 ─ A0c·A0_02·A0_03 (10s) ─ 08:09:58 ─ Task_A (GPT-6.1 Sol, 472s) ─ 08:17:52 ─ Ac·T9·V3 (9s) ─ 08:18:01
08:05:12 ─ planner ─ B1×30 ─ B1c ─ B2×30 (스트리밍) ─ 08:15:18 ─ B2r·게이트·B12·finalizer·D0 ─ 08:15:50 ─ (T9 대기 2분 2초)
08:05:16 ─ V0 ─ V1×30 ─ V1c ─ 08:11:11 ─ V2 08:11:14 ─ (V3 대기 6분 47초)
```
| 원인 | 근거 |
|---|---|
| **① A 사슬이 직렬이다** | Task_A는 A0_03의 screening과 vocabulary를 preflight로 받으므로 A0이 끝나야 시작한다. 최종 판정 task(T9)는 Ac와 D0를 모두 기다린다. B 사슬은 08:15:50에 끝났지만 T9는 Ac(08:17:55)를 2분 넘게 기다렸다 |
| **② Task_A는 출력이 많아 오래 걸린다** | 입력 36,937에 출력(추론 포함) 40,677토큰을 1회 호출로 냈다. 결과 JSON이 116,582자다. 초당 약 86토큰이므로 생성량이 시간을 정한다. `llm_reasoning: high`이고, verbosity는 YAML로 낮출 수 없다(SDK 기본 medium) |
| **③ A0_01은 출력보다 사고 시간이 길다** | 입력 2.5만, 출력 7,437토큰에 276초가 걸렸다(초당 약 27토큰). `llm_reasoning: medium`이다. 11-03 2차 실행에서도 9토큰을 내는 데 207초가 걸려, 사고 시간이 대부분이다 |
| **④ B 사슬은 임계 경로가 아니다** | B1 평균 108초·최대 179초, B2 평균 166초·최대 323초. 동시 실행 12개 제한과 B1c→B2의 ordinal 스트리밍 때문에 10분 38초가 걸렸지만, A 사슬보다 약 2분 일찍 끝났다 |
| 코드 task | 건당 3~4초. 임계 경로에는 A0c·A0_02·A0_03·Ac·T9·V3 6개, 약 20초뿐이다 |
**단축 방안(참고, 미적용)**
- Task_A가 가장 큰 몫이다. 출력량(client_goal 11.7만 자)을 줄이거나 `llm_reasoning`을 medium으로 낮추는 방안이 있다. 다만 출력 품질에 영향이 있으므로 품질 비교가 먼저다.
- A0_01은 `llm_reasoning` low를 시험할 수 있다.
- 두 호출이 직렬인 것은 데이터 의존(screening → Task_A) 때문이라 구조로는 줄일 수 없다.
- 임계 경로가 A 사슬이므로, B·V 사슬을 빠르게 해도 전체 시간은 줄지 않는다.
## 6. 확인하지 못한 것
- 공급자 청구 기준 실비용. `[USAGE]`는 백엔드 단가표 기준이다.
- `client_goal.json`·D0 manifest·value_facts의 법률적 정확성. 이번 보고서는 형식과 흐름만 검증했다.
- V1 `max_tokens` 조기 종료의 원인(추론 토큰이 한도를 쓴 것인지). Gemini 응답의 `thoughts_token_count`가 로그에 없다.
@@ -0,0 +1,111 @@
# Stage 1 Part 1 실패분석서 (2026-11-03 실행)
- 대상: `1. Stage_1/v.8/stage_1_part_1_v.8.yml`(sha256 `adf666b1…`, task 29)
- 실행: workspace `11월_1일_구성`, 세션 `0207ad0e`, 2026-11-03 02:35:30~02:44:11 UTC
- 근거: 배포 백엔드 `agent-backend` 로그(`docker logs`), 배포본 `llm_bridge/bridge.py`·`src/agent.py`, localdocs 작업공간 파일 목록. 모두 읽기 전용으로 확인했다.
## 1. 결론
**`Task_Ac_client_goal_capture`의 오류는 결과일 뿐이다. 원인은 upstream인 `Task_A_client_goal`의 OpenAI 호출 실패다.** 백엔드 브리지는 chat.completions 호출에도 `llm_verbosity`를 Responses API 전용 인자 `text={"verbosity": …}`로 넣는다. openai SDK 3.40은 이 인자를 거부해, Task_A는 첫 호출 전에 2회(재시도 포함) 모두 실패했다. 실패한 task는 `{{prev}}` 렌더링에 들어가지 않으므로, `Task_Ac`의 코드에는 `{{prev}}` 문자열이 그대로 남았다. 이를 JSON으로 읽다가 `Expecting property name enclosed in double quotes: line 1 column 2`가 났다. capture는 설계대로 `client_goal.json`에 `CAPTURE_FAILED` 표식을 썼다.
실행은 02:44:10에 사용자 화면에서 취소됐다(`POST …/cancel/0207ad0e…`, `execution_stopped`). 그래서 B2 8건, B2 복구, B2 게이트, B12, finalizer, D0, T9, V3는 실행되지 않았다. 11-03 개정의 핵심인 캐시 개선은 실측으로 확인됐다. Gemini 91회 호출의 입력 적중률은 89.8%로, 11-02의 7.6%보다 크게 올랐다.
## 2. 실행 경과
| 구간 | 결과 |
|---|---|
| A0_01 → A0c → A0_02 → A0_03 | 성공. A0_01은 1회 호출로 끝났다(terminate 동작). 초안 14,569자 저장, `domain_screening.json` `READY_WITH_REVIEW` |
| Evidence planner → B1 30 → B1c 30 | 성공. part 30개 모두 정상 |
| B1r 복구 planner | `REPAIR_PLANNED`, `repair_count: 0`. 빈 fan-out으로 대기가 바로 풀렸다 |
| B1 게이트 | `B1_DETERMINISTIC_GATE_DONE`, severity PASS, final 30, suspect 6. `stage1_tmp/quality_gate/`(`B1_failure.json`·`B1_precheck.json`·`B1_repair_plan.json`·manifest)가 생성됐다 |
| V0 → V1 30 → V1c 30 → V2 | 성공. `READY_WITH_REVIEW`(문서 30, ok 27, review 3, records 95) |
| B2 30 | 22건 완료. 8건(12, 22, 23, 25~29)은 LLM 응답 뒤 실행기 처리 전에 취소됐다 |
| Task_A | **실패**(§3.1) |
| Task_Ac | `CAPTURE_FAILED PREV_PARSE_FAILED`(§3.2) |
| 이후 단계 | 취소로 미실행 |
## 3. 문제점
### 3.1 [치명] Task_A가 OpenAI 호출 전에 실패한다
- **증상:** `LLM API 오류: Completions.create() got an unexpected keyword argument 'text'`가 2회 났다(재시도 분류 other, 2/2). 프롬프트 조립(44,883토큰, 정적 입력 4개 inline)은 정상이었다.
- **원인:**
- `bridge.py` `_apply_verbosity`(232~243행)는 provider가 openai이면 endpoint와 관계없이 `kwargs["text"] = {"verbosity": …}`를 넣는다. 주석은 completions에도 `text`를 쓴다고 적었지만 SDK는 받지 않는다.
- 이 함수는 chat.completions 경로(1380·1469·1558·1586행)에서도 호출된다.
- Task_A는 `llm_endpoint`가 없어 chat.completions를 쓰고, `llm_verbosity: medium`이 있다.
- **영향 범위:**
- 같은 조합의 다른 task도 같은 방식으로 실패한다. 현행 YAML 중 openai + completions + verbosity는 Part 1 `Task_A_client_goal`(medium)과 Part 2 `Task_C_B_domain_worker_*`(low)다.
- S2_20의 OpenAI task 4종은 `llm_endpoint: responses`라 해당하지 않는다.
- 브리지 파일은 2026-10-28에 배포됐다. 그 뒤 위 두 task가 온라인에서 돈 기록은 없다.
- **해결:**
- (Part 1 권장, YAML) Task_A에서 `llm_verbosity`를 지운다. GPT-5 계열의 기본 verbosity는 medium이라 출력 설정은 사실상 그대로다. Task_A는 도구 없는 1회 호출이므로 다른 Responses 전용 기능이 필요 없다.
- (Part 1 대안, YAML) `llm_endpoint: responses`로 바꾼다. SKILL §6.5.2는 GPT-5.6+ 캐시에 responses를 권하지만, Stage 1의 도구 없는 preflight 경로에서는 아직 실행된 적이 없다. 이번 수정에는 권하지 않는다.
- (Part 2) 같은 날 다른 세션이 작성한 `1. Stage_1/v.8/캐시최적화_part_2_앙상블_Fable.md`가 이 원인을 이미 다뤘다. 그 문서는 `llm_endpoint: responses`를 실행 전제로 정했다. Sol 도구 호출도 Responses 전용이기 때문이다. Part 2는 그 문서를 따른다.
- (근본, 백엔드) `_apply_verbosity`가 chat.completions 경로에서는 `text`를 넣지 않아야 한다. 해당 SDK가 받는 인자로 바꾸거나 생략한다. SDK가 chat.completions에서 어떤 인자를 받는지는 확인하지 못했다.
### 3.2 [주요] upstream 실패가 capture에서 원인이 보이지 않는 메시지로 드러난다
- **증상:** `CAPTURE_FAILED PREV_PARSE_FAILED: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)`.
- **원인:** 백엔드는 의존 task가 실패하면 그 결과를 prev에 넣지 않고, prev가 비면 task를 재생성하지 않는다(`agent.py` 2535행대). 그래서 `r"""{{prev}}"""`가 그대로 남고, `{{`의 두 번째 `{`에서 JSON 파싱이 실패한다.
- **판정:** 동작 자체는 설계대로다. 표식이 지난 실행의 `client_goal.json`을 덮었고, T9의 A 게이트가 이 표식을 보고 BLOCKED를 기록하게 되어 있다(이번에는 취소로 T9 미실행). 다만 메시지만으로는 upstream 실패를 알기 어렵다.
- **해결:** capture 7종(A0c·Ac·B1c·B2c·B1rc·B2rc·B12c 공통 `extract`)에서 prev 문자열이 `{{prev}}` 그대로이면 `UPSTREAM_NO_OUTPUT`으로 표시한다. 문자열 비교 한 줄이면 되고, 표식 동작은 바꾸지 않는다.
### 3.3 [주요] 취소된 실행은 지난 실행의 B2 part를 남긴다
- **증상:** 작업공간 `evidence_event_candidate_parts/`에 파일 30개가 있다. 이번 실행에서 capture까지 끝난 것은 22개다. 나머지 8개(E-013, E-023, E-024, E-026~E-030)는 수정 시각이 11-02 13:33~13:37 UTC인 지난 실행의 파일이다.
- **영향:** 다음 실행이 끝까지 돌면 capture가 모두 덮으므로 문제가 없다. 그러나 이번처럼 중간에 취소되거나 capture가 시작되지 않으면, 복구 planner와 게이트는 형식이 맞는 지난 part를 정상으로 본다. part에 실행 식별값이 없어 구분할 수 없다.
- **해결:**
- (당장) 재실행 전에 `evidence_indexed_parts/`와 `evidence_event_candidate_parts/`를 비운다.
- (YAML) `Task_Evidence_shard_planner`가 시작할 때 계획한 ordinal의 B1·B2 part 경로에 비JSON 표식을 쓴다. 그러면 지난 part가 남지 않고, 복구 planner가 표식을 `NOT_JSON`으로 잡는다. 표식은 복구 기준과 그대로 맞는다.
### 3.4 [경미] A0_01의 캐시 적중이 낮다
- **수치:** 1회 호출, 입력 24,906, 적중 2,049(8.2%), 279초.
- **원인:** A0_01 프롬프트는 줄 시작 `</COMMON_CACHE_PREFIX_STAGE_1>`가 남아 공통부만 캐시된다.
- **판정:** 실행당 1회 호출이라 같은 prefix를 다시 읽는 일이 없다. B1·B2처럼 고쳐도 절감은 없으므로 고치지 않는다.
### 3.5 [확인 필요] 이번 실행에서 검증되지 않은 경로
취소로 다음 경로는 실행되지 않았다. 다음 실행에서 로그로 확인한다.
- B2r 복구 planner의 빈 fan-out과 `B2_repair_plan.json` DONE
- B2 게이트의 CLEARED와 `exception_count` 출력
- B12의 조건부 전이(SKIPPED 또는 1회 호출)
- B12c → finalizer → D0
- T9가 깨진 `client_goal.json`을 보고 BLOCKED를 기록하는가(이번 실행의 정상 기대 결과)
- V3
## 4. 캐시·비용 실측 (11-03 개정 효과)
| task | 호출 | 입력 | 적중 | 적중률 | 출력 | 평균/최대 시간 |
|---|---:|---:|---:|---:|---:|---|
| B1 | 30 | 692,498 | 653,850 | 94.4% | 64,017 | 115s / 204s |
| B2 | 30 | 650,794 | 548,160 | 84.2% | 131,656 | 164s / 284s |
| V1 | 30 | 461,973 | 438,540 | 94.9% | 26,642 | 76s / 241s |
| A0_01 | 1 | 24,906 | 2,049 | 8.2% | 6,374 | 279s |
- **전체:** 91회, 입력 1,830,171, 적중 89.8%. `[USAGE]` 기록 비용 합계는 $1.12이고, Task_A는 호출 전에 실패해 비용이 없다.
- **11-02 대비:**
- B1은 약 770만 토큰·$5.88에서 69만 토큰으로 줄었다.
- B2는 약 570만 토큰·$4.77에서 65만 토큰으로 줄었다.
- V1은 호출당 입력이 약 3만에서 약 1.5만으로 줄었다. 이중 전송이 사라진 결과이며, 고정부 적중량은 14,618로 그대로다.
- 비용 비교는 B2 8건의 처리 결과가 버려진 상태라 대략치다.
- **방안의 추정과 비교:** 방안은 B1 약 96%, B2 약 87%, V1 94~96%로 추정했다. 실측은 B1 94.4%, B2 84.2%, V1 94.9%였다.
- **캐시 생성:**
- B1 prefix 50,233자 12회, V1 27,927자 8회, B2 43,920자 2회, A0 3,385자 1회.
- 생성 실패와 만료는 0건이다.
- B1·V1은 동시 실행 수만큼 중복 생성됐다. 브리지가 잠금 밖에서 생성하기 때문이며, 적중에는 영향이 없다.
## 5. 수정 순서
1. Part 1 `Task_A_client_goal`에서 `llm_verbosity`를 지운다(§3.1). Part 2 `Task_C_B_domain_worker_*`는 `캐시최적화_part_2_앙상블_Fable.md`의 ① `llm_endpoint: responses`를 Part 2 실행 전에 적용한다.
2. capture 공통 `extract`에 `UPSTREAM_NO_OUTPUT` 구분을 넣는다(§3.2).
3. `Task_Evidence_shard_planner`에 part 표식 쓰기를 넣는다(§3.3). 넣기 전에는 재실행 전에 parts 두 폴더를 비운다.
4. Part 1을 다시 실행해 §3.5 경로를 끝까지 확인한다. 실행 중 취소하지 않는다.
5. 백엔드 `_apply_verbosity`의 chat.completions 경로 수정을 백엔드 담당에 요청한다(§3.1 근본 해결).
## 6. 확인하지 못한 것
- 백엔드가 조립한 실제 OpenAI 요청 본문(로그에는 예외 메시지만 있다)과, openai SDK 3.40의 chat.completions가 받는 verbosity 인자
- `llm_verbosity`를 지운 뒤 Task_A의 실제 출력 길이와 `cache_write_tokens`
- 취소 뒤에도 B2 LLM 호출 8건이 끝까지 진행되어 비용이 발생한 것(로그 `[USAGE] Saved`)이 백엔드의 의도된 동작인지 여부
@@ -0,0 +1,299 @@
# Stage 1 Part 1 추가 개정 전략서 (A0 사슬 · 지난 실행 파일 차단)
- **적용 대상:** `1. Stage_1/v.8/stage_1_part_1_v.8.yml`(sha256 `9c425a21…`, 11,413행, task 29). 행 번호는 모두 이 파일 기준이다.
- **근거 문서:**
- `Testrun/Nov_03/결과보고서_part_1.md`: 세션 `e278fe64` 분석
- `Testrun/Nov_03/추가수정_for_결과보고서_part_1.md` §2: 재작성 권고, 독립검증 1회
- 그 뒤 사용자 질의응답 4건에서 정한 추가 항목. 아래 §0.2에 적는다.
- **백엔드 근거:** 배포본 `/app/src/agent.py`를 읽기 전용으로 확인했다.
- 2525~2556행: 의존 task가 끝난 뒤 prev로 다시 렌더링하는 규칙
- 646행~: `_render_template`의 `| json`·`| py`·`| raw` 수식어
- 854행~: `_build_prev_value`
- **지침:** YAML은 `2. Stage_2/SKILL.md`를, Python은 `2. Stage_2/test_code_executor.ipynb`를 따른다. 코드 task는 기존 보일러플레이트(`_init`·`_call`·`read_raw`·`write_doc`)를 그대로 쓴다.
## 0. 이 문서가 합친 것
### 0.1 `추가수정_for_결과보고서_part_1.md` §2 (1~6번)
| 원 항목 | 이 문서 |
|---|---|
| 1. A0_01 프롬프트: 구조 검사를 코드로 이관 | M1 |
| 2. A0_02: 시작할 때 screening 무효화 | M3 |
| 3. A0_03: vocabulary 무효화와 A0_02 연동 검사 | M4. (A)-3의 `status == "FAILED"` 조건은 의도적으로 뺐다. 근거는 M4(b)-3 |
| 4. D0: 시작할 때 manifest 무효화 | M5 |
| 5. handoff writer: 산출물 3종을 게이트로 검사 | M6 |
| 6. 오프라인 하네스 2경우 → 온라인 | M7(시나리오 5개로 확장) |
### 0.2 추가 항목 (질의응답 4건에서 확정)
- **추가 1:** 실행 초반에 판정 파일(`quality_gates/stage1_part1_soft_gate_handoff.json`)을 비JSON 표식으로 미리 덮는다. 판정이 기록되지 않는 경우(Task_A 건너뜀, 중간 취소, 대기 멈춤)에도 지난 실행의 READY 판정이 남지 않게 하기 위해서다. → **M2**
- **추가 2:** Task_A 2014행의 vocabulary 도메인 절 수 검사(LLM이 개수를 셈)를 A0_03 코드로 옮기고, 2014행은 존재·표식 검사로 줄인다. → **M4(c)·(d) + M6 `VOCABULARY_STALE`** (개수 자체는 이미 코드가 보장한다)
- **추가 3:** "A0_01 재시도" 보류 항목은 따로 조치하지 않는다. M1의 근거로 흡수한다.
- A0_01은 prev가 없어 `max_iterations`가 적용되지 않는다(로그 "1/8").
- `FAILED` 응답은 백엔드가 성공으로 처리하므로 재시도가 없다.
- A0c에서 raise해도 백엔드가 다시 실행하는 것은 A0c다.
- YAML로 재시도를 살릴 수단이 없으므로, 헛 FAILED가 나올 조건을 없애는 것이 유일한 대책이다. → **M1**
- **추가 4:** M1~M6은 지난 실행 파일이 흘러가는 것을 막을 뿐, 쓸모없는 Task_A 호출(약 $0.53·486초)은 막지 못한다. 입력 약 3만 6천 토큰은 매번 과금된다. 호출을 없애는 `when` 건너뛰기는 M2를 전제로 probe로 확인한 뒤에만 도입한다. → **§4 단계 2**
## 1. 해결할 문제
| # | 경로 | 이번 실행 | 결과 |
|---|---|---|---|
| F1 | A0_01이 충족 불가능한 프롬프트 규칙(297행)으로 헛 FAILED를 낸다. 재시도는 없다 | 발생 | 실행 전체 BLOCKED |
| F2 | A0_02·A0_03·D0는 실패하면 파일을 쓰지 않아 지난 실행 파일이 남는다(1399·1824·9356행). 하류가 그 파일로 진행한다 | 발생 | 산출물 3종이 지난 입력 기반 |
| F3 | 초안 JSON은 정상인데 A0_02 코드 검증이 실패하는 경우 | 미발생 | **READY인데 내용은 지난 실행 것**이 된다. handoff A0 게이트(9986~9995행)는 초안만 보고, 봉인 대조는 같은 낡은 파일의 해시끼리 비교해 통과한다 |
| F4 | handoff writer가 돌지 못한다(취소·멈춤·Ac 미실행) | 이전 실행(11-03 오전 취소)에서 발생 | 지난 판정 파일이 남는다 |
| F5 | 스크리닝이 실패해도 Task_A가 호출된다 | 발생 | $0.53·486초 낭비 |
**raise로는 해결되지 않는다.**
- 백엔드는 부모가 실패해도 자식을 "dependencies satisfied"로 실행한다. 다만 prev가 비면 task를 다시 렌더링하지 않는다(agent.py 2533~2541행).
- A0_03은 prev를 쓰지 않으므로, A0_02가 raise해도 지난 파일로 READY가 된다.
- 그래서 대책은 **표식(무효화) + 연동 검사 + 최종 게이트**의 조합이다.
## 2. 설계 원칙
- **P1 — LLM은 입력이 있는지만 판단한다.** 구조와 개수 검사는 결정적 코드가 맡는다. LLM의 개수 세기와 머리말 해석은 실행마다 결과가 달라진다.
- **P2 — 산출물은 시작할 때 무효화한다.** 쓰는 task가 맨 앞에서 자기 산출물에 비JSON 표식을 쓰고, 성공했을 때만 정본으로 덮는다. 실패, 시간 초과, 강제 종료, 미실행 어느 경우에도 지난 파일이 남지 않는다. Part 1 11-03 개정의 `PART_PENDING`과 같은 방식이다.
- **P3 — 표식 쓰기의 실패는 숨기지 않는다.**
- 표식 쓰기는 기존 `try: RESULT = main()` 블록 **밖**에서 한다.
- localdocs의 `Error` 응답이면 raise해서 백엔드 재시도를 받는다.
- 이 블록 안에서 쓰면 예외가 `UNHANDLED_EXCEPTION`으로 삼켜져 재시도가 없다.
- **P4 — 연동 검사.** 하류는 상류가 이번 실행에 성공했는지를 prev와 해시로 확인한다. 지금 A0_03이 확인하는 registry의 version과 sha(1693~1703행)는 실행이 바뀌어도 같아서 지난 파일을 가려내지 못한다.
- **P5 — 최종 게이트는 raise 없이 BLOCKED로 끝난다.** handoff writer는 핵심 산출물을 직접 검사하고, 문제가 있으면 `write_blocked_sidecar`로 끝낸다.
- **P6 — 실측되지 않은 백엔드 동작에는 기대지 않는다.** `when` 건너뛰기, SKIPPED 뒤의 대기, 코드 task prev 값의 정확한 형태가 여기에 해당한다. 하네스나 probe로 확인한 뒤에만 쓴다.
## 3. 표식 일람
| 산출물 | 표식(첫 줄) | 쓰는 task | 덮는 곳(성공) | 판별 |
|---|---|---|---|---|
| `quality_gates/stage1_part1_soft_gate_handoff.json` | `HANDOFF_PENDING <utc>` | Evidence planner(M2) | handoff writer 10113행(main)·10013행(`write_blocked_sidecar`) | 비JSON |
| `routing/domain_screening.json` | `SCREENING_PENDING <utc>` | A0_02(M3) | A0_02 1372행 | 비JSON |
| `routing/candidate_profile_vocabulary.md` | `VOCABULARY_PENDING <utc>` | A0_03(M4) | A0_03 1792행 | 첫 줄 접두사, `## DOMAINS` 부재 |
| `routing/domain_activation_manifest.json` | `MANIFEST_PENDING <utc>` | D0(M5) | D0 정본 쓰기 | 비JSON |
- 모든 표식은 `<NAME>_PENDING`으로 시작하는 한 줄이다. 판별은 `raw.lstrip().startswith("<NAME>_PENDING")` 또는 JSON 파싱 실패로 한다.
- 시각은 `datetime.now(timezone.utc).isoformat()`이다.
- **import 주의:** `datetime`이 import된 곳은 planner(2791행)뿐이다. A0_02(721~727행)·A0_03(1427~1433행)·D0(9014~9024행)의 import 구역에는 `from datetime import datetime, timezone`을 반드시 추가한다. 표식 코드는 try 밖에 있으므로, 빠뜨리면 모듈 단계 NameError로 모든 실행(S5 포함)이 막힌다. `ast.parse`로는 잡히지 않는다.
## 4. 수정 항목
### 단계 1 — 지금 적용 (M1~M7)
#### M1. A0_01 프롬프트: 구조 검사를 코드로 넘긴다 (F1)
- **297행**
- 변경 전: "단어 사전의 머리말에 `registry_version`이 없거나 `## DOMAINS` 아래 도메인 절이 26개가 아니면 중단하고 `FAILED: activation_cue_digest`만 보고한다."
- 변경 후: "단어 사전(`Default_Agent/routing/activation_cue_digest.md`)의 내용이 대화에 없거나 비어 있으면 중단하고 `FAILED: activation_cue_digest`만 보고한다. 사전의 형식과 도메인 수는 후속 코드가 검사하므로 판단하지 않는다."
- **311행**
- 변경 전: "사전은 머리말, `## LEGEND`, `## GLOBAL_DEFAULTS`, `## USAGE`, `## DOMAINS` 다섯 부분이다."
- 변경 후: "사전은 `## LEGEND`, `## GLOBAL_DEFAULTS`, `## USAGE`, `## DOMAINS` 네 부분이다."
- **242행(권장):** "registry의 26개 법리 렌즈"를 "사전 `## DOMAINS`에 실린 법리 렌즈"로 바꿔 숫자 하드코딩을 없앤다. 271행의 "원본 26개"는 읽기 금지 대상을 설명하는 문구라 그대로 둔다.
- **바꾸지 않는 것:** 245·278행의 비판단 6종 금지, `<RUNTIME_OUTPUT_OVERRIDE>`(503~510행)의 `FAILED: <사유>` 출구. 정당한 입력 부재를 보고하는 데 필요하다.
- **근거:**
- 배포본과 로컬 원본 digest 모두 머리말이 처음부터 없다. 297행은 원래 충족할 수 없는 규칙이었다.
- 구조 검사는 A0_02가 이미 코드로 한다: `DIGEST_MALFORMED`(1122~1123행), `DIGEST_DOMAIN_SET_MISMATCH`(1128~1129행), 머리말 부재 경고 `DIGEST_HEADER_ABSENT`(1133~1151행).
- A0_01은 재시도가 없어 헛 FAILED 한 번이 곧 실행 전체 BLOCKED가 된다(§0.2 추가 3).
- **검증:** 수정 후 A0_01 프롬프트 구간(153~511행)을 grep해 `26개`·`머리말`·`registry_version`이 다음 행에만 남았는지 확인한다.
- 245·278행: 비판단 6종 금지 목록
- 271행: 원본 26개 읽기 금지
- 403행: 출력 형식 문구
- 242행: 권장 수정을 적용하지 않았을 때
#### M2. Evidence planner: 판정 파일 선무효화 (F4, §0.2 추가 1)
- **위치:** `Task_Evidence_shard_planner` `main()` 첫 줄 `_init()`(2946행) 직후. planner의 `write_doc`(2839~2844행)은 이미 `Error` 응답이면 raise한다.
- **변경:**
```python
# 판정 파일을 실행 초반에 무효화한다. handoff writer 가 돌지 못하면(취소·멈춤·하류 미실행)
# 표식이 남아 Part 2 가 지난 실행의 판정을 읽지 않는다.
HANDOFF_PATH = "quality_gates/stage1_part1_soft_gate_handoff.json"
write_doc(HANDOFF_PATH, "HANDOFF_PENDING %s\n" % datetime.now(timezone.utc).isoformat())
```
- **위치를 planner로 정한 이유:**
- planner는 `IN`에서 곧바로 시작해 실행 첫 4초 안에 끝난다(이번 실행 04:45:39~43).
- A0_02에 두면 A0_01이 끝나는 약 200초 뒤에야 써지므로, 그 전에 취소된 실행은 덮지 못한다.
- P3 확인: 이 줄은 planner `main()` 안에 있다. planner는 바깥에서 예외를 삼키지 않으므로(raise 시 other 2/2 재시도) 조건을 충족한다. 적용 전에 `main()` 호출부를 다시 확인한다.
- **Part 2 쪽 영향:**
- Part 2 guard는 `read_json(HANDOFF)`(`stage_1_part_2_v.8.yml` 658행, `read_json` 정의 250~265행)에서 파싱 오류로 멈춘다. 진행은 막히지만 이유가 `PART1_HANDOFF_BLOCKED`로 나오지 않는다.
- 메시지를 맞추는 Part 2 수정은 §6 연동 항목으로 둔다.
#### M3. A0_02: screening 선무효화 (F2·F3)
- **위치:** 모듈 끝의 `try: RESULT = main()`(1393행) 바로 앞.
- **변경:**
1. `write_doc`(830~832행)에 planner와 같은 `Error` 응답 검사를 넣는다. 응답 text가 `Error`로 시작하면 `RuntimeError("WRITE_FAILED:...")`.
2. try 블록 밖에서 `_init()`을 부르고 표식을 쓴다(P3).
```python
# 지난 실행의 screening 이 하류로 흐르지 않게 먼저 무효화한다. 성공하면 main() 이 정본으로 덮는다.
_init()
write_doc(OUTPUT_PATH, "SCREENING_PENDING %s\n" % datetime.now(timezone.utc).isoformat())
```
3. `main()` 첫 줄의 `_init()`(1072행)은 지운다. 세션은 위에서 연다.
- **선택:** FAILED 출력에 초안 첫 줄 120자를 `draft_head`로 싣는다. `DRAFT_UNREADABLE`일 때 A0c 표식 내용이 바로 보인다.
- **효과:** A0_02가 실패하면 screening은 표식으로 남는다. A0_03, Task_A, D0, handoff writer는 각자의 검사에서 실패를 드러낸다(§5).
#### M4. A0_03: vocabulary 선무효화, A0_02 연동 검사 + Task_A 2014행 이관·단순화 (F2·F3, §0.2 추가 2)
- **(a) 선무효화.** M3과 같이 `write_doc`(1536행)에 `Error` 검사를 넣는다. 그다음 `try: RESULT = main()`(1818행) 앞에서 `_init()`과 `VOCABULARY_PENDING` 표식 쓰기를 하고, `main()` 첫 줄의 `_init()`(1662행)은 지운다.
- **(b) A0_02 연동 검사.** run_code 부모를 `{{prev}}`로 받는 기존 관용인 `stage_1_part_2_v.8.yml` `previous_state()`(1471~1485행)를 그대로 따른다.
- 그 주석은 "백엔드는 run_code 부모의 stdout JSON을 dict로 넣는다(문자열 폴백 유지)"라고 적는다. SKILL.md 556·656행도 같은 뜻이다.
- Part 1 안의 `{{prev}}` 8곳은 모두 LLM 부모라 이 형태의 근거가 되지 않는다.
- 모듈 상단 상수 구역(1544행 부근)에 넣는다.
```python
# A0_02 의 이번 실행 결과. 실패하면 백엔드가 prev 를 채우지 않아 표기가 그대로 남는다.
# 백엔드가 치환하지 않도록 비교용 prev 표기는 나눠 쓴다.
PREV_PLACEHOLDER = "{" * 2 + "prev" + "}" * 2
A0_02_TASK = "Task_A0_domain_screener_02"
A0_02_PREV_TEXT = r"""{{prev}}"""
```
`main()` 첫머리, 1664행 `# ---- 입력 ----` 앞(= **screening을 읽기 전**)에서 1~3을 검사한다. screening이 표식이면 1669~1670행이 `SCREENING_UNREADABLE`로 바로 끝내기 때문이다. 4는 screening을 읽은 뒤에 검사한다. 어긋나면 `fail(...)`를 부르고 `return None`으로 끝낸다. 표식이 남는다.
1. `A0_02_PREV_TEXT.strip() in ("", PREV_PLACEHOLDER)`이면 `UPSTREAM_NO_OUTPUT`(A0_02 실패 또는 미실행)이다.
2. Part 2 `previous_state`와 같은 순서로 푼다.
- `prev = json.loads(A0_02_PREV_TEXT)`. 예외가 나면 명시적으로 잡아 `UPSTREAM_UNPARSEABLE`로 처리한다. 잡지 않으면 바깥 try의 `UNHANDLED_EXCEPTION`이 된다.
- `row = prev.get(A0_02_TASK)`. str이면 `json.loads`한다.
- dict에 `status`가 없고 `json_output`이 dict이면 `row = row["json_output"]`.
- 끝내 dict가 아니면 `UPSTREAM_UNPARSEABLE`이다.
3. `row.get("written") is not True`이면 `UPSTREAM_NOT_WRITTEN`이다. `status`로는 판단하지 않는다. A0_02는 screening `status="FAILED"`를 정상 기록할 수 있고(`STATUS_RANK` 863행, 1405~1407행 `written: True`), 지금은 그런 경우에도 A0_03이 진행한다. 이 동작을 바꾸지 않는다.
4. `row["screening_sha256"]`이 방금 읽은 `screening_raw`의 sha256과 다르면 `SCREENING_NOT_FROM_THIS_RUN`이다.
- A0_02는 기록한 `body`의 sha를 출력하고(1371→1380행), A0_03은 `read_raw` 결과의 sha를 낸다(1666·1690행).
- **쓴 바이트와 읽은 바이트가 같은지는 실측되지 않았다.** 이 YAML의 다른 봉인 대조는 모두 읽은 값끼리 비교한다.
- 그래서 처음에는 이 검사를 `warn("SCREENING_SHA_UNCONFIRMED", ...)`로 둔다. M7-3에서 같음이 확인되면 `fail`로 올린다. 그 전에도 1~3만으로 S1~S3은 막힌다.
- **(c) Task_A 2014행 이관: 새 코드는 넣지 않는다.** 이관할 개수 검사는 이미 코드가 보장한다.
- **같은 실행 안에서는 개수가 늘 맞는다.**
- A0_02는 중복 후보를 `DOMAIN_ID_DUPLICATE`(1213~1215행)로 실패시키고, `if ERRORS: return None`(1347행)으로 screening을 쓰지 않는다.
- A0_03은 후보 하나라도 처리하지 못하면 `if ERRORS: return None`(1756~1757행)으로 vocabulary를 쓰지 않는다.
- `render()`(1636~1642행)는 rows 하나마다 `### ` 머리를 정확히 하나 낸다.
- 따라서 같은 실행의 screening과 vocabulary 사이에서 "절 수 = 후보 수"는 항상 참이다. 이것을 다시 검사하는 코드는 실행되지 않는 코드가 된다.
- **2014행이 실제로 막던 위험은 다른 실행의 파일이 섞이는 것이다.** 그 위험은 다음 두 곳이 맡는다.
- (a) 선무효화
- M6의 `VOCABULARY_STALE` 검사: vocabulary 머리말의 `screening_sha256:`(1603행이 기록)와 현재 screening 원문 해시를 비교한다.
- 이로써 (B)② "2014행 검사의 A0_03 코드 이관"은 "이미 코드가 보장함을 확인 + 섞임 검사는 M6에 둠"으로 반영된다.
- **(d) Task_A 프롬프트 2014행 단순화.**
- 변경 후: "`routing/candidate_profile_vocabulary.md`의 내용이 없거나 비어 있거나 `VOCABULARY_PENDING`으로 시작하면 중단하고 `FAILED: candidate_profile_vocabulary`만 보고한다. 도메인 절 수는 앞선 코드가 보장하므로 세지 않는다."
- 2013행(screening 최상위 키·`candidates` 검사)은 그대로 둔다. 표식이 들어오면 이 규칙이 Task_A를 `FAILED: domain_screening`으로 끝낸다.
- (권장) 2013행에 "또는 `SCREENING_PENDING`으로 시작하면"을 덧붙인다. 그러면 "최상위 키" 해석에 기대지 않고도 표식을 실패로 처리한다.
- **주의:**
- run_code 부모의 prev 형태(stdout JSON이 dict로 들어옴, 문자열 폴백)는 Part 2 `previous_state` 주석, S2_10 load_fanout 관용, SKILL.md 556·656행으로 뒷받침된다. 다만 Part 1에서는 실측된 적이 없다. M7-3(a)로 확인한다.
- `_init()`을 try 밖으로 옮기면 동작이 바뀐다.
- 지금: localdocs 초기화가 실패하면 `UNHANDLED_EXCEPTION`이 되고 FAILED를 출력할 뿐 raise하지 않는다.
- 바뀐 뒤: raise → 재시도 → 그래도 실패하면 출력 없음 → 자식은 S3 경로(`UPSTREAM_NO_OUTPUT`)로 간다. P3 취지에 맞는 변화다.
- 세 task 모두 `_init` 호출은 main 첫 줄 1곳뿐이다(1072·1662·9300행). `MCP_HEADERS`는 모듈 수준에서 정의되므로 다른 코드 경로에는 영향이 없다.
- `{{prev.X | py}}`는 쓰지 않는다. 미치환이면 모듈 적재 단계에서 문법·이름 오류를 내, 표식을 쓰기도 전에 죽는다.
#### M5. D0: manifest 선무효화 (F2)
- **위치:** `try: RESULT = main()`(9349행) 앞. `write_doc`(9129행)에 `Error` 검사를 넣고, try 밖에서 `_init()`과 `MANIFEST_PENDING` 표식을 쓴다. `main()` 첫 줄의 `_init()`(9300행)은 지운다.
- **효과:**
- D0가 실패하면(screening 표식 포함) 지난 manifest가 남지 않는다.
- D0는 A0_02만 기다리므로(`wait_until`) A0_02와 같은 연동 검사를 넣을 수도 있다. 그러나 screening 표식만으로 D0 모듈이 입력 파싱에서 실패하므로 필수는 아니다.
#### M6. handoff writer: 산출물 3종 게이트 (F2·F3, P5)
- **위치:** `read_gate_failures()`(9965행~)의 A0 초안 검사(9985~9995행) 뒤, `return out` 앞.
- **변경:** 세 파일을 읽어 다음 조건이면 `out`에 추가한다.
| 파일 | 실패 조건 | gate / status |
|---|---|---|
| `routing/domain_screening.json` | JSON이 아니다(표식 포함), 또는 `domain_screening` dict가 없다 | `A0` / `SCREENING_UNREADABLE` |
| `routing/candidate_profile_vocabulary.md` | `VOCABULARY_PENDING`으로 시작한다, 또는 `## DOMAINS`가 없다 | `A0` / `VOCABULARY_UNREADABLE` |
| `routing/domain_activation_manifest.json` | JSON이 아니다(표식 포함) | `D0` / `MANIFEST_UNREADABLE` |
| vocabulary ↔ screening | vocabulary 머리말 `screening_sha256: \`…\``(1603행 형식)이 현재 screening 원문의 `digest()`와 다르다. 두 값 모두 읽은 원문 기준이라 쓰기·읽기 동일성에 기대지 않는다 | `A0` / `VOCABULARY_STALE` |
`VOCABULARY_STALE`은 Task_A 2014행이 막던 "다른 실행 파일의 섞임"을 코드로 대신하는 검사다(M4(c)).
읽기 자체가 예외이면 기존 패턴처럼 `detail=str(exc)[:300]`으로 담는다.
- **효과:** 지금은 screening이나 manifest가 깨지면 `main()`의 `parse_json`(10024행 부근)에서 예외가 나고, T9 EXCEPTION으로 BLOCKED를 쓴 뒤 raise한다(10128~10136행). 바뀐 뒤에는 원인이 이름 붙은 게이트로 기록되고 raise 없이 끝난다.
- **바꾸지 않는 것:** 기존 A 게이트(`CLIENT_GOAL_UNREADABLE`)와 A0 초안 게이트, 봉인 대조, `write_blocked_sidecar`.
#### M7. 검증: 오프라인 하네스 → 온라인
1. **정적 검사**
- ruby YAML 적재와 task 29개 확인
- 코드 task 전부 `ast.parse` 통과
- 표식을 쓰는 4개 task(planner·A0_02·A0_03·D0)에 `datetime`·`timezone` import가 있는지 확인. `ast.parse`로는 NameError를 잡지 못하므로 2단계 하네스에서 실제 실행으로도 확인한다.
- `{{` 치환 대상 점검: A0_03에 새로 생긴 `{{prev}}`는 `A0_02_PREV_TEXT` 1곳뿐이어야 한다. 나머지는 나눠 쓴 비교 문자열이어야 한다.
2. **하네스(localdocs 모의)**
- 시나리오 S1~S5(§5)를 코드 task 단위로 재현한다.
- 각 시나리오에서 handoff 판정, 산출물 4종의 표식·정본 상태, raise 여부가 §5와 같은지 확인한다.
- 이전 세션의 `chk_pm.py` 구조(httpx 스텁, 템플릿 렌더링)를 재사용한다.
3. **prev 형태와 sha 동일성 확인(온라인 1회 로그로)**
- (a) A0_03의 `A0_02_PREV_TEXT`가 실제로 어떻게 렌더링되었는지 확인한다(stdout JSON인지 봉투인지). `[EXECUTOR] re-created with rendered prev context` 직후의 코드 원문을 로그에서 대조한다.
- (b) 같은 실행의 A0_02 stdout `screening_sha256`(쓴 본문 기준)과 A0_03 stdout `screening_sha256`(읽은 원문 기준)이 같은지 대조한다. 두 값은 이미 둘 다 출력되고 있다. 같으면 M4(b)-4를 `warn`에서 `fail`로 올린다.
- 지난 정상 실행의 로그는 컨테이너 재시작으로 남아 있지 않다. 그래서 다음 온라인 실행에서 확인한다.
4. **온라인:** Part 1을 중간 취소 없이 한 번 실행한다. 판정이 `READY` 계열인지, 산출물 4종이 정본인지, 표식이 남지 않았는지 확인한다.
5. **선택:** 온라인 1회는 의도적으로 S2를 만들어(초안의 근거 하나를 범위 밖 값으로) BLOCKED 경로를 실측한다. 비용은 Task_A 1회분이다.
### 단계 2 — probe 확인 뒤 도입 (F5, §0.2 추가 4)
#### M8. A0_03 → Task_A 건너뛰기 (`when`) — 보류
- **안:** `task_procedure`의 `Task_A0_domain_screener_03.nexts`를 `- task: Task_A_client_goal` + `when: output.status == 'READY'`로 바꾼다.
- **전제:** M2가 적용되어 있어야 한다. 그래야 건너뛴 뒤 판정이 기록되지 않아도 지난 READY 판정이 남지 않는다.
- **먼저 확인할 것(단독 probe YAML):**
- (i) SKIPPED 뒤 Ac가 실행되는가, 실행된다면 prev가 비어 `UPSTREAM_NO_OUTPUT` 표식을 쓰는가.
- (ii) handoff writer와 OUT이 도달하는가, 아니면 대기에서 멈추는가. S2_10에서 조건으로 건너뛴 fan-out 부모 뒤의 `all X_*` 대기가 멈춘 사례가 있다.
- (iii) 백엔드의 `task_skip` 이벤트(agent.py 2525행 부근) 뒤 `execution_complete`가 나오는가.
- **YAML 안의 선례:** 11350~11356행. B2 게이트가 B12를 `when`으로 건너뛰고, 주석은 "B12c와 finalizer는 그대로 돈다"고 적는다. 팬아웃이 아닌 LLM → capture 형태다. 이 선례는 (i)·(iii)의 부분 근거가 되지만 실측 여부는 UNVERIFIED다. (ii)에 해당하는 선례는 없으므로 probe가 여전히 필요하다.
- **판단 기준:**
- (i)·(ii)·(iii)이 모두 정상이면 도입한다.
- (ii)가 멈추면 도입하지 않는다. 멈춘 실행은 M2 표식 덕분에 안전하지만 사용자에게는 끝나지 않는 실행이 된다.
- **도입하지 않을 때의 비용:** S1·S2에서 Task_A 1회. 입력 약 3만 6천 토큰과, 짧은 `FAILED` 응답 전까지의 추론 시간이다. 이번 A0_01처럼 오래 생각할 수 있어 시간은 UNVERIFIED다.
## 5. 시나리오별 기대 결과 (M1~M6 적용 뒤)
| # | 상황 | A0_02 | A0_03 | Task_A → Ac | D0 | handoff |
|---|---|---|---|---|---|---|
| S1 | A0_01이 비JSON(이번 사례) | 초안 파싱 실패 → `SCREENING_PENDING` 남음 | `UPSTREAM_NOT_WRITTEN`(prev 검사, screening 읽기 전) → `VOCABULARY_PENDING` 남음 | 호출됨 → `FAILED: domain_screening` → `client_goal.json` 표식 | screening 파싱 실패 → `MANIFEST_PENDING` 남음 | BLOCKED: A0 초안, A0 screening, A0 vocabulary, D0, A 게이트. raise 없음 |
| S2 | 초안 정상, A0_02 검증 실패 | `SCREENING_PENDING` 남음 | S1과 같음 | S1과 같음 | S1과 같음 | BLOCKED: A0 screening, A0 vocabulary, D0, A 게이트. **지금은 READY로 봉인되는 경로** |
| S3 | A0_02 표식 쓰기 실패(localdocs Error) | raise → 재시도 2/2 → FAILED, screening은 지난 것 | 재렌더링 없음 → `UPSTREAM_NO_OUTPUT` → `VOCABULARY_PENDING` | 지난 screening + vocabulary 표식 → 2014행 규칙으로 FAILED → 표식 | 지난 screening으로 정본 생성 가능 | BLOCKED: A0 vocabulary, A 게이트 |
| S4 | handoff writer 이전에 취소·멈춤 | — | — | — | — | `HANDOFF_PENDING` 남음 → Part 2 진행 불가 |
| S5 | 정상 | 정본 | prev 검사 통과(sha는 확인 전 warn) → 정본 | 정상 | 정상 | READY 계열 |
- S3에서 D0가 지난 screening으로 만든 manifest는 봉인 대조를 통과할 수 있다. 그래도 vocabulary와 A 게이트가 BLOCKED를 보장한다.
- D0에 A0_02 연동 검사(M5 선택)를 넣으면 S3에서도 manifest가 표식으로 남는다.
## 6. 적용 순서와 범위
1. 보존본 `stage_1_part_1_v.8_11_03_<시각>.yml`을 만든다.
2. 패치 스크립트(앵커 1회 일치 검사)로 M1 → M2 → M3 → M4 → M5 → M6을 적용한다. 머리말 "개정 요지"에 한 항목을 추가하고 구성표의 [개정] 표기를 갱신한다. 대상은 A0_01·A0_02·A0_03·Task_A·planner·D0·handoff writer 7개다.
3. M7 1~3(정적 검사, 하네스, prev 형태 확인)
4. 커밋과 업로드: 사용자 승인 필요
5. M7 4(온라인)
6. 단계 2(M8)는 별도 probe 결과를 본 뒤 결정한다.
**범위 밖 · 연동 권고**
- **Part 2 guard 메시지(선택):** `stage_1_part_2_v.8.yml`의 handoff 읽기(658행)에서 원문이 `HANDOFF_PENDING`으로 시작하면 `PART1_HANDOFF_BLOCKED`(remedy: Part 1 재실행)를 내게 한다. 지금도 진행은 막히지만, 원인이 JSON 파싱 오류로 보이지 않게 하려는 것이다.
- **handoff writer `write_doc`(9535행)의 `Error` 검사(선택):** 지금은 판정 쓰기가 실패해도 stdout에 `SOFT_GATE_HANDOFF_WRITTEN`이라고 거짓 보고한다. M2 표식 덕분에 안전한 쪽으로 실패하지만, 보고는 정확해야 한다. planner와 같은 검사를 넣는 것을 권한다.
- **planner 실패 시 지난 `evidence_shard_plan.json`(11-03 보류 지적):** 이번 범위가 아니다.
- **백엔드 `_apply_verbosity` 수정:** 이번 범위가 아니다.
## 7. 확인하지 못한 것
- 코드 task를 prev로 받은 값의 정확한 형태. `_build_prev_value`가 run_code 응답 봉투를 주는지 stdout JSON을 바로 주는지 확인하지 못했다. M4(b)-2의 다형 파싱과 M7-3(a)로 대응한다.
- localdocs의 쓰기·읽기 바이트 동일성. M4(b)-4는 확인 전까지 warn으로 둔다(M7-3(b)).
- `when` SKIPPED 뒤의 대기 동작. M8 probe가 필요하다.
- M1 이후에도 Gemini가 다른 이유로 FAILED를 낼 가능성. 정당한 입력 부재 외의 FAILED는 S1 경로로 BLOCKED가 된다.
## 8. 개정 이력
- **v1:** 최초 작성. `추가수정_for_결과보고서_part_1.md` §2와 추가 항목 4건을 통합했다.
- **v2 (독립검증 1차 반영)**
- A0_02·A0_03·D0에 `datetime` import 추가를 명시했다(치명).
- M4(b)를 실측된 `{{prev}}` 형태로 바꾸고 str·봉투를 모두 처리하게 했다.
- prev 검사를 screening 읽기 전으로 옮겼다.
- `status` 대신 `written`으로 판정하게 했다.
- sha 검사는 쓰기·읽기 동일성을 확인할 때까지 warn으로 둔다.
- M4(c)를 "항상 통과하는 절 수 검사"에서 "screening 중복 후보 검사"로 바꿨다.
- M1 grep 제외 행을 명시했다.
- 행 번호를 정정했다(1792·10013·10113·658·1122·1128).
- S1·S5 표를 정정했다.
- handoff writer `write_doc`의 Error 검사를 연동 권고에 추가했다.
- **v3 (독립검증 2차 반영)**
- M4(c)의 중복 후보 검사를 지웠다. A0_02 1213행과 A0_03 1756행이 이미 보장하므로 실행되지 않는 코드였다. 섞임 위험은 M6 `VOCABULARY_STALE`로 옮겼다.
- M4(b) prev 파싱을 Part 2 `previous_state`(1471~1485행) 관용으로 바꿨다. `json_output` 폴백을 넣고, `output` 분기는 지우고, 파싱 예외를 명시적으로 잡는다.
- 검사 위치를 "1664행 앞"으로 고쳐 (a)와의 모순을 없앴다.
- §0.1에 (A)-3의 status 조건을 제외한 사실을 적었다.
- 행 번호를 정정했다(658·721~727).
- M1 grep에 242행 조건을 더했다.
- `_init` 이동에 따른 동작 변화를 적었다.
- M8에 11350~11356행 선례를 적었다.
@@ -0,0 +1,85 @@
# 추가 수정안: 결과보고서_part_1.md §6 권고 조치 재작성
- 대상: `1. Stage_1/v.8/stage_1_part_1_v.8.yml`(`9c425a21…`). 행 번호는 이 파일 기준이다. YAML은 아직 고치지 않았다.
- 근거:
- 세션 `e278fe64` 로그(`run_e278.log`)
- 독립 검증 1회(sub-agent, 읽기 전용 코드 추적)
- 주 세션의 인용 행 대조(242·245·311·1399·1824·2013·2014·9356·9986행)
## 1. 검증 결과 요약
| 원래 권고 | 판정 | 이유 |
|---|---|---|
| ① A0_01 297행에서 `registry_version` 머리말 요구를 지우고 26개 검사만 남긴다 | **부분 정확** | 방향은 맞다. 그러나 26개 검사도 LLM에 남기면 같은 종류의 헛 FAILED가 다시 날 수 있다. A0_02 코드가 이미 같은 검사를 한다 |
| ② A0_02가 FAILED이면 `domain_screening.json`에 비JSON 표식을 쓴다 | **정확하지만 불충분** | 실패하면 파일을 덮어쓰지 않는 결함이 A0_03과 D0에도 있다. 또 실패 분기에서만 쓰면 시간 초과나 강제 종료는 덮지 못한다 |
**① 확인 사항**
- 프롬프트는 초안에 머리말 값을 쓰라고 요구하지 않는다. 오히려 비판단 6종(`registry_version` 등)은 A0_02가 붙인다며 금지한다(245행).
- A0_02는 그 값을 registry 원문에서 직접 계산한다(1110·1117행). digest에 머리말이 없으면 경고 `DIGEST_HEADER_ABSENT`만 남긴다(1133~1151행).
- 따라서 머리말 요구를 지워도 모델이 채우지 못할 값은 생기지 않는다.
- 배포본과 로컬 원본 digest 모두 머리말이 처음부터 없다. 297행 규칙은 원래 충족할 수 없는 규칙이었다.
- 이번에 처음 터진 것은 11-03에 추가한 `<RUNTIME_OUTPUT_OVERRIDE>`(503~510행)가 `FAILED: <사유>` 한 줄 출구를 명시한 탓으로 보인다. This is an inference without much evidence.
**②에서 새로 드러난 더 위험한 경로**
- 초안 JSON은 정상인데 A0_02의 코드 검증에서 실패하는 경우다(`CONSERVATION_FAILED`·`DIGEST_MALFORMED` 등).
- handoff의 A0 게이트(9986~9995행)는 **초안** 파싱 실패만 본다. 이 경우는 잡지 못한다.
- 그러면 D0가 지난 screening으로 manifest를 만든다. handoff의 봉인 대조도 같은 낡은 파일의 해시끼리 비교하므로 통과한다.
- 결과는 **READY인데 내용은 지난 실행 것**이 된다.
**raise는 대안이 아니다.** 백엔드는 부모가 실패해도 자식을 실행한다. A0_03은 `{{prev}}`를 쓰지 않으므로 raise해도 지난 파일로 READY가 된다.
## 2. 재작성한 권고 조치 (적용 순서)
1. **A0_01 프롬프트: 구조 검사를 LLM에서 빼고 코드로 넘긴다.**
- 297행을 "단어 사전 내용이 대화에 없거나 비어 있으면 `FAILED: activation_cue_digest`만 보고한다"로 바꾼다. 머리말 검사와 26개 검사를 모두 지운다.
- 구조 검사는 A0_02가 이미 맡고 있다(`DIGEST_MALFORMED` 1121행, `DIGEST_DOMAIN_SET_MISMATCH` 1127행).
- 311행의 "머리말, … 다섯 부분"은 "`## LEGEND`·`## GLOBAL_DEFAULTS`·`## USAGE`·`## DOMAINS`"로 바꾼다.
- (선택) 242행 "registry의 26개 법리 렌즈"는 "사전 `## DOMAINS`의 도메인 절 전체"로 바꿔 숫자 하드코딩을 없앤다.
2. **A0_02: 시작할 때 screening을 무효화한다.**
- `_init()` 직후 `routing/domain_screening.json`에 비JSON 표식을 쓴다. 예: `SCREENING_PENDING Task_A0_domain_screener_02 <utc>`.
- 성공하면 정본 쓰기(1372행)가 표식을 덮는다. 실패 분기(1399행), 시간 초과, 강제 종료에서는 표식이 남는다.
- 표식 쓰기가 실패하면(localdocs "Error" 응답) raise해서 백엔드 재시도를 받는다. planner `write_doc`과 같은 방식이다.
- (선택) FAILED 출력에 A0c의 `detail`(초안 첫 줄)을 실어 원인을 드러낸다.
3. **A0_03: 시작할 때 vocabulary를 무효화하고, A0_02 결과와 연동 검사를 한다.**
- `_init()` 직후 `routing/candidate_profile_vocabulary.md`에 표식을 쓴다.
- `r"""{{prev}}"""`로 A0_02의 출력을 받는다. A0_03은 A0_02 하나만 기다리므로 prev가 렌더링된다. 다음 중 하나라도 해당하면 FAILED로 끝낸다.
- prev가 비었거나 치환되지 않은 표기다(비교 문자열은 `"{"*2+"prev"+"}"*2`로 나눠 쓴다).
- `status == "FAILED"`이거나 `written != true`다.
- prev의 `screening_sha256`이 방금 읽은 screening 원문의 sha와 다르다.
- 지금 A0_03은 registry의 version과 sha(1693~1703행)만 확인한다. 이 값은 실행이 바뀌어도 같아서 지난 screening을 걸러내지 못한다.
4. **D0: 시작할 때 `routing/domain_activation_manifest.json`을 무효화한다.** 실패하면 출력만 하고 미기록하는 동작(9356행)이 지난 manifest를 남기기 때문이다.
5. **handoff writer `read_gate_failures`(9965행~): 산출물 자체를 게이트로 검사한다.**
- 다음 파일이 파싱되지 않거나 표식이면 게이트 실패로 추가한다.
- `domain_screening.json` → `A0`/`SCREENING_UNREADABLE`
- `candidate_profile_vocabulary.md` → `A0`/`VOCABULARY_UNREADABLE`
- `domain_activation_manifest.json` → `D0`/`MANIFEST_UNREADABLE`
- 이렇게 하면 지금처럼 `parse_json` 예외로 raise하지 않고, BLOCKED를 기록한 뒤 정상 종료한다.
6. **오프라인 하네스로 재현한 뒤 온라인 재실행한다.** 다음 두 경우를 하네스로 재현해, 둘 다 handoff가 `BLOCKED`로 끝나고 하류 산출물 3종이 표식인지 확인한다.
- (a) 초안이 표식인 경우(이번 사례)
- (b) 초안은 정상인데 A0_02 검증이 실패하는 경우
그다음 Part 1을 다시 돌려 handoff READY 계열을 확인한다.
**보류 (근거 부족 · 실측 필요)**
- **A0_03→Task_A에 `when: output.status == 'READY'`를 걸어 Task_A 호출(약 $0.53·486초)을 건너뛰는 방안.**
- SKIPPED 뒤에 Ac와 handoff가 실행되는지는 실측된 적이 없다.
- Ac가 실행되지 않으면 handoff가 기록되지 않아 지난 handoff가 남을 위험이 있다.
- 단독 probe로 확인하기 전에는 도입하지 않는다. 1~5만 적용해도 Task_A는 `FAILED: domain_screening`을 내고, Ac 표식을 거쳐 A 게이트에서 BLOCKED가 된다.
- **Task_A 2014행의 vocabulary 도메인 절 수 검사(LLM 개수 세기)를 A0_03 코드로 넘기는 방안.** ①과 같은 위험이지만 이번 실행에서는 터지지 않았다. 3번을 작업할 때 같이 검토한다.
- **A0_01 재시도.** `max_iterations: 1`은 prev가 없어 적용되지 않고(로그 "1/8"), FAILED 응답은 성공으로 처리된다. 1번으로 FAILED가 나올 조건을 없애는 것이 실질적인 대책이다.
## 3. 원래 권고와의 차이
| 항목 | 원래 | 재작성 |
|---|---|---|
| A0_01 검사 | 머리말만 삭제 | 머리말·26개 모두 코드로 이관, 311행 문구 수정 |
| 무효화 시점 | A0_02 실패 시 | A0_02·A0_03·D0 시작 시(시간 초과·강제 종료 포함) |
| 무효화 범위 | screening 1개 | screening·vocabulary·manifest 3개 |
| 연동 검사 | 없음 | A0_03이 A0_02의 `status`·`written`·`screening_sha256` 대조 |
| 최종 게이트 | 초안만 검사 | 산출물 3종도 검사해 raise 없이 BLOCKED |
| 검증 | 온라인 재실행 | 오프라인 하네스 2경우 → 온라인 |
@@ -0,0 +1,130 @@
# Stage 1 Part 2 R0 통계치 (2026-11-04 실행)
- **대상:** `stage_1_part_2_v.8.yml`(`22ac686f…`)의 workspace `11월_1일_구성` 실행. 세션 `7f798164`, 04:50:58~04:59:31 UTC. worker 15개는 GPT-6.1 Sol, reasoning high.
- **근거(모두 읽기 전용):**
- `agent-backend` 로그. R0 stdout과 에러 문자열을 확인했다.
- localdocs에서 읽은 산출물:
- worker 원본 `runtime/domain_seed_outputs/<D>.json` 15개
- R0 수용본 `stage1_tmp/task_c_bo/admitted_seeds/<D>.json` 15개
- `stage1_tmp/task_c_bo/postb_seed_ledger.json`
- `quality_gates/stage1_part2_review_handoff.json`
- `BO.json`
- 집계 스크립트: scratchpad `p2c/r0_stats.py`.
- **용도:** 다음 비교 실행(예: worker reasoning medium)의 기준선.
## 요약
| 항목 | 값 |
|---|---|
| R0 상태 | `READY`. **BLOCK 0, 격리 0, 거부 0** |
| 수용 처분(`admission_records`) | 610건 = 보정 607(`repair_harvest` 532 · `repair_derive` 75) + review 3 |
| 후보 → BO | worker 후보 107 → 수용 107 → BO 107(소실 0, 병합 흡수 0) |
| review 항목 | worker 원본 seed 330건(후보 `review_items` 306 + `unknown_or_unrouted_reviews` 24). R0·F0를 거친 review handoff 1,145건(모두 `SOFT_WARNING`, 최종 작성 차단 0) |
| 증거 슬롯(483개) | filled 223(46.2%) · partial 177(36.6%) · missing 66(13.7%) · conflicted 17(3.5%) |
## 1. R0 격리·거부 건수와 BLOCK 여부
- **BLOCK 없음.** R0 stdout은 `"status": "READY"`이고 ledger도 `READY`다.
- 로그에 `PART2_SEED_ADMISSION_BLOCKED`와 `source_refs outside Stage A universe`가 각각 보인다. 그러나 둘 다 task에 넘긴 코드 본문(`params=`) 안의 문자열이며, 실행 결과로 나온 것이 아니다.
- **격리 0, 거부 0.** ledger의 `SEED_ADMISSION_SUMMARY`는 `enforcement: enforce`, `quarantined_candidates: 0`, `admitted_candidates: 107`, `quarantine_ratio: 0.0`이다.
- **처분 610건은 후보를 버리지 않는 보정이다.** R0는 이 기록을 review handoff에 `R0:admission:NNN`으로 남긴다.
| 처분 | 원인 코드 | 건수 | 내용 |
|---|---|---:|---|
| `repair_harvest` | `SCHEMA_PATTERN` | 400 | `party_refs`(280)에 한글 이름, `object_refs`(120)에 문장. 패턴 `^[A-Za-z][A-Za-z0-9_.:/-]*$` 위반이라 값을 `worker_surplus`로 옮겼다 |
| `repair_harvest` | `SCHEMA_TYPE` | 132 | `dependency_refs`에 `{"domain_id","source_refs"}` 객체를 적었다. 도메인 id 문자열이어야 한다 |
| `repair_derive` | `SCHEMA_REQUIRED` | 75 | `completion_receipt` 필수 5키(`domain_id`·`task_instance_id`·`seed_count`·`emitted_seed_ids`·`r0_membership_key`)가 15개 도메인 모두에서 빠져 R0가 채웠다 |
| `review` | `SCHEMA_ADDITIONAL_PROPERTY` | 3 | X1 `completion_receipt`에 스키마 밖 키 3개 |
- 도메인별 처분 건수는 §2 표의 "처분" 열에 있다.
- `repair_derive`는 X3를 포함한 모든 도메인에서 5건씩이다. 나머지 도메인 차이는 모두 `repair_harvest` 건수다.
## 2. 도메인별 `bo_seed_candidates` 수와 BO 수
| 도메인 | worker 후보 | 수용 | BO | 후보 review | unrouted | handoff 항목 | 처분(harvest/derive/review) |
|---|---:|---:|---:|---:|---:|---:|---|
| E-01 | 5 | 5 | 5 | 14 | 2 | 50 | 17 / 5 / 0 |
| E-02 | 13 | 13 | 13 | 34 | 1 | 119 | 52 / 5 / 0 |
| E-03 | 3 | 3 | 3 | 11 | 1 | 47 | 23 / 5 / 0 |
| E-04 | 9 | 9 | 9 | 27 | 2 | 93 | 39 / 5 / 0 |
| E-07 | 1 | 1 | 1 | 4 | 1 | 15 | 3 / 5 / 0 |
| E-08 | 3 | 3 | 3 | 20 | 2 | 46 | 12 / 5 / 0 |
| E-09 | 24 | 24 | 24 | 61 | 3 | 238 | 131 / 5 / 0 |
| E-10 | 14 | 14 | 14 | 25 | 2 | 142 | 88 / 5 / 0 |
| E-11 | 5 | 5 | 5 | 13 | 2 | 58 | 26 / 5 / 0 |
| E-12 | 1 | 1 | 1 | 3 | 1 | 16 | 4 / 5 / 0 |
| E-13 | 5 | 5 | 5 | 18 | 2 | 76 | 39 / 5 / 0 |
| E-15 | 2 | 2 | 2 | 7 | 1 | 28 | 11 / 5 / 0 |
| X1 | 12 | 12 | 12 | 40 | 2 | 111 | 40 / 5 / 3 |
| X2 | 10 | 10 | 10 | 23 | 2 | 100 | 47 / 5 / 0 |
| X3 | 0 | 0 | 0 | 0 | 1 | 6 | 0 / 5 / 0 |
| **합계** | **107** | **107** | **107** | **306** | **24** | **1,145** | **532 / 75 / 3** |
- **BO 수는 모든 도메인에서 후보 수와 같다.** F0 게이트 `candidate_conservation`이 "BO 107 + absorbed 0 == ledger 107"로 PASS했다. 근접 중복 군집 20개는 모두 `KEEP_SEPARATE`로 유지됐다.
- **BO 유형:** event 92, state 15. 금액이 결속된 BO는 57건이다.
- **X3**는 seed 상태가 `READY_WITH_REVIEW`인데 후보가 0이다. D0 선별 근거도 0건이었다(slice `positive_refs` 0).
- **handoff 항목**에는 도메인 귀속 항목만 셌다. 같은 순서로 대응한다.
## 3. `review_items` 수
| 층 | 건수 | 구성 |
|---|---:|---|
| worker 원본 seed | 330 | 후보 `review_items` 306 + `unknown_or_unrouted_reviews` 24 |
| review handoff(최종) | 1,145 | 아래 표 |
| handoff `issue_type` | 건수 | 비고 |
|---|---:|---|
| `seed_admission_repair` | 610 | §1의 R0 처분 |
| `review_required` | 325 | 도메인 review |
| `EXTENSION_PAYLOAD_KEY_UNDECLARED` | 107 | F0, BO 전부 |
| `amount_or_date_uncertain` | 80 | |
| `near_duplicate_kept_separate` | 20 | |
| `schema_field_fallback` | 3 | |
- 심각도는 1,145건 모두 `SOFT_WARNING`이다. `blocks_final_drafting: true`는 0건이다.
- **도메인 review 상위 코드:**
- `E09_CAUSE_REGISTRY_MISMATCH_REVIEW` 32
- `UNROUTED_ISSUE_REVIEW` 26
- `UNREGISTERED_EFFECT_TYPE_REVIEW` 24
- `E09_THIRD_PARTY_CONSENT_REVIEW` 24
- `E02_PAYMENT_STATUS_CONFLICT` 12
- `X2_STATE_OR_LINEAGE_CONFLICT` 12
- 1,145건의 53%는 worker 형식 오류에서 나온 보정 기록이다. 순수한 판단 review는 325건 + 80건이다.
## 4. `evidence_slot_status`의 filled/missing 분포
| 도메인 | filled | partial | missing | conflicted | 슬롯 합계 | filled 비율 |
|---|---:|---:|---:|---:|---:|---:|
| E-01 | 7 | 9 | 1 | 0 | 17 | 41% |
| E-02 | 40 | 17 | 1 | 0 | 58 | 69% |
| E-03 | 2 | 7 | 0 | 0 | 9 | 22% |
| E-04 | 12 | 26 | 16 | 4 | 58 | 21% |
| E-07 | 2 | 2 | 4 | 0 | 8 | 25% |
| E-08 | 5 | 13 | 3 | 2 | 23 | 22% |
| E-09 | 60 | 37 | 23 | 0 | 120 | 50% |
| E-10 | 4 | 21 | 3 | 0 | 28 | 14% |
| E-11 | 20 | 11 | 0 | 3 | 34 | 59% |
| E-12 | 0 | 1 | 1 | 0 | 2 | 0% |
| E-13 | 2 | 8 | 1 | 3 | 14 | 14% |
| E-15 | 2 | 2 | 1 | 0 | 5 | 40% |
| X1 | 43 | 6 | 10 | 1 | 60 | 72% |
| X2 | 24 | 17 | 2 | 4 | 47 | 51% |
| X3 | 0 | 0 | 0 | 0 | 0 | — |
| **합계** | **223** | **177** | **66** | **17** | **483** | **46.2%** |
- **R0는 슬롯 판정을 바꾸지 않았다.** worker 원본과 수용본의 분포가 15개 도메인 모두 같다.
- **missing이 많은 도메인:** E-04 16, E-09 23, X1 10. 세 도메인이 missing의 74%다.
- **filled 비율이 낮은 도메인:** E-10 14%, E-13 14%, E-04 21%, E-03 22%. partial이 대부분이다.
- **conflicted 17건:** E-04 4, X2 4, E-11 3, E-13 3, E-08 2, X1 1. 상충 근거가 함께 있는 슬롯이다.
## 5. 해석과 비교 시 볼 점
1. **수용 단계는 건전하다.** BLOCK·격리·소실이 모두 0이다. 처분 610건은 전부 형식 보정이고 후보 내용은 유지됐다.
2. **다만 보정 532건은 정보 손실을 동반한다.** `party_refs`·`object_refs`·`dependency_refs`의 값이 BO에 투영되지 않아, BO 107건의 `core_field_base.Object`가 모두 null이다. 원인은 worker 프롬프트가 이 칸들의 식별자 형식을 알려 주지 않는 것이다(`결과보고서_1_part_2.md` §4-2).
3. **reasoning을 medium으로 낮춰 비교할 때 볼 지표:**
- 수용 처분 610건과 그중 `repair_harvest` 532건
- 격리 건수
- 도메인별 후보 수(E-09 24, E-10 14, E-02 13)
- 슬롯 filled 비율 46.2%와 missing 66건
- 도메인 review 325건
4. **검증 범위:** 숫자는 산출물 파일에서 직접 셌다. 법률적 정확성은 판단하지 않았다.
@@ -0,0 +1,95 @@
# Stage 1 Part 2 결과보고서 1 (2026-11-04 실행)
- **대상:** `stage_1_part_2_v.8.yml`(11-04 일치성 개정판 `22ac686f…`, task 9종).
- **실행:** workspace `11월_1일_구성`, 세션 `7f798164`, 2026-11-04 04:50:58 ~ 04:59:31 UTC(8분 33초).
- **근거:**
- `agent-backend` 로그(코드 task stdout, `[USAGE]`).
- localdocs `read_docs`로 읽은 산출물(seed 15, ledger, exception pack, review handoff, R1 판정, BO.json, slice·공유 우주, 서버 자산 366건).
- 모두 읽기 전용으로 확인했다.
## 1. 판정 — **부분 성공**: BO까지 완성, 마지막 S0(signal) 실패
| 기준 | 결과 |
|---|---|
| 백엔드 | task 36건 중 35건 성공. `Task_C_BO_S0_signal_bundle_writer`가 2회 시도 모두 `exit_code=1`로 끝나 `task_error`가 1건 났다. `execution_complete`는 나왔다 |
| 핵심 산출물 | A0 `READY`, fan-out `CLEARED`(15), seed 15건 `READY_WITH_REVIEW`, R0 `READY`, R1 `READY`, F0 `PASS`. **`BO.json` 107건 작성** |
| 실패 원인 | `MODULE_MIRROR_HASH_MISMATCH:Default_Agent/signals/adapters/s3_domain_seed_adapter.txt`. 서버 workspace 사본(7,223자, sha `0aa58a1d…`)은 10-31 개정 전 판본이다. manifest가 기대하는 값은 `0372ac56…`이고 로컬과 174행이 다르다. `signals/emitters/emitter_runtime.txt`도 서버 사본이 옛 판본이어서, adapter를 고쳐도 다음 검사에서 같은 오류가 난다 |
| 영향 | Part 2 signal 묶음(SG-02~13, `compatibility_views/*`)이 만들어지지 않았다. 잔재 파일도 없다(`actio_case_signals.json` 등 not found). **Part 3·S2가 signal을 읽는다면 이 회차로는 진행할 수 없다** |
| 이번 개정 | 개정 4건이 모두 실행에서 확인됐다(§3). A0 봉인 대조, 모듈 해시, manifest pin(`a828e962…`)도 모두 통과했다 |
**왜 A0는 통과하고 S0만 멈췄나.** A0는 자기가 반입하는 stage1_runtime 모듈 8개만 manifest와 대조한다. 이번에 올린 두 모듈과 manifest는 서버 사본이 로컬과 같다. 반면 S0는 signal adapter 4개, emitter 13개, compiler 7개를 반입하는데, 그중 10-31 이후 바뀐 두 파일이 서버에 올라가지 않았다.
서버에 아예 없는 manifest 항목도 214건 있다(computations, law_versions, router 등). Part 2 task 중 이 파일을 읽는 것은 없으므로 이번 실패와는 관계없다.
## 2. IO 구조 (DAG)
```
[입력·Part 1] handoff(digest_guard 7키) · domain_screening · domain_activation_manifest · evidence_indexed
· evidence_event_candidates · value_facts(+gate) · client_meeting.md · 배포 자산(Default_Agent/*)
A0 (코드 4.5s) ─ 봉인 대조(screening·manifest·registry + C-05 증거·사건) · 모듈 반입 · stage_a · slice 15
├▶ stage1_tmp/task_c_bo/{stage_a_context, source_universe_manifest, value_facts_catalog}.json
├▶ runtime/domain_slices/<D>.json ×15 · runtime/compiled_prompts/<D>.md ×15
└▶ runtime/shared/{source_universe.json(254,830자), vocabulary.md} · runtime/worker_inputs/<D>.json ×15
│
prewarm (Sol 3.3s, 캐시 113,723토큰 생성) ─▶ load_fanout (코드) ─▶ fanout/domain_fanout_plan.json
│
▼ 동시 8개씩
worker_* ×15 (GPT-6.1 Sol high, 11~268s) ─▶ capture_* ×15 ─▶ runtime/domain_seed_outputs/<D>.json
│ (all)
R0 (코드 4.1s) ─▶ stage1_tmp/task_c_bo/{admitted_seeds/<D>.json, postb_seed_ledger.json}
└▶ quality_gates/stage1_part2_exception_pack.json (예외 13)
▼
R1 (Flash-Lite 8.4s) ─▶ stage1_tmp/task_c_bo/postb_adjudication_decisions.json
▼
F0 (코드 3.5s) ─▶ BO.json (107) · postb_compiled_bundle_compact.json · quality_gates/stage1_part2_review_handoff.json
▼
S0 (코드) ✗ MODULE_MIRROR_HASH_MISMATCH ─▶ (signals/* · compatibility_views/* 미생성)
```
## 3. 산출물 검증 (YAML 의도 대비)
| 구간 | 실측 | YAML 의도 | 판정 |
|---|---|---|---|
| A0 | 15개 도메인 모두 slice 작성, 오류 0. 경고는 `PREFLIGHT_FILE_NEAR_LIMIT`(공유 우주 254,830자 > 90%) 1건. 도메인별 합계 최대 382,724자(X2), 한도 500,000자. value_facts `BOUND` | 봉인·반입·한도 검사 후 slice와 worker 입력 작성 | **정상** |
| C-05 봉인 | 증거·사건 파일 sha가 handoff `digest_guard`와 일치해 통과 | 바뀐 파일이면 `SEAL_FAILED` | **정상** |
| C-01 선별 | X2: `positive_refs` 10, `confidence` high, `selected_sources` 10. E-09: 5 / high / 5 | 이전에는 늘 0 / low | **의도대로 바뀜** |
| C-03 투영 | 공유 우주의 사건 100건 모두 `support_locators[{directness}]`. `obligation_direction`은 12건 | 오프라인 실측(12)과 같음 | **정상** |
| worker·C-07 | seed 15개 모두 `READY_WITH_REVIEW`. 후보 107(E-09 24, E-10 14, E-02 13, X1 12, X2 10 …, X3 0). 조항 id(`MTG.`·`:`) 인용 0. R0 BLOCK 0 | 조항 id를 인용하면 R0가 BLOCK | **정상** |
| R0 수용 | ledger 107, 완전 중복 0, 근접 중복 군집 20. 수용 보정 610건 | 스키마 밖 값은 보정하고 review를 남김 | **동작 정상, 품질 문제 있음(§4-2)** |
| R1 | 예외 13건(모두 `field_conflict`), 13건 모두 `KEEP_SEPARATE` | 예외가 있을 때만 판정 | **정상** |
| F0 | BO 107 = ledger 107(보존 등식 PASS). event 92, state 15. 금액 57건(value_id 결속, 강등 0). 게이트 7종 PASS | BO 스키마·참조·금액 결속 | **정상** |
| review handoff | `FINALIZED`. 1,145건 모두 `SOFT_WARNING`. `blocks_final_drafting` 0 | 하류(Stage 2)로 넘김 | **정상(양이 많음)** |
| S0 | 실패 | signal 묶음 작성 | **실패(§1)** |
## 4. 런타임·비용과 품질 문제
1. **런타임:** 총 8분 33초 중 worker 단계가 7분 46초다.
- worker는 동시 8개까지만 돌았다. 04:51:17에 8개가 시작했고, 나머지는 자리가 날 때마다 시작했다.
- 마지막 worker_13은 04:54:55에 시작해 245초가 걸렸다. 실제 임계 경로는 "가장 느린 호출"이 아니라 "동시 실행 한도 + 늦게 시작한 무거운 호출"이다.
- 비용은 $3.08이다(GPT-6.1 Sol 16회 $3.05, Flash-Lite 1회 $0.03). prewarm 캐시는 worker 15회 모두 113,723토큰 적중했다.
2. **R0 보정 610건: worker가 스키마 패턴을 지키지 않는다.**
- `party_refs` 280건: "강용원" 같은 한글 이름.
- `object_refs` 120건: "인테리어 자재 물품대금 채무를…" 같은 문장.
- `dependency_refs` 132건: `{"domain_id","source_refs"}` 객체.
- 15건씩: `completion_receipt`의 필수 5키 누락.
- 이 값은 모두 `worker_surplus`로 옮겨져 BO에 반영되지 않는다. 그래서 **BO 107건 모두 `core_field_base.Object`가 null**이다.
- `Performer`·`Subject`는 원래 R0가 투영하지 않는 칸이다(설계상 null).
- 원인은 프롬프트에 있다. `object_refs[]`는 "목적물 식별자 문자열", `party_roles[].party_refs`는 형식 안내 없이 적혀 있고, 스키마 패턴 `^[A-Za-z][A-Za-z0-9_.:/-]*$`를 말하지 않는다. 이번 개정 전부터 있던 문제다.
3. **review 항목이 많다.**
- 1,145건 = 수용 보정 610 + 도메인 review 325 + `EXTENSION_PAYLOAD_KEY_UNDECLARED` 107(BO 전부) + 금액·날짜 불확실 80 + 근접 중복 20 등.
- 모두 SOFT라 진행은 막지 않는다. 다만 하류 검토 부담이 크다.
## 5. 다음 조치
1. **(필수, S0 복구)** 로컬 `v.7/extension_research/Default_Agent/` 아래 두 파일을 서버 workspace 같은 경로에 올리고, 다시 실행해 S0를 확인한다. `.py` 사본도 manifest에 같은 해시로 있다.
- `signals/adapters/s3_domain_seed_adapter.txt`(`0372ac56…`)
- `signals/emitters/emitter_runtime.txt`
- 업로드 전에 manifest의 `signals/*`, `compiler/*` 항목 전체를 서버 사본과 대조하면 같은 실패가 반복되지 않는다. 이번 대조에서 내용이 다른 파일은 위 2건뿐이었다.
2. **(권장)** worker 프롬프트 `<OUTPUT_SCHEMA>`(prewarm·worker 두 블록, 바이트 동일 유지)에 두 가지를 명시한다.
- `party_refs`·`object_refs`는 영문 식별자 패턴만 쓴다. 이름과 문장은 `excerpt`·`reason`에 적는다.
- `dependency_refs`는 도메인 id 문자열만 쓴다.
- 그러면 `Object` 소실과 보정 review 약 530건이 줄어든다.
3. **(확인)** E-04·E-11·E-13·X2 overlay가 새로 채워진 `selected_sources`로 의도대로 작동하는지 seed 내용으로 점검한다(C-17).
**검증 범위:** 산출물의 법률적 정확성은 검증하지 않았다. 형식, 흐름, 계약 준수만 확인했다. 비용은 백엔드 `[USAGE]` 단가표 기준이다. 비교할 이전 Part 2 성공 회차가 같은 입력으로는 없어서, 개정 전후 품질 비교는 하지 않았다.
@@ -0,0 +1,90 @@
# Stage 1 Part 1 결과보고서 2 (2026-11-04 2차 실행)
- **대상:** `stage_1_part_1_v.8.yml`, sha256 `4cf8c5b7…`, task 29개.
- 로컬 저장은 10:32:54 KST, 업로드는 10:33:31 KST다.
- **직전 판(`_11_04_10_30am.yml`, `2450ea53…`)과의 차이는 두 줄뿐이다.**
- `Task_A0_domain_screener_01`: `llm_reasoning` medium → **low**
- `Task_V1_value_facts_*`: `llm_reasoning` medium → **low**
- **실행:** workspace `11월_1일_구성`, 세션 `83ad5831`, 2026-11-04 01:33:42 ~ 01:39:27 UTC.
- **근거:**
- `agent-backend` 로그 28,258행과 localdocs 산출물 75개. 모두 읽기 전용으로 확인했다.
- 비교 대상은 1차 실행(세션 `b077789a`, 결과보고서 `결과보고서_part_1.md`)이다.
## 1. 판정 — **성공** (`READY_WITH_REVIEW`)
| 기준 | 결과 |
|---|---|
| 백엔드 | task 199개 모두 `task_complete`, `execution_complete` 1회. 코드 task 106건 모두 `error_code=0`, iteration 2 재시도 0 |
| 일시 오류 1건 | `V1c_value_facts_capture_3`의 code-executor 호출 1차 시도가 `SSE stream ended without a response`로 끊겼다. 브리지가 자동 재시도해 11.1초 만에 성공했다. 결과에 영향은 없다 |
| Part 1 판정 | handoff **`READY_WITH_REVIEW`**, `stage2_auto_progression_allowed: true`, hard gate 0 |
| 검토 항목 | 25건(B1 6 · B2 7 · D0 12). 최종 작성 차단 2건은 D0의 `E08_TERM_RENEWAL_CONFLICT`와 `E13_CONSIDERATION_OR_GOOD_FAITH_CONFLICT`다(§3) |
| 봉인 정합 | screening sha `f6cfe2a2…`가 vocabulary 머리말, D0 manifest, handoff `activation_seal_crosscheck`에서 모두 같다. digest_guard 7키가 있다 |
| 잔재·경고 | 산출물 75개가 모두 정상 시작이고, `*_PENDING` 표식은 0이다. A0_02 `DIGEST_HEADER_ABSENT`(의도된 경고), B1r·B2r fan-out 0, Gemini 캐시 만료 후 재생성 13회는 모두 정상이다 |
## 2. IO 구조 (DAG)
```
[입력] client_meeting.md · Default_Agent/routing/activation_cue_digest.md · 증거 shard 30 · 스키마·사전
A 사슬 (임계 경로)
A0_01 (3.8 Flash, low, 44.5s) ─▶ A0c ─▶ routing/domain_screening_draft.json
└▶ A0_02 ─▶ routing/domain_screening.json ─▶ A0_03 ─▶ routing/candidate_profile_vocabulary.md
│ (둘 다 preflight)
▼
Task_A (GPT-6.1 Sol, medium, 278.2s) ─▶ Ac ─▶ client_goal.json ─────────────────────┐
B 사슬 │
shard_planner ─▶ B1_*×30 (3.8 Flash, medium) ─▶ B1c_* ─▶ evidence_indexed_parts/ ──┐ │
(ordinal 스트림) ─▶ B2_*×30 (medium) ─▶ B2c_* ─▶ evidence_event_candidate_parts/ │
B1_quality_gate ─▶ evidence_indexed.json B1r_planner ─▶ (B1r_*·B1rc_* 0건) │
B2_quality_gate ─▶ evidence_event_candidates.json + B12_exception_pack.json B2r_planner ─▶ (0건)
└▶ B12 (Flash-Lite, low) ─▶ B12c ─▶ B12_adjudication_decisions.json │
└▶ B12_audit_finalizer ─▶ B1/B2_failure.json (CLEARED) │
D0 (A0_03 + B 게이트) ─▶ routing/domain_activation_manifest.json ───────────────────┤
▼
T9 handoff_writer (Ac + D0) ─▶ quality_gates/stage1_part1_soft_gate_handoff.json + routing/party_aliases.json
V 사슬
V0 ─▶ V1_*×30 (3.8 Flash, low) ─▶ V1c_* ─▶ value_facts_parts/ ─▶ V2 ─▶ value_facts.json + quality_gates/value_facts_gate.json
└▶ V3 (V2 + client_goal) ─▶ value_facts_party_links.json
```
## 3. 산출물 검증 (YAML 의도 대비, 1차 실행과 비교)
| 구간 | 실측 (2차) | 1차 | 판정 |
|---|---|---|---|
| A0 | 후보 15(원천 단위 36), 검토 2(`E08_TERM_RENEWAL_CONFLICT`, `E13_CONSIDERATION_OR_GOOD_FAITH_CONFLICT`). vocabulary 절 15 | 후보 15, 검토 1(`UNROUTED`) | **정상.** low에서도 후보 집합 15개가 그대로다(E-10 포함). 미인용 원천 단위가 사라지고, 대신 도메인 내부 충돌 2건을 검토로 올렸다 |
| Task_A | 105,700자 → **107,663자**, 14키. 원고 2·피고 7·제3자 13, IC 5, 청구 후보 5. `defendant_qualification` **8** | 7 | **형식 정상.** 프로필 칸은 모두 후보 안이다. 다만 **오민한이 IC-01(물품대금)에도 피고로 추가됐다**. 근거 인용("강용원은 물품대금 채권을 실현하는 데 필요한 소의 제기를 희망한다")에 오민한의 이름이 없다. 1차는 "직접 문장이 없어 피고로 확정하지 않는다"고 적었다. Task_A 설정은 바꾸지 않았으므로 모델의 실행 간 편차로 본다. 변호사 확인이 필요하다 |
| B1·B2 | B1 items 30, suspect 6. B2 후보 100, exception 16 | 97 / 15 | **정상.** B 설정은 바뀌지 않았고 편차는 작다 |
| B12 | 판정 16건(SOFT 10 · DISMISS 3 · HARD 2 · ESCALATE 1) | 15건 | **정상** |
| D0 | active 13 + active_with_review 2(E-08·E-13) + supporting 1, 검토 12, **unrouted 0** | active 14, 검토 7, unrouted 1 | **정상.** E-08·E-13은 A0 검토를 받아 `active_with_review`가 됐다. E-12(B 증거 구성요소 `e12.opposing_record`로 활성)가 새로 생겼는데, 스크리닝 후보가 아니어서 Task_A에 프로필 칸이 없다 |
| T9·alias | handoff READY_WITH_REVIEW. canonical 22, alias 1, error 없음 | alias 2 | **정상** |
| V | gate **READY_WITH_REVIEW**: ok 28 · review 2(E-006, E-022) · failed 0, records **117**, rejected 3. V3 links 119(resolved 97) | ok 30, records 109, rejected 0 | **정상(경미한 하락).** 기록은 8건 늘었다. 그러나 E-006 `DURATION`, E-022 금액 없는 `PAYMENT_MADE` 같은 형식 오류 3건이 게이트에서 거부됐다. 잘림·파싱 실패는 0이다 |
## 4. 런타임과 비용
- **총 5분 44.7초**(1차 10분 37.9초 대비 **−46%**).
- **임계 경로:** A0_01 44.5s → A0c~A0_03 11s → **Task_A 278.2s(전체의 81%)** → T9·V3 10s.
- 다른 사슬은 먼저 끝났다. V 사슬은 2분 58초, B 사슬은 3분 58초(D0 4분 1초)에 끝났다.
| 구간 | 본문 출력 | 사고 토큰 | 평균 / 최대 | 1차 대비 |
|---|---:|---:|---|---|
| A0_01 (low) | 7,442 | **0** | 44.5s | 353.5s, 사고 51,440 |
| V1 ×30 (low) | 26,573 | **0** | 8s / 20s | 70s / 284s, 사고 293,319 |
| B1 ×30 (medium) | 52,291 | 136,506 | 41s / 122s | 비슷 |
| B2 ×30 (medium) | 94,837 | 138,576 | 49s / 108s | 비슷 |
| Task_A (medium) | completion 32,874 | 미기록 | 278.2s | 263.7s |
- B1·B2는 공유 캐시 크기(21,816 / 18,293)로 나눴다. B2 쪽이 늦게 끝나 1차 추정과 맞는다.
- **비용은 $2.36(92회)으로 1차 $3.66보다 −35%다.**
- 모델별: gemini-3.8-flash $1.93 · gpt-6.1-sol $0.42 · flash-lite $0.01.
- 남은 Gemini 사고 27.5만 토큰은 모두 B1·B2에서 나온다.
- **3.8 Flash의 `thinking_level=low`는 이번 실행에서 사고 토큰 0이었다.** 사실상 사고 없이 응답했다.
## 5. 평가와 남은 일
1. **A0 low는 이번 1회에서 목적 손상이 없었다.** 후보 15개 유지, 미인용 0, 도메인 충돌 검토 2건 추가로 오히려 보수적이다. 다만 평가서 기준(low 3회)에는 2회가 더 필요하다.
2. **V1 low는 속도·비용 이득이 크지만, 품질은 약간 떨어졌다.** review 2건과 rejected 3건이 생겼다. 금액 기록 누락은 없다(record 0 문서 7개는 1차의 8개 안에 포함된다). 재실행에서도 같은 수준이면 수용 가능하다.
3. **다음 병목은 Task_A(278초)다.** 추론 수준보다 출력량(약 10.8만 자)이 시간을 정한다.
4. **확인이 필요한 것:**
- 오민한 IC-01 피고 추가가 의도된 판단인지(상호 속용 영업양수인 책임 가능성 등). Task_A 판단이 실행마다 흔들리는 문제다.
- E-12 활성의 타당성.
5. **검증 범위:** 산출물의 법률적 정확성은 검증하지 않았다. 비용은 백엔드 `[USAGE]` 단가표 기준이다.
@@ -0,0 +1,73 @@
# Stage 1 Part 2 결과보고서 2 (2026-11-04 4차 실행)
- **대상:** `stage_1_part_2_v.8.yml`(`3a66272c…`, 5,769행). 개정전략서 4pm의 H-1~H-5가 적용되어 있고, 그전에 넣은 F-2·S-1·S-2도 함께 들어 있다. worker reasoning은 medium이다.
- **실행:** workspace `11월_1일_구성`, 세션 `5d47278e`, 2026-11-04 07:26:06 ~ 07:30:41 UTC(4분 35초).
- **근거(모두 읽기 전용):**
- `agent-backend` 로그: task 완료·오류 이벤트, 코드 task stdout, `[USAGE]`.
- localdocs 산출물: seed 15개, ledger, exception pack, R1 판정, `BO.json`, review handoff, compact, `signals/signal_manifest.json`.
## 1. 판정 — **성공** (BO `PASS`, signal `READY_WITH_REVIEW`)
| 기준 | 결과 |
|---|---|
| 백엔드 | task 37건 모두 `task_complete`. `task_error`·`task_retry` 0. `execution_complete` 1회 |
| 코드 task | A0 `READY` · load_fanout `PREPARED` · capture 15 · R0 `READY` · **F0 `PASS`(BO 78건)** · **S0 `READY_WITH_REVIEW`** |
| S0 | 정본 signal 거래 1건 기록(`S5TX-89d93dca8f879c30090d`). 파일 32종(manifest + 31). signal gate `PASS`, 오류 0 |
| 이전 실패 해소 | 2·3차 회차에서 멈췄던 F0와 S0가 이번에 처음 끝까지 통과했다 |
| 비용 | $1.96(GPT-6.1 Sol 16회 $1.94, Flash-Lite 1회 $0.02) |
## 2. IO 구조 (DAG)
```
[입력·Part 1] handoff(digest_guard 7키) · domain_screening(source_document_refs MTG.* 36)
· domain_activation_manifest · evidence_indexed · evidence_event_candidates · value_facts · client_meeting.md
A0 (코드 4.5s) ─ 봉인 대조 · 모듈 반입 · stage_a · slice 15 · 한도 검사(공유 우주 254,830자)
└▶ runtime/{domain_slices, compiled_prompts, worker_inputs}/<D> ×15 · runtime/shared/{source_universe.json, vocabulary.md}
│
prewarm (Sol 2.6s) ─▶ load_fanout (코드) ─▶ fanout/domain_fanout_plan.json (15)
▼ 동시 8개씩
worker_* ×15 (Sol medium, 9~154s) ─▶ capture_* ×15 ─▶ runtime/domain_seed_outputs/<D>.json
▼
R0 (코드 3.9s) ─▶ admitted_seeds/<D> ×15 · postb_seed_ledger.json(78)
└▶ quality_gates/stage1_part2_exception_pack.json (field_conflict 8)
▼
R1 (Flash-Lite 8.5s) ─▶ postb_adjudication_decisions.json (KEEP 6 · BLOCK 2)
▼
F0 (코드 3.5s) ─▶ BO.json (78) · postb_compiled_bundle_compact.json (human_review_count 2)
└▶ quality_gates/stage1_part2_review_handoff.json (FINALIZED, 451)
▼ S-2: handoff FINALIZED · bo_item_count 78 == BO 78 확인
S0 (코드 4.2s) ─▶ signals/signal_manifest.json + domain_signals/<D> ×15 · SG-02~13 · compatibility_views ×3
· downstream_read_sets(Part 3 L0 등)
```
## 3. 산출물 검증 (YAML 의도 대비)
| 구간 | 실측 | 의도 | 판정 |
|---|---|---|---|
| A0 | 15개 도메인 slice. 공유 우주 254,830자(경고 1건), 도메인별 합계 최대 382,724자. value_facts `BOUND` | 봉인·한도 검사 | **정상** |
| worker(H-3) | 후보 78건. 사건 id(`EVT-`) 인용 후보 **10건**(3차 2/81). `source_refs` 149개 중 EVT 26개. 요건 행 266개 중 `event_candidate` 25개 | 사건 후보에서 나온 후보는 EVT id를 함께 적는다 | **개선, 부분적**. 인용률은 13%다 |
| R0 수용 | 처분 80건(`completion_receipt` 필수 키 75, 스키마 밖 키 5). `repair_harvest` 0. 격리 0 | 보정·격리 기록 | **정상**. 참조 형식 개정 효과가 유지됐다 |
| R0 군집(H-4) | 근접 중복 군집 16개 = 사건 기준 1, 문서 기준 15. 구성원 39. exception 8건(모두 field_conflict) | 사건 id가 있으면 사건 단위 | **동작 정상**. 사건 id 인용이 적어 대부분 문서 군집이다 |
| R1(H-2) | **KEEP_SEPARATE 6, BLOCK_REVIEW 2**, blocked 2(일치) | 다른 행위는 KEEP, 같은 행위의 값 상충만 BLOCK | **정상**. BLOCK 2건은 같은 대상에 대한 상충이다: EX-FIELD-003 동일 담보부 차용금의 발생 시점(2023-01-06 vs 2024-01-05), EX-FIELD-004 시가 평가 기간·금액 |
| F0(H-1) | **PASS**. BO 78 = ledger 78(보존 등식). event 65, state 13. 금액 결속 42. `F0:human_review:EX-FIELD-003·004` 2건(HARD_WARNING, `human_judgment_required`). compact `human_review_count` 2 | BLOCK이어도 멈추지 않고 따로 보존 + 사람 판정 review | **정상** |
| review handoff | `FINALIZED`, `bo_item_count` 78. 451건(SOFT 449, HARD 2). 구성: 도메인 review 213, 수용 처분 80, 미선언 확장 키 78, 금액·날짜 57, 근접 중복 16, 폴백 5, 사람 판정 2 | 하류로 넘김 | **정상** |
| S0(S-1·S-2) | S-2 통과(FINALIZED · 78 = 78). signal gate PASS, 오류 0. E-08·E-13의 `MTG.*` conflict ref도 통과 | 스크리닝 단위를 출처 우주에 포함 | **정상**. S-1이 처음 실측으로 확인됐다 |
| S0 산출 | manifest `READY_WITH_REVIEW`. `active_domains` 13개(E-08·E-13 제외), `active_calculations` 9개(CE-01~04·07·08·10·11·13). 도메인 signal 15개, 호환 뷰 3개 | Part 3 입력 묶음 | **정상** |
## 4. 회차 비교와 남은 문제
| 지표 | 1차(high) | 2차(high, 참조 개정) | 3차(medium) | **4차(medium, H 적용)** |
|---|---:|---:|---:|---:|
| 결과 | BO PASS / S0 모듈 실패 | F0·S0 실패 | F0·S0 실패 | **전부 성공** |
| 후보·BO | 107 / 107 | 85 / — | 81 / — | **78 / 78** |
| R0 수용 처분 | 610 | 92 | 92 | **80** |
| R1 판정 | KEEP 13 | KEEP 9 + blocked 9(모순) | BLOCK 11 | **KEEP 6 · BLOCK 2** |
| 사건 id 인용 후보 | 7 / 107 | — | 2 / 81 | **10 / 78** |
| 런타임 · 비용 | 8분 33초 · $3.08 | 4분 16초 · $2.02 | 4분 36초 · $2.02 | **4분 35초 · $1.96** |
1. **후보 수가 계속 줄고 있다(107 → 78).** 가장 큰 감소는 E-09(24 → 6)다. 참조 형식 개정 이후 worker가 등기 행 단위 후보를 덜 낸다. 이 회차는 성공했으므로, 지금 바로 1차 BO(107건)와 사건 단위로 대조할 수 있다. 등기·처분 사건이 누락됐는지 확인하는 것이 다음 우선순위다.
2. **사건 id 인용률은 13%에 그친다.** 그래서 군집 16개 중 15개는 여전히 문서 기준이다. 필요하면 worker 규칙에 "사건 후보에서 읽은 요건 행이 있으면 그 후보의 `source_refs`에도 같은 EVT id를 넣는다"를 더해 볼 수 있다.
3. **BO `Object`는 78건 모두 null이다.** 당사자·목적물 id 체계가 없어서 생기는 알려진 한계다.
4. **Stage 2 확인:** 사람 판정 2건은 handoff의 `human_judgment_required`로만 전달된다. S2_00이 이 issue_type을 사용자에게 보여 주는지 확인해야 한다.
5. **검증 범위:** 형식, 흐름, 계약 준수만 보았다. BO와 signal의 법률적 타당성은 판단하지 않았다.
@@ -0,0 +1,91 @@
# Stage 1 Part 1 결과보고서 (2026-11-04 실행)
- **대상:** `stage_1_part_1_v.8.yml`, sha256 `2450ea53…`, task 29개.
- 로컬 저장은 09:46:39 KST, 업로드는 09:47:09 KST다. 시각이 맞아 이 파일이 실행된 것으로 본다(내용 대조는 하지 않음).
- **실행:** workspace `11월_1일_구성`, 세션 `b077789a`, 2026-11-04 00:47:25 ~ 00:58:03 UTC.
- **근거:**
- `agent-backend` 로그 28,130행(`[USAGE]`, `[BRIDGE]`, 코드 task stdout).
- localdocs `read_docs`로 읽은 산출물 75개.
- 모두 읽기 전용으로 확인했다. 비교 대상은 11-03 08:05 실행(세션 `2ef6f8fc`)이다.
## 1. 판정 — **성공** (`READY_WITH_REVIEW`)
| 기준 | 결과 |
|---|---|
| 백엔드 | task 199개 모두 `task_complete`, `execution_complete` 1회. 코드 task 106건 모두 `error_code=0`. 재시도(iteration 2) 0, `FAILED` 0 |
| Part 1 판정 | `quality_gates/stage1_part1_soft_gate_handoff.json`이 **`READY_WITH_REVIEW`**이고 `stage2_auto_progression_allowed: true`다. hard gate는 0이다 |
| 검토 항목 | 18건(B1 6 · B2 5 · D0 7). 최종 작성 차단 1건은 `UNROUTED_ISSUE_REVIEW`(`MTG.WISH.05.00`)로, 11-03과 같은 항목이다 |
| 봉인 정합 | screening sha `508242cf…`가 vocabulary 머리말, D0 manifest, handoff `activation_seal_crosscheck`에서 모두 같다. digest_guard 7키가 있다 |
| 지난 실행 잔재 | 확인한 산출물 75개가 모두 정상 JSON·MD로 시작한다. `*_PENDING` 표식은 남지 않았다 |
| 경고(정상) | A0_02 `DIGEST_HEADER_ABSENT` 2건은 의도된 경고다. B1r·B2r는 고장 part가 없어 fan-out 0이다. B12 캐시 생성 실패(866토큰 < 최소)는 영향이 없다 |
## 2. IO 구조 (DAG)
```
[입력] client_meeting.md · Default_Agent/routing/activation_cue_digest.md · 증거 shard 30 · 스키마·사전
A 사슬 (임계 경로)
A0_01 (LLM 3.8 Flash, medium) ─▶ A0c ─▶ routing/domain_screening_draft.json
└▶ A0_02 (코드 검증) ─▶ routing/domain_screening.json ─▶ A0_03 ─▶ routing/candidate_profile_vocabulary.md
└───────────────┬──────────────────────────────────────────────┘
▼
Task_A (LLM GPT-6.1 Sol, medium) ─▶ Ac ─▶ client_goal.json ────────────────┐
│
B 사슬 │
shard_planner ─▶ B1_*×30 ─▶ B1c_* ─▶ evidence_indexed_parts/E-0NN.json ─┐ │
(ordinal 스트림) ─▶ B2_*×30 ─▶ B2c_* ─▶ evidence_event_candidate_parts/ ┤
B1_quality_gate ─▶ evidence_indexed.json B1r_planner ─▶ (B1r_*·B1rc_* 0건) │
B2_quality_gate ─▶ evidence_event_candidates.json B2r_planner ─▶ (B2r_* 0건) │
└▶ (B2 게이트가 쓴 B12_exception_pack.json) ─▶ B12 (LLM Flash-Lite, low) ─▶ B12c ─▶ B12_adjudication_decisions.json
└▶ B12_audit_finalizer ─▶ B1/B2_failure.json(CLEARED) │
D0 (A0_03 + B 게이트) ─▶ routing/domain_activation_manifest.json ─────────┤
▼
T9 handoff_writer (Ac + D0) ─▶ quality_gates/stage1_part1_soft_gate_handoff.json
+ routing/party_aliases.json
V 사슬
V0 ─▶ V1_*×30 (LLM 3.8 Flash, medium) ─▶ V1c_* ─▶ value_facts_parts/ ─▶ V2 ─▶ value_facts.json
+ quality_gates/value_facts_gate.json
└▶ V3 (V2 + client_goal) ─▶ value_facts_party_links.json
```
## 3. 산출물 검증 (YAML 의도 대비)
| 구간 | 산출물(실측) | YAML 의도 | 판정 |
|---|---|---|---|
| A0 | screening `READY_WITH_REVIEW`: 후보 15, 원천 단위 36(인용 35, 미인용 1), 검토 1. vocabulary `READY`, 도메인 절 15 | fail-open 후보 도출, 근거 인용, 보존 등식, sha 봉인 | **정상.** 후보 15개가 11-03과 같다(E-10 포함). 검토는 5건에서 1건으로 줄었다 |
| Task_A·Ac | `client_goal.json` 105,700자, 최상위 14키, parties 원고 2·피고 7·제3자 13, issue cluster 5, 청구 후보 5, `defendant_qualification` 7 | 피고 자격 4키 기준, 스크리닝 후보 안에서만 도메인 프로필 칸 | **정상.** 피고 7명이 11-03과 같다. 프로필 칸 ID는 모두 후보 15개 안에 있다. IC-01에 E-01이 늘고, IC-04에서 E-09가 빠졌다 |
| B1 | parts 30 → `evidence_indexed.json` items 30. 게이트 PASS, suspect 6, 복구 0 | 30문서 전수 색인, 결정적 게이트 | **정상** |
| B2 | parts 30 → `evidence_event_candidates.json` items 30. 후보 97, dedup 0, exception 15 | 사건 후보, 채권 방향 | **정상.** 11-03(126)보다 후보가 23% 적다. 원인은 확인하지 않았다(§5) |
| B12 | 판정 15건(SOFT 10 · DISMISS 4 · ESCALATE 1). finalizer는 B1 SOFT_WARNING · B2 HARD_WARNING, review 11, hard 0 | exception이 있을 때만 판정 | **정상** |
| D0 | manifest `READY_WITH_REVIEW`: 도메인 26, active 14, supporting 1(EC-00), 검토 7, unrouted 1 | A0 + B 신호 합산, 자기검증 | **정상.** active가 10에서 14로 늘었다(E-03·E-08·E-10·E-13). D0 검토는 17건에서 7건으로 줄었다 |
| T9·alias | handoff `READY_WITH_REVIEW`. `party_aliases.json`은 canonical 22, alias 2, 후보 3, 승계 2, error 없음 | 게이트 실패 시 BLOCKED, 산출물 게이트 | **정상** |
| V | gate `READY`: 문서 30 모두 ok, records 109, rejected 0. V3 links 89(resolved 73 · unresolved 16) | 원문 인용 값 사실, 게이트 대조 | **개선.** 11-03에는 ok 26 · review 3 · failed 1, records 90이었다. `max_tokens` 조기 종료가 사라졌다 |
## 4. 런타임과 비용
- **총 10분 37.9초**(11-03 대비 −2분 12초)다.
- **임계 경로는 A 사슬이다.** A0_01 353.5s → 코드 10s → Task_A 263.7s → 코드 10s이고, 전체의 97%다.
- B 사슬은 4분 19초, V 사슬은 5분 24초에 끝나고 대기했다.
| 구간 | 호출 | 본문 출력 | 사고 토큰 | 평균 / 최대 시간 |
|---|---:|---:|---:|---|
| A0_01 | 1 | 6,390 | 51,440 | 347s |
| B1 (캐시 21,816) | 30 | 55,494 | 143,648 | 41s / 109s |
| B2 (캐시 18,293) | 30 | 92,642 | 131,525 | 45s / 107s |
| V1 | 30 | 22,846 | **293,319** | 70s / 284s |
| B12 | 1 | 3,285 | 0 | 8s |
| Task_A | 1 | completion 30,946 | 미기록 | 264s |
- B1·B2는 공유 캐시 크기로 나눴다. 어느 쪽이 B2인지는 출력량으로 추정했다.
- **비용은 $3.66(93회)으로, 11-03의 $1.61보다 2.3배다.**
- 모델별: gemini-3.8-flash $3.25 · gpt-6.1-sol $0.40 · flash-lite $0.01.
- 원인: 11-03 13:02 브리지 재배포로 `llm_reasoning`이 실제 `thinking_level`로 전달됐다. 그 결과 Gemini 사고 토큰이 62만 개가 됐고, 사고 토큰은 출력 단가로 청구된다.
- V1은 본문 2.3만 토큰에 사고 29만 토큰을 써, 사고량의 47%를 차지한다.
## 5. 남은 문제와 확인하지 못한 것
1. **V1 사고량이 과다하다.** 값을 옮겨 적는 추출에 medium 사고를 쓴다. 11-03 사용자 지정값은 low였지만 현재 YAML은 medium·`llm_token_limit: 65536`이다. 품질은 개선됐으므로, low로 바꾸면 ok 30이 유지되는지 비교한 뒤 정한다.
2. **A0_01이 런타임의 55%다.** `모델_조건변경_A0_A1_평가서.md`의 option 1(3.8 Flash low)을 비교 실행으로 확인한다.
3. **B2 후보가 126에서 97로 줄었다.** 추론 수준 변경(high에서 medium) 때문인지, 누락인지 중복 감소인지 확인하지 않았다. exception은 14에서 15로 비슷하다.
4. 산출물의 법률적 정확성(피고 자격, 활성 도메인 14개 타당성)은 검증하지 않았다. 형식과 흐름만 확인했다.
5. 비용은 백엔드 `[USAGE]` 단가표 기준이다. 공급자 청구서와 대조하지 않았다.
@@ -0,0 +1,97 @@
# Stage 1 Part 2 실패결과보고서 1 (2026-11-04 2차 실행)
- **대상:** `stage_1_part_2_v.8.yml`(`30ed8748…`, worker 참조 형식 개정판).
- **실행:** workspace `11월_1일_구성`, 세션 `4ff7d817`, 2026-11-04 05:53:51 ~ 05:58:07 UTC(4분 16초), 비용 $2.02.
- **근거(모두 읽기 전용):**
- `agent-backend` 로그(코드 task stdout, 에러, `[USAGE]`).
- localdocs 산출물: R1 판정, exception pack, ledger, review handoff, `BO.json`, source universe manifest, D0 manifest, Part 1 `routing/domain_screening.json`.
- S0 검사 코드 `Default_Agent/signals/compiler/signal_gate.py`.
## 1. 결론
| task | 결과 | 실패 원인(한 줄) | 해결안 |
|---|---|---|---|
| A0 ~ R1 | 성공 | — | — |
| **F0** | 2회 모두 `FAILED` | R1이 9건을 `KEEP_SEPARATE`로 판정하면서 같은 9건을 `blocked_review_items`에도 넣었다. F0는 이 목록이 비어 있지 않으면 무조건 멈춘다 | F0에서 판정과 모순되는 blocked 항목을 review로 낮춘다. R1 프롬프트에 "blocked에는 `BLOCK_REVIEW`로 판정한 것만 넣는다"를 넣는다 |
| **S0** | 2회 모두 `FAILED` | SG-01 출처 검사가 D0 manifest `conflict_refs`의 `MTG.*` 6개를 출처 우주에서 찾지 못했다 | S0 출처 우주에 Part 1 스크리닝 `source_document_refs`(`MTG.*` 정본 36개)를 더한다 |
| (부수) | — | F0가 실패했는데도 S0가 실행됐고, 지난 회차의 `BO.json`(107건)을 읽었다 | S0 앞에서 review handoff가 `FINALIZED`인지 확인한다 |
두 실패는 서로 독립이다. F0를 고쳐도 S0는 같은 이유로 멈춘다. 셋 모두 YAML만 고치면 되고, 모듈과 manifest는 재봉인하지 않아도 된다.
## 2. 실패 지점과 원인
### 2-1. F0 — `R1 returned BLOCK_REVIEW items: 인간 검토 필요`
- **실패 지점:** `Task_C_BO_F0_final_bo_compiler_gate_writer`, YAML 4693행 근처 `if blocked or block_decisions: _fail(...)`.
- 게이트 `r1_decision_presence`만 PASS하고 그 뒤 게이트는 실행되지 않았다. 5초 뒤 재시도해도 같은 입력이라 같은 결과가 나왔다.
- **R1 산출물(`postb_adjudication_decisions.json`)이 자기모순이다.**
- `canonical_decisions` 9건이 모두 `KEEP_SEPARATE`다. 근거 문장은 "preserve separately or route to review"다.
- 그런데 `blocked_review_items`에도 같은 9건이 들어 있다. 예: "Conflicting BehaviorTime values (2024-08-05 vs 2024-08-31); requires human review."
- F0는 canonical 판정이 무엇이든 `blocked_review_items`가 비어 있지 않으면 멈춘다.
- **예외 9건은 모두 `field_conflict`다.** 행위 시점(BehaviorTime)이 둘 이상이거나, 서로 다른 value_id의 금액이 함께 있는 경우다.
- 예: EX-FIELD-004는 2억 원(`E-006-VF-006`)과 3억 원(`E-006-VF-003`)이다.
- R1 프롬프트(4005행)는 금액 상충을 "KEEP_SEPARATE 또는 BLOCK_REVIEW"로 정하게 한다. KEEP_SEPARATE를 기본값으로 하라는 문장(4006행)도 있다. R1은 KEEP_SEPARATE를 골랐으므로 판정 자체는 규칙에 맞는다.
- **왜 이번에만 났나.**
- R1 프롬프트 4번 마지막 줄 "compact payload로 확정할 수 없으면 반드시 `blocked_review_items`에 넣는다"가 KEEP_SEPARATE와 동시에 적용될 여지를 남긴다.
- R1 모델은 Gemini 3.5 Flash-Lite, reasoning low다. 같은 프롬프트로 직전 회차(04:50Z 세션 `7f798164`)에서는 13건 모두 KEEP_SEPARATE만 냈고 blocked는 0이었다. 실행마다 흔들리는 해석의 문제다.
- **영향:** BO.json이 갱신되지 않았다. review handoff는 `PENDING_FINALIZE`(386건, `bo_item_count` 없음)로 남았다.
### 2-2. S0 — `S0_SIGNAL_GATE_FAILED: sg01_source_membership`
- **실패 지점:** `signal_gate.py` 91–96행. SG-01(D0 manifest)의 `domain_entries[]`마다 `positive_refs`·`negative_refs`·`conflict_refs`가 `all_refs`(S0 출처 우주) 안에 있어야 한다.
- **걸린 값**
- E-08 `conflict_refs`: `MTG.FACT.05.02`, `MTG.FACT.05.03`, `MTG.FACT.05.04`, `MTG.OPP.05.00`
- E-13 `conflict_refs`: `MTG.FACT.03.03`, `MTG.OPP.03.01`
- **원인: 조항 id 체계가 둘이다.**
- S0는 출처 우주를 `stage1_tmp/task_c_bo/source_universe_manifest.json`으로 만든다(YAML 5415–5441행). 그 안의 상담 조항 id는 stage_a 형식(`s01_consultation:1-가`)뿐이다.
- D0 manifest의 negative·conflict ref는 Part 1 스크리닝 형식 `MTG.<SEC>.NN.NN`이다. 일치성 보고서 C-07과 같은 뿌리다.
- **왜 이번에 처음 났나.**
- D0 entry에는 `positive_refs` 키가 없다(D0는 `primary_positive_refs`로 쓴다). 그래서 이 검사는 늘 빈 목록을 본다.
- 이전 회차까지는 `negative_refs`·`conflict_refs`도 비어 있었다.
- 11-04 Part 1 2차 실행(A0 low)에서 E-08·E-13이 `active_with_review`가 되며 conflict ref가 생겼다. 그래서 잠복해 있던 결함이 드러났다.
- 11-04 첫 Part 2 실행은 S0가 모듈 해시에서 먼저 멈춰 이 검사까지 가지 못했다.
- **정본 목록은 있다.** Part 1 `routing/domain_screening.json`의 `source_document_refs`(36개)가 `MTG.*` 단위의 정본이다. Part 1 프롬프트도 "SOURCE_UNITS 목록과 같은 집합"이라고 적는다. 걸린 6개는 모두 이 목록에 있다.
### 2-3. 부수 결함 — S0가 지난 회차 BO를 읽었다
- 백엔드는 부모 task가 실패해도 자식 task를 실행한다(11-02부터 알려진 동작). 그래서 F0 실패 뒤에도 S0가 돌았다.
- S0는 `BO.json`을 읽어 `bo_ids`를 만든다(5417행). 지금 workspace의 BO.json은 지난 회차 것이다(107건, 이번 ledger는 85건).
- 이번에는 SG-01에서 먼저 멈췄다. 그러나 S0 검사를 고치고 F0가 다시 실패하면, **옛 BO와 새 seed를 섞은 signal 묶음이 PASS로 기록될 수 있다.**
## 3. 해결 방안
| 순서 | 고칠 곳 | 내용 | 비고 |
|---|---|---|---|
| **F-1** | F0 코드(4693행 근처) | `blocked_review_items` 중 같은 `exception_id`에 `BLOCK_REVIEW`가 아닌 canonical·field 판정이 있는 항목은 실패로 세지 않는다. review handoff에 `HARD_WARNING`, `blocks_final_drafting: true`로 남긴다. 판정 자체가 `BLOCK_REVIEW`인 항목은 지금처럼 멈춘다 | 결정적. 모델 편차를 코드가 흡수한다 |
| **F-2** | R1 프롬프트 `<EXECUTION_SEQUENCE>` 4번 | "`blocked_review_items`에는 canonical 판정을 `BLOCK_REVIEW`로 정한 exception만 넣는다. KEEP_SEPARATE를 고른 exception은 넣지 않는다"를 추가한다 | F-1이 있으면 보조 수단이다 |
| **S-1** | S0 코드(5415–5441행) | Part 1 `routing/domain_screening.json`의 `source_document_refs`를 읽어 `all_source_refs`에만 더한다. `meeting_clause_ids`에는 넣지 않는다 | 검사는 그대로 엄격하다. 목록 밖 `MTG.*`는 여전히 실패한다 |
| **S-2** | S0 코드 시작부 | `quality_gates/stage1_part2_review_handoff.json`의 `status`가 `FINALIZED`가 아니거나 `bo_item_count`가 `len(BO.json)`과 다르면 `S0_UPSTREAM_F0_NOT_FINALIZED`로 멈춘다 | 옛 BO 혼입을 막는다 |
**택하지 않은 대안**
- **SG-01 adapter에서 `MTG.*` ref를 지우기:** 충돌 근거가 signal에서 사라진다.
- **D0가 stage_a 형식 id를 쓰게 하기:** Part 1 모듈과 YAML을 함께 바꿔야 한다. 조항 id 단일화는 별도 과제다.
- **R1 모델 상향:** 런타임과 비용은 늘지만 F0의 모순 처리 문제는 그대로 남는다.
**검증 방법(적용 후)**
1. 이번 회차의 R1 판정 파일로 F0를 오프라인 재생해 BO가 85건 작성되고, blocked 9건이 review로 남는지 확인한다.
2. D0 manifest와 screening으로 S0 universe를 만들어 SG-01 오류가 0인지 확인한다. screening 목록 밖 가짜 `MTG.*`를 넣은 사본으로는 실패하는지도 확인한다.
3. review handoff를 `PENDING_FINALIZE`로 둔 사본으로 S-2 정지를 확인한다.
## 4. 이번 회차의 다른 관찰
- **지난 프롬프트 개정(참조 형식 명시)은 효과가 있었다.**
| 지표 | 1차 → 2차 |
|---|---|
| R0 수용 처분 | 610 → **92** |
| `repair_harvest` | 532 → **0** |
| 남은 처분 | `completion_receipt` 필수 5키 × 15 = 75 · `UNKNOWN_VALUE_REVIEW_MISSING` 12 · 스키마 밖 키 5 |
| review handoff | 1,145 → 386(F0 전 기준) |
| 격리 | 0 |
- **런타임과 비용:** 8분 33초에서 4분 16초로, $3.08에서 $2.02로 줄었다. worker 설정(Sol, high)은 같고, 최장 호출이 268초에서 111초로 짧아졌다. 출력이 줄어든 결과로 보인다(추론 토큰은 로그에 없다).
- **확인 필요:** 후보가 107건에서 **85건**으로 줄었다.
- E-09 24 → 11, E-10 14 → 12, E-02 13 → 12, X1 12 → 12, X2 10 → 9.
- 프롬프트 변경으로 줄어든 것인지, 실행 간 편차인지는 이 회차만으로 가릴 수 없다.
- F0를 고친 뒤 재실행해 BO 내용(특히 E-09 등기·처분 사건)이 빠지지 않았는지 1차 BO와 비교해야 한다.
- **검증 범위:** 법률적 타당성은 보지 않았다. 해결안은 아직 적용하지 않았다.
@@ -0,0 +1,88 @@
# Stage 1 Part 2 실패결과보고서 2 (2026-11-04 3차 실행)
- **대상:** `stage_1_part_2_v.8.yml`(`2d69f426…`). worker reasoning은 medium이고, F-1·F-2·S-1·S-2가 적용된 판이다.
- **실행:** workspace `11월_1일_구성`, 세션 `167723e7`, 2026-11-04 06:38:56 ~ 06:43:32 UTC(4분 36초), 비용 $2.02.
- **근거(모두 읽기 전용):**
- `agent-backend` 로그(코드 task stdout, 에러, `[USAGE]`).
- localdocs 산출물: exception pack, R1 판정, ledger, review handoff, `BO.json`.
## 1. 결론
| task | 결과 | 원인 | 판정 |
|---|---|---|---|
| A0 ~ R1 | 성공 | — | 정상 |
| **F0** | 2회 모두 `FAILED` | R1이 예외 11건 **모두를 canonical `BLOCK_REVIEW`로 판정**했다. F-1 규칙상 "판정 자체가 BLOCK_REVIEW"이므로 멈췄다 | 코드는 **설계대로** 동작했다. **설계 전제가 틀렸다**(§2) |
| **S0** | 2회 모두 `FAILED` | `S0_UPSTREAM_F0_NOT_FINALIZED:status=PENDING_FINALIZE bo_item_count=None bo_json=107` | **S-2가 의도대로 막았다.** 지난 회차 BO(107건)를 쓰지 않았다. S-1은 이번에 검사까지 가지 못했다 |
- **지난 회차 결함은 고쳐졌다.** R1은 이번에 판정과 blocked 목록이 일치했다(11 = 11). F-2가 효과를 냈다.
- **남은 문제는 하나다.** R0가 "단일 값을 골라야 한다"며 R1에 올리는 근접 중복 예외가, 실제로는 서로 다른 행위를 묶은 것이다. 그래서 R1이 BLOCK을 고르면 회차 전체가 멈춘다.
- F0만 고치면 S0는 S-2를 통과하고 이번 판의 S-1까지 검증된다.
## 2. 실패 원인 — 근접 중복 예외의 전제 오류
### 2-1. R0가 예외를 만드는 방식(YAML 3776–3825행)
1. R0는 증거 번호 집합, 사건 id 집합, `BOType`, `ActionType`이 같은 seed를 **근접 중복 군집**으로 묶는다.
2. 군집 후보는 이미 결정적으로 **따로 보존(KEEP_SEPARATE)** 되고, `near_duplicate_kept_separate` review가 붙는다.
3. 군집 안에서 `BehaviorTime`이나 `amount`가 서로 다르면 주석 "writer가 단일 값을 고를 수 없으므로"에 따라 `field_conflict` 예외로 R1에 올린다. 허용 판정에는 `BLOCK_REVIEW`가 있다.
### 2-2. 전제가 틀린 이유
- **따로 보존한 후보는 각자 자기 값을 갖는다.** F0가 단일 값을 고를 일이 없다. 1차 회차에서 13건을 모두 `KEEP_SEPARATE`로 처리했을 때 F0가 BO 107건을 문제없이 썼다.
- **군집 자체가 너무 넓다.** ledger seed 81건 중 사건 id(`source_event_candidate_ids`)를 가진 것은 **2건**뿐이다. 그래서 실제 묶는 기준은 "같은 증거 문서 + 같은 BO 유형 + 같은 행위 유형"이 된다.
- **이번 예외 11건은 모두 서로 다른 행위다.**
| 예외 | 묶인 후보 | 실제 관계 |
|---|---|---|
| EX-FIELD-004 | E-02:002 · E-02:003 · E-13:001 · … | 첫 번째 대여(2022-12-17)와 추가 대여(2023-03-17) |
| EX-FIELD-005 | E-02:007 · E-02:008 | 공사 계약금(2021-05-01, 3억)과 중도금(2021-08-30, 4억) |
| EX-FIELD-008 | E-09:002~005 · E-10:004·008 | 성수동 대지의 상속 지분등기, 증여, 경매매각 이전 등 등기부의 서로 다른 등기 6건 |
| EX-FIELD-010 | E-10:005~007 | 경매개시결정(2024-07-21)과 매각 이전·말소(2024-10-05) |
| EX-FIELD-001 | E-01:001 · E-01:003 | 명의신탁 확인(4,000만 원)과 예비적 상계 주장(5,000만 원) |
- **R1의 판단은 규칙상 틀리지 않았다.** R1 규칙(4010–4011행)은 BehaviorTime의 우열을 가릴 수 없거나 금액이 서로 다른 정본이면 "KEEP_SEPARATE 또는 BLOCK_REVIEW"를 고르게 한다. 같은 프롬프트로 1차 회차는 13건 모두 KEEP, 이번 회차는 11건 모두 BLOCK을 골랐다. **모델 선택에 따라 회차 전체의 성패가 갈리는 구조**가 원인이다.
### 2-3. 실행 경과
| 회차 | worker | 후보 | R1 판정 | F0 |
|---|---|---|---|---|
| 1차(`7f798164`) | high | 107 | KEEP 13 / blocked 0 | PASS |
| 2차(`4ff7d817`) | high | 85 | KEEP 9 / blocked 9(모순) | FAILED |
| 3차(`167723e7`, 이번) | **medium** | 81 | **BLOCK 11** / blocked 11 | FAILED(설계대로) |
- 이번 회차 worker 최장 호출은 130초였다(2차 111초, 1차 268초).
- 후보 수 감소(107 → 85 → 81)는 이번 실패와 별개다. §5에서 따로 다룬다.
## 3. 해결 방안
| 순서 | 고칠 곳 | 내용 | 이유 |
|---|---|---|---|
| **G-1(권장)** | F0 코드, F-1 바로 아래 | `exception_type == "field_conflict"`인 예외의 canonical `BLOCK_REVIEW`는 **KEEP_SEPARATE로 적용**하고, `F0:r1_blocked:*` HARD_WARNING review로 남긴다. link·semantic 등 다른 유형의 BLOCK_REVIEW는 지금처럼 멈춘다 | 근접 중복 후보는 R0가 이미 따로 보존한다. field_conflict에서 BLOCK과 KEEP의 실제 차이는 "검토 표시"뿐이다. 결정적이라 모델 편차와 무관하다 |
| **G-2(보조)** | R1 프롬프트 `<ADJUDICATION_LEGAL_STANDARDS>` | "field_conflict 군집의 후보가 서로 다른 행위(날짜·금액·대상이 다름)를 기술하면 KEEP_SEPARATE다. BLOCK_REVIEW는 같은 행위를 두 후보가 다른 값으로 적었을 때만 쓴다"를 추가한다 | R1 판정을 실제 의미에 맞춘다. G-1이 있으면 실패에는 영향이 없다 |
| **G-3(정정)** | R0 주석(3804–3805행) | "writer가 단일 값을 고를 수 없으므로"를 "같은 행위의 값 상충일 수 있어 R1이 병합 여부를 본다"로 고친다 | 전제 오류를 바로잡는다. 동작은 바뀌지 않는다 |
**F-1과의 관계.** 실패결과보고서 1의 F-1은 "판정 자체가 BLOCK_REVIEW이면 멈춘다"였다. G-1은 그 원칙을 field_conflict 유형에서만 완화한다. Stage 1은 법률효과를 확정하지 않고 두 값을 모두 보존한 채 Stage 2로 넘기는 것이 원칙이다(R1 프롬프트 `<ADJUDICATION_LEGAL_STANDARDS>` 첫 항). 그래서 따로 보존과 검토 표시로 충분하다.
**택하지 않은 대안**
- **R0가 field_conflict를 pack에 올리지 않기:** R1이 정말 같은 행위를 MERGE할 기회가 사라진다. 지금까지 MERGE는 0건이지만 기능 자체를 없애는 것은 범위 밖이다.
- **R1 모델 상향:** KEEP와 BLOCK 모두 규칙상 허용되므로, 모델을 바꿔도 BLOCK이 다시 나올 수 있다.
- **근접 중복 기준 강화**(BehaviorTime을 키에 넣거나 worker가 사건 id를 인용하게 하기): 군집 과대 묶음의 근본 해결이지만 R0와 worker 계약을 함께 바꿔야 한다. 별도 과제로 남긴다.
**검증 방법(적용 후)**
1. 이번 회차의 R1 판정 파일(BLOCK 11)로 F0를 재생해 BO 81건이 써지고 `F0:r1_blocked:*` review가 11건 남는지 확인한다.
2. link 유형 BLOCK_REVIEW를 넣은 사본으로는 여전히 멈추는지 확인한다.
3. 재실행해 S0가 S-2를 통과하고, S-1로 SG-01 오류가 0인지 확인한다.
## 4. 이번 회차에서 확인된 것
- **F-2:** R1 판정과 blocked 목록이 일치했다(모순 0).
- **F-1:** 판정 자체가 BLOCK인 11건에서 멈췄다(설계대로).
- **S-2:** F0 실패 뒤 S0가 옛 BO(107)를 쓰지 않고 `S0_UPSTREAM_F0_NOT_FINALIZED`로 멈췄다.
- **S-1:** 이번 회차는 S-2에서 멈춰 검사까지 가지 못했다(미검증).
## 5. 별도 확인이 필요한 것
- **후보 수 감소:** 107(high, 개정 전) → 85(high, 참조 형식 개정 후) → 81(medium). 감소의 대부분은 참조 형식 개정 직후에 나타났다(E-09 24 → 11 → 10).
- worker가 형식 규칙을 지키려고 후보를 덜 내는지, 실행 간 편차인지 아직 모른다.
- F0를 고친 뒤 BO 내용을 1차 BO(107건)와 사건 단위로 비교해야 한다.
- **군집 과대 묶음:** worker seed 대부분에 사건 id가 없어 근접 중복이 "같은 문서" 수준으로 잡힌다. near_duplicate review 18건과 예외 11건이 여기서 나온다.
@@ -0,0 +1,91 @@
# Stage 1 Part 3 실행결과보고서 1 (2026-11-05, L1 JEV 추천기 첫 실행)
- **대상:** `stage_1_part_3_v.8.yml`(`057ff1ee…`, 2,155행). L1 후보 유형 추천기(JEV)를 처음 넣은 판이다. 근거 전략서는 `개정전략서_part_3_v2_with_part_1_2.md`이고, 그림자 실행 설정(`SHADOW_RUN=True`)이다.
- **실행:** workspace `11월_1일_구성`, 세션 `67b1e054`, 2026-11-05 02:14:32 ~ 02:14:57 UTC(**25초**).
- **입력:** Part 2 4차 실행 산출. 신호 거래 `S5TX-89d93dca8f879c30090d`, BO 78건(`BO.json` sha `654529b4…`).
- **근거(모두 읽기 전용):**
- `agent-backend` 로그: SSE 이벤트, `[TASK:*]`, 코드 task stdout, `JEV call`.
- localdocs 산출물: L1 영수증, 요청 파일, handoff, `legal_effect_structures.json`, L0 영수증.
- **실행 판 확인:** 로그의 신설 task 4종 이름과 `JEV call model=jev-1.14.0`이 개정본과 일치한다.
## 1. 판정 — **성공**
| 기준 | 결과 |
|---|---|
| 백엔드 | `task_complete` 38건 = L0 1 + planner 1 + recommender 17 + capture 17 + apply 1 + L2 1. `task_error`·`task_retry`·`stage_error`·Traceback 0건. `stage_complete` 1, `execution_complete` 1 |
| L0 | `READY_WITH_REVIEW`. 구조 50, Θ 34, BO 부착 63 / 미부착 15, route 부착 66 / 미부착 18. errors·warnings 없음 |
| L1 planner | `PLANNED`. 후보 13, 쌍 17. 요청 파일은 `planned:true`, `handoff_sha256` `7605ddc9…` |
| L1 recommender | JEV 17회 호출, 모두 응답했다. 모델 `jev-1.14.0`, 입력 토큰 합 **8,375**(약 $0.00035, 출력 무료) |
| L1 capture | 17건 모두 `ANSWERED`(`FAILED` 0) |
| L1 apply | `APPLIED`. 결론은 13건 모두 `UNDECIDED`(그림자 실행). 번들·handoff 재기록 없음(`bundle_rewritten:false`, `handoff_rewritten:false`) |
| L2 | `READY_WITH_REVIEW`. 보존 등식 세 개 모두 통과(선언 50, route 66+18=84, BO 63+15=78). `review_queue` 2종 |
- **그림자 실행 의도대로 동작했다.** L1이 판정 점수만 영수증에 남겼고, L2 입력(번들·handoff)은 L0 산출 그대로다.
- 그래서 최종 `legal_effect_structures.json`은 L1 도입 전과 같은 결과다. 미부착 BO 15건과 `PART3_BO_UNATTACHED` HARD 15건이 그대로 있다.
## 2. IO 구조 (DAG, 실측 시각)
```
[입력·Part 2] signals/* (S5TX-89d93dca…) · BO.json(78) · Default_Agent 자산
L0 (코드 6.1s, 02:14:32→38) ─▶ stage1_tmp/task_le/structure_seed_bundle.json
quality_gates/stage1_part3_review_handoff.json (OPEN, 33)
validation_assets/routing/part3_receipt.json
└▶ L1 planner (코드 3.1s) ─▶ stage1_tmp/task_le/recommender_requests.json (후보 13, 쌍 17)
│ dynamic_fanout 17
├▶ recommender_0..16 (jev, 02:14:42 동시 발사) ─▶ capture_{same_ordinal} (6.4~8.7s)
│ └▶ stage1_tmp/task_le/recommender_answers/pair_0000..0016.json
└▶ (planner→apply 직접 간선)
L1 apply (코드 3.3s; "All 17 instances … completed → aggregate set" 뒤 시작)
─▶ validation_assets/routing/part3_recommender_receipt.json (번들·handoff 미기록)
L2 (코드 3.4s, 02:14:54→57) ─▶ legal_effect_structures.json (READY_WITH_REVIEW) · handoff FINALIZED
```
## 3. 산출물 검증 (YAML 의도 대비)
| 구간 | 실측 | 의도 | 판정 |
|---|---|---|---|
| 후보 조건(§2.3) | 후보 13개. 도메인별로 E-02 5, X1 6, E-15 1, E-12 1. 후보별 미부착 BO 항목 수의 합 15 = 미부착 BO 15 | 미부착 BO를 만든 Θ 밖 유형만 후보로 삼는다 | **정상**. 미부착 15건이 모두 후보에 걸렸다 |
| 포괄 유형 제외 | 쌍 17개 중 `general_legal_effect` 대상 0. E-02는 `money_claim`, X1·E-15는 `succession_notice_lien_asset_defense`, E-12는 선언 유형 5개 전부 | T에서 제외한다 | **정상** |
| `state` | 영문 식별자만. 호출당 입력 약 490토큰 | 사건 서술을 외부로 보내지 않는다 | **정상** |
| JEV 응답 형식 | 17건 모두 `answers.relation`에 확률 3키가 있고 capture가 그대로 저장했다 | 유효 답 검사 통과 | **정상**. 무효·누락 답 0 |
| apply 판정 | `UNDECIDED` 13. `PART3_RECOMMENDER_ANSWER_MISSING` 항목 0이라 handoff가 바뀌지 않았다 | 그림자 실행에서는 수용·승격 비활성 | **정상** |
| L2 | 보존 등식 통과. `review_queue`는 `PART3_BO_UNATTACHED` HARD 15, `UNREGISTERED_EFFECT_TYPE_REVIEW` HARD 18. handoff `FINALIZED` | L1이 L2 입력을 바꾸지 않았으면 L0 기준 결과가 나온다 | **정상** |
## 4. 판정 점수 (영수증 `part3_recommender_receipt.json`, 정규화 확률)
| 도메인 | 후보 → 선언 유형 | independent | part_of | wording | attach_score |
|---|---|---:|---:|---:|---:|
| E-02 | partial_payment → money_claim | 0.29 | **0.71** | 0.00 | **0.71** |
| E-02 | demand_notice → money_claim | 0.62 | 0.36 | 0.02 | 0.38 |
| E-02 | debt_acknowledgement → money_claim | 0.67 | 0.32 | 0.01 | 0.33 |
| E-02 | due_date_modification → money_claim | 0.67 | 0.33 | 0.00 | 0.33 |
| E-02 | guarantor_procurement_promise → money_claim | 0.75 | 0.24 | 0.01 | 0.25 |
| E-15 | inheritance_succession_status → succession_notice_lien_asset_defense | 0.69 | 0.30 | 0.01 | 0.31 |
| E-12 | sole_ownership_assertion → (선언 유형 5개) | 0.68~0.91 | 0.09~0.30 | 0.00~0.04 | 0.09~0.32 |
| X1 | *_notice_lifecycle 6종 → succession_notice_lien_asset_defense | 0.77~0.95 | 0.05~0.22 | 0.00~0.01 | 0.05~0.23 |
**시작 임계값(0.80/0.20/0.80)을 적용했다면** — 영수증 점수로 다시 계산한 값이다.
- **수용: 0건.** 최고 점수는 `partial_payment`의 0.71로 `accept_min` 0.80에 못 미친다.
- **승격 제안: 5건.** X1의 `contract_change_request`·`contract_rescission`·`lease_termination`·`oral_demand`·`registry_cancellation_demand` notice_lifecycle이다(independent ≥ 0.80).
- **무결정: 8건.**
- 결국 이 회차 데이터로는 시작 임계값에서도 **붙는 BO가 0건**이다. 전략서 §8이 예상한 대로 X1·E-15는 승격 제안이나 무결정으로 기운다.
## 5. 프로브(P-1~P-4) 결과
| 프로브 | 결과 |
|---|---|
| P-1 jev wildcard·`state` 전달·키 | **확인.** 다음이 모두 동작했다.<br>- `Created JEV task: Task_C_LE_L1_recommender_*`로 wildcard 확장.<br>- `{{item.state_json}}`(JSON 문자열) 전달. 응답이 식별자에 맞게 갈렸고, 호출당 약 490토큰.<br>- `retry`·`description`·`provider: jev`가 스테이지 `llm_provider: openai`와 공존.<br>- 서버 `JEV_API_KEY` 유효.<br>`{{item.state}}` 객체 치환은 시험하지 않았다. |
| P-2 실패한 jev 인스턴스 뒤 하류 진행 | **미확인.** 실패한 인스턴스가 0건이었다. |
| P-3 장벽 | **절반 확인.** 비어 있지 않은 fan-out에서 apply는 planner와 `all capture_*`(17개)가 모두 끝난 뒤 시작했다(`aggregate set` → `dependencies satisfied`). 빈 fan-out에서 장벽이 풀리는지는 미확인이다. |
| P-4 capture의 `{{prev}}` 형태 | **확인.** 17개 capture 모두 같은 ordinal 인스턴스의 응답에서 `answers.relation`을 꺼냈다. apply의 prev 문맥에 planner와 capture 17개가 모두 실렸다(`re-created with rendered prev context`). capture를 없앨지는 별도 결정이다. |
## 6. 남은 문제와 권고
1. **JEV가 `independent_effect` 쪽으로 강하게 기운다.** 17쌍 중 16쌍에서 independent가 최댓값이었다.
- 원인 후보 1: `state`가 식별자뿐이라 정보가 적다(전략서 §8 위험 3).
- 원인 후보 2: 선택지가 셋뿐이어서 "무관"인 쌍(예: E-12 `sole_ownership_assertion` → `boundary_determination`)도 independent로 몰린다.
- 그래서 지금 설계로는 P3-02(미부착 15건)가 거의 줄지 않는다.
- 보정 단계에서 할 일: (a) 15건에 사람이 라벨을 붙여 `partial_payment`→`money_claim`처럼 붙어야 할 쌍을 확정하고 `accept_min`을 다시 정한다(전략서는 0.5 근처까지 허용, 최댓값 조건은 유지). (b) 질문이나 선택지 설명을 고칠지 검토한다. (c) 레지스트리 승격 후보 5건(X1 notice_lifecycle)을 법률 검토한다.
2. **P-2와 빈 fan-out 장벽(P-3 절반)은 아직 실측하지 않았다.** 작은 프로브로 확인하기를 권한다. 0건 fan-out 1회, 그리고 잘못된 `state`를 1건 넣은 회차를 돌린다.
3. **`SHADOW_RUN`은 그대로 둔다.** 보정 전에 끄면 시작 임계값에서 승격 제안 5건이 handoff에 SOFT 항목으로 추가된다(BO 부착은 0건).
4. **검증 범위:** 형식, 흐름, 계약 준수만 보았다. JEV 판정이 법률적으로 맞는지는 판단하지 않았다.
@@ -0,0 +1,126 @@
# Stage 1 Part 3 실행결과보고서 2 (2026-11-05, L1 glossary 첫 실행)
- **대상:** `stage_1_part_3_v.8.yml`(`284f4417…`, 2,513행).
- L1 앞에 `Task_C_LE_L1_glossary`(Gemini 3.8 Flash, 사고 수준 low)를 넣었다.
- planner는 정의와 BO 문맥을 JEV state에 싣는다.
- JEV 지시문은 "Use only the information given in state"로 바꿨다.
- 그림자 실행 설정(`SHADOW_RUN=True`)이다.
- **실행:** workspace `11월_1일_구성`, 세션 `781fad3b`, 2026-11-05 05:06:19 ~ 05:07:13 UTC(**54초**).
- **입력:** 1차 회차(세션 `67b1e054`)와 같은 Part 2 4차 산출이다. BO 78건, L0 결과(구조 50, BO 63/15)도 같다.
- **근거(모두 읽기 전용):**
- `agent-backend` 로그: SSE 이벤트, `[TASK:*]`, `[BRIDGE]`, `[USAGE]`.
- localdocs 산출물: `type_glossary.json`, 요청 파일, L1 영수증, handoff, `legal_effect_structures.json`, L0 영수증.
- 1차 회차의 쌍별 확률은 같은 로그 구간(세션 `67b1e054`)의 capture 출력에서 뽑았다.
## 1. 판정 — **실행은 성공, 의도한 효과는 나오지 않음**
| 기준 | 결과 |
|---|---|
| 백엔드 | `task_complete` 39건 = L0 1 + glossary 1 + planner 1 + recommender 17 + capture 17 + apply 1 + L2 1. `task_error`·`task_retry`·Traceback 0건. `stage_complete` 1, `execution_complete` 1 |
| glossary | Gemini 1회 31.9초. prompt 15,084, output 3,479, thoughts 0 토큰. **$0.0244** |
| planner | `PLANNED`. 후보 13, 쌍 17(1차와 같다). glossary `OK`: 요청 48 = 수용 48, 버린 항목 0, 조문 버림 0, kind 정정 0, 정의 없이 보낸 유형 0. BO 문맥 `OK` |
| JEV | 17회, `jev-1.14.0`. 입력 토큰 합 **11,243**(1차 8,375, 호출당 약 660). 모두 응답했다 |
| apply | `APPLIED`. 13건 모두 `UNDECIDED`(그림자 실행). 번들·handoff 재기록 없음. 정의 누락이 없어 `PART3_GLOSSARY_MISSING`도 없음 |
| L2 | `READY_WITH_REVIEW`. 보존 등식 셋 통과(선언 50, route 66+18=84, BO 63+15=78). review_queue는 `PART3_BO_UNATTACHED` HARD 15와 `UNREGISTERED_EFFECT_TYPE_REVIEW` HARD 18로 1차와 같다 |
- **실행 면에서는 개정이 의도대로 돌았다.** 새 task가 정의표를 계약 형식대로 냈고, 검증을 모두 통과했으며, 정의가 17쌍 state에 실렸다. 그림자 실행이라 L2 결과는 1차와 같다.
- **효과 면에서는 목적과 반대로 갔다.** JEV가 independent_effect 쪽으로 더 기울었다(§4). 미부착 15건을 줄이는 데는 이번 개정이 도움이 되지 않았다.
## 2. IO 구조 (DAG, 실측)
```
L0 (코드) ─▶ structure_seed_bundle.json · review handoff(OPEN, 33) · part3_receipt.json
├▶ glossary (Gemini 3.8 Flash low, 05:06:23→05:06:55; 번들 1개 preflight inline, 도구 미노출)
│ └─ 응답 봉투 ─▶ planner prev
└▶ planner (코드 3.2s; prev = [glossary, L0]) ─▶ type_glossary.json(48) · recommender_requests.json(13/17)
│ dynamic_fanout 17
├▶ recommender_0..16 (jev) ─▶ capture_{same_ordinal} ─▶ recommender_answers/pair_0000..0016.json
└▶ apply (코드 3.2s; "All 17 instances … aggregate set" 뒤) ─▶ part3_recommender_receipt.json
L2 (코드 3.4s) ─▶ legal_effect_structures.json (READY_WITH_REVIEW) · handoff FINALIZED
```
- 로그에서 확인한 간선:
- glossary는 L0를 기다렸다.
- planner는 `deps={'Task_C_LE_L1_glossary', 'Task_C_LE_L0_structure_seed_reducer'}`를 기다린 뒤 `rendered prev context: ['Task_C_LE_L1_glossary', 'Task_C_LE_L0_structure_seed_reducer']`로 다시 만들어졌다.
- planner의 `timeout`은 300으로 반영됐다.
- preflight는 백엔드가 "No-tools preflight: all 1 file(s) are shared → inlined into prompt prefix only"로 처리했다. 첫 iteration의 토큰은 12,007이었다.
## 3. glossary 산출 (미검증 LLM 초안)
| 항목 | 값 |
|---|---|
| 대상 | 선언 33 + 후보 15 = 48 |
| 정의 길이 | 최대 68자(상한 80) |
| 조문 수 | 1개 14건, 2개 34건 |
| sha256 | `3cb6348f…` (영수증 `glossary.glossary_sha256`) |
예시. 조문은 사람이 대조하지 않았으므로 맞는지 판단하지 않았다.
| type_id | definition_ko | statutes |
|---|---|---|
| money_claim (선언) | 일정한 금전의 지급을 목적으로 채권자가 채무자에게 청구하는 권리이다. | 민법 제376조, 제390조 |
| partial_payment (후보) | 채무자가 부담하는 채무의 일부를 변제함으로써 해당 범위에서 채무를 소멸시키고 채무를 승인하는 효력이다. | 민법 제460조, 제168조 제3호 |
| demand_notice (후보) | 채권자가 채무자에게 채무의 이행을 촉구하는 최고로서 이행지체 및 시효중단의 효력을 발생시키는 통지이다. | 민법 제174조, 제387조 제2항 |
| debt_acknowledgement (후보) | 소멸시효의 이익을 받을 채무자가 시효 완성 전에 채권자에 대해 채무의 존재를 승인하는 관념의 통지이다. | 민법 제168조 제3호 |
| succession_notice_lien_asset_defense (선언) | 승계·통지 사실의 흠결이나 유치권 성립 등을 이유로 채무이행 또는 인도 청구를 거절하는 항변권이다. | 민법 제320조, 제450조 |
## 4. JEV 판정 비교 (같은 입력, 1차 → 2차, 정규화 확률)
| 도메인 | 후보 → 선언 유형 | independent 1차→2차 | part_of 1차→2차 | wording 1차→2차 |
|---|---|---|---|---|
| E-02 | partial_payment → money_claim | 0.29 → **0.68** | **0.71** → 0.32 | 0.00 → 0.00 |
| E-02 | demand_notice → money_claim | 0.62 → 0.85 | 0.36 → 0.15 | 0.02 → 0.00 |
| E-02 | debt_acknowledgement → money_claim | 0.67 → 0.85 | 0.32 → 0.15 | 0.01 → 0.00 |
| E-02 | due_date_modification → money_claim | 0.67 → 0.89 | 0.33 → 0.11 | 0.00 → 0.00 |
| E-02 | guarantor_procurement_promise → money_claim | 0.75 → 0.88 | 0.24 → 0.12 | 0.01 → 0.00 |
| E-15 | inheritance_succession_status → succession_notice_lien_asset_defense | 0.69 → 0.95 | 0.30 → 0.05 | 0.01 → 0.00 |
| E-12 | sole_ownership_assertion → 선언 유형 5개 | 0.68~0.91 → 0.94~1.00 | 0.09~0.30 → 0.00~0.05 | 0.00~0.04 → 0.00~0.01 |
| X1 | *_notice_lifecycle 6종 → succession_notice_lien_asset_defense | 0.77~0.95 → 0.98~1.00 | 0.05~0.22 → 0.00~0.02 | 0.00~0.01 → 0.00 |
- 쌍은 `pair_id` 앞부분 `d|k|T`로 맞췄다. 정의가 들어가 state sha가 바뀌었으므로 sha 부분은 회차마다 다르다.
- **17쌍 모두에서 independent가 올랐다.**
- 1차에서 유일하게 part_of가 최댓값이던 `partial_payment → money_claim`도 independent 0.68로 뒤집혔다.
- 신뢰도도 높아졌다. 1.00이 6쌍이다.
- **시작 임계값(0.80/0.20/0.80)으로 다시 계산하면:**
- 수용 0건.
- 승격 제안 12건: E-02 4건, E-12 1건, E-15 1건, X1 6건. 1차는 5건이었다.
- 무결정 1건: `partial_payment`, attach 0.32.
- 결국 이 설정을 켜면 미부착 BO는 줄지 않고, 승격 제안만 늘어난다.
### 원인 분석
이번 회차는 정의 추가와 지시문 변경을 함께 바꿨으므로, 아래는 실측에서 끌어낸 가설이다.
1. **정의가 차이를 드러냈다.**
- 선언 유형 정의는 상위 권리를 추상적으로 정의한다. 예: `money_claim` = "청구하는 권리".
- 후보 정의는 고유한 효과와 조문을 적는다. 예: 시효중단, 채무승인, `민법 제168조 제3호`.
- 그 결과 criteria의 independent_effect 설명("선언 유형이 다루지 않는 고유한 결과·요건·구제")에 그대로 들어맞게 되었다. 조문이 서로 다르다는 점도 독립의 근거로 읽혔을 가능성이 크다.
2. **질문 틀이 목적과 어긋난다.**
- 부착에 필요한 판단은 "이 BO가 선언 유형 구조 안의 사건·요건·항변으로 다뤄질 수 있는가"다. 예를 들어 일부변제·최고·승인은 금전채권의 시효·금액에 작용하는 사건이다.
- 그런데 지금 선택지는 "고유한 효과가 있는가"를 묻는다. 고유한 효과가 있어도 선언 유형의 생애에 속하는 사건은 많은데, 이 경우를 담을 선택지가 없다.
- 정보가 늘수록 JEV는 이 틀 안에서 더 확신을 가지고 independent를 고른다.
3. **지시문 변경("identifiers" → "information")의 몫은 이 회차만으로 나눌 수 없다.**
4. **이 회차의 판정이 틀린 것은 아니다.** X1의 6쌍처럼 선언 유형과 실제로 관계가 없는 쌍에서 independent가 1.00에 가까워진 것은 정보가 늘어 판별이 선명해진 결과로 볼 수 있다.
## 5. 프로브와 기타 관찰
| 항목 | 결과 |
|---|---|
| glossary 실패 시 planner 진행 | **미확인**(glossary가 실패하지 않았다) |
| P-2 실패한 jev 인스턴스 · 빈 fan-out 장벽 | **미확인**(1차와 같은 데이터라 시험되지 않았다) |
| 비어 있지 않은 fan-out 장벽 | 재확인. "All 17 instances … aggregate set" 뒤에 apply가 시작했다 |
| `llm_reasoning: low` → thoughts | `thoughts_tokens=0`. 사고 토큰이 쓰이지 않았다 |
| 비용 | glossary $0.0244 + JEV 약 $0.0005. 1차 대비 회차당 약 $0.025 늘었다 |
## 6. 권고
1. **`SHADOW_RUN`은 그대로 둔다.** 지금 임계값으로 켜면 승격 제안 12건만 handoff에 쌓이고, 부착은 0건이다.
2. **질문 틀을 고치는 것을 먼저 검토한다.** JEV 이후 구간의 개정이므로 사용자 승인이 필요하다.
- 선택지 예: "선언 유형 구조 안에서 다뤄지는 사건·요건·항변"(부착 대상), "선언 유형과 별개 구조"(승격 후보), "무관"(목표 T가 맞지 않음).
- criteria 설명은 "고유한 효과가 있어도 선언 유형의 성립·소멸·시효·금액에 작용하면 부착"이라는 판단 기준을 담도록 바꾼다.
3. **원인을 나누는 A/B 실행을 고려한다.** 이번 `type_glossary.json`(`3cb6348f`)을 고정해 재사용하고, 지시문만 "identifiers"로 되돌려 한 번 돌린다. 그러면 정의 효과와 지시문 효과를 가를 수 있다. 정의가 회차마다 다시 생성되는 점도 이 방법으로 통제된다.
4. **사람 라벨을 붙인다.** 미부착 BO 15건마다 "붙여야 할 선언 유형 / 승격 / 무관"을 정해야, 어떤 질문 틀과 임계값이 맞는지 잴 수 있다.
5. **조문은 여전히 미검증이다.** 이 판의 점수는 임계값 보정 근거로만 쓴다.
## 7. 검증 범위
형식, 흐름, 계약 준수, 회차 간 수치 비교만 보았다. glossary 정의·조문과 JEV 판정이 법률적으로 맞는지는 판단하지 않았다.
@@ -0,0 +1,112 @@
# Stage 1 Part 3 실행결과보고서 3 (2026-11-05, criteria 개정 + `unrelated` 첫 실행)
- **대상:** `stage_1_part_3_v.8.yml`(`43dfd228…`, 2,560행). 2차 실행 판(`284f4417`)에서 두 가지를 바꿨다.
- 2:25pm: criteria 두 줄. part_of를 넓히고 independent를 좁혔다.
- 2:39pm: 넷째 선택지 `unrelated`를 추가하고 apply를 개정했다(4키, 수용 차단, 승격 하한 0.50, 영수증 v2).
- 그림자 실행 설정(`SHADOW_RUN=True`)이다.
- **실행:** workspace `11월_1일_구성`, 세션 `2650ba1a`, 2026-11-05 05:52:09 ~ 05:53:17 UTC(**68초**).
- **입력:** 1·2차와 같은 Part 2 4차 산출이다. BO 78건, L0 결과(구조 50, BO 63/15)도 같다.
- **근거(모두 읽기 전용):**
- `agent-backend` 로그(타임스탬프 포함).
- localdocs 산출물: `type_glossary.json`, 요청 파일, L1 영수증 v2, handoff, `legal_effect_structures.json`.
- 1·2차의 쌍별 확률은 같은 백엔드 로그 구간에서 뽑은 값(`실행결과보고서_2_part_3.md` §4)을 쓴다.
## 1. 판정 — **실행 성공, 의도한 효과 확인**
| 기준 | 결과 |
|---|---|
| 백엔드 | `task_complete` 39건(L0 1 + glossary 1 + planner 1 + recommender 17 + capture 17 + apply 1 + L2 1). `task_error`·`task_retry`·Traceback 0건. `stage_complete`·`execution_complete` 각 1 |
| glossary | Gemini 1회 43.9초. prompt 15,084, output 3,091, thoughts 0 토큰. $0.0229. 48/48 통과, 조문 버림 0. sha `1e3b5fab…`(2차 `3cb6348f…`와 다름 — 다시 생성됐다) |
| planner | `PLANNED`. 13후보·17쌍(변화 없음). timeout 300 반영 |
| JEV | 17회, `jev-1.14.0`. 입력 토큰 합 14,283(호출당 약 840). **ANSWER_MISSING 0** — 17건 모두 4키 확률을 돌려줬다 |
| apply | `APPLIED`. 영수증 `…receipt.v2`, `relation_keys` 4개, `thresholds.independent_floor` 0.5. 13건 모두 `UNDECIDED`(그림자 실행). 번들·handoff 재기록 없음 |
| L2 | `READY_WITH_REVIEW`. 보존 등식 셋 통과. review_queue는 HARD 15 + 18로 1·2차와 같다 |
- 4키 계약(criteria ↔ `RELATION_KEYS` ↔ 영수증 v2)이 실호출에서 깨지지 않았다.
- 이번 회차에서 처음으로 JEV 판정이 목적한 방향으로 갈렸다(§3).
## 2. IO 구조 (실측 시각)
```
L0 ─▶ bundle · handoff(OPEN, 33)
├▶ glossary (05:52:14→05:52:58, Gemini 43.9s) ─▶ planner prev
└▶ planner (05:52:58→05:53:01, 3.35s) ─▶ type_glossary.json(48) · recommender_requests.json(13/17)
├▶ recommender_0..16 (jev) — "All 17 … aggregate set" 05:53:02
│ └▶ capture_{same_ordinal} — "All 17 … aggregate set" 05:53:11
└▶ apply (→05:53:14, 3.17s) ─▶ part3_recommender_receipt.json (v2)
L2 (→05:53:17, 3.27s) ─▶ legal_effect_structures.json (READY_WITH_REVIEW)
```
## 3. JEV 판정 비교 (1차 → 2차 → 3차, 정규화 확률)
i = independent_effect, p = part_of_declared_type, w = wording_variant, u = unrelated(3차만). 쌍은 `d|k|T`로 맞췄다.
| 도메인 | 후보 → 선언 유형 | 1차 i / p | 2차 i / p | **3차 i / p / w / u** | 3차 최댓값 |
|---|---|---|---|---|---|
| E-02 | partial_payment → money_claim | 0.29 / 0.71 | 0.68 / 0.32 | 0.00 / **1.00** / 0.00 / 0.00 | part_of |
| E-02 | demand_notice → money_claim | 0.62 / 0.36 | 0.85 / 0.15 | 0.00 / **1.00** / 0.00 / 0.00 | part_of |
| E-02 | debt_acknowledgement → money_claim | 0.67 / 0.32 | 0.85 / 0.15 | 0.00 / **1.00** / 0.00 / 0.00 | part_of |
| E-02 | due_date_modification → money_claim | 0.67 / 0.33 | 0.89 / 0.11 | 0.01 / **0.99** / 0.00 / 0.00 | part_of |
| E-02 | guarantor_procurement_promise → money_claim | 0.75 / 0.24 | 0.88 / 0.12 | 0.33 / **0.36** / 0.00 / 0.31 | part_of(근소) |
| E-15 | inheritance_succession_status → succession_notice_lien_asset_defense | 0.69 / 0.30 | 0.95 / 0.05 | 0.15 / 0.16 / 0.00 / **0.69** | unrelated |
| E-12 | sole_ownership_assertion → aggregate_building_management | 0.68 / 0.30 | 0.98 / 0.02 | 0.14 / 0.05 / 0.00 / **0.81** | unrelated |
| E-12 | sole_ownership_assertion → boundary_determination | 0.76 / 0.22 | 1.00 / 0.00 | 0.30 / 0.04 / 0.00 / **0.66** | unrelated |
| E-12 | sole_ownership_assertion → coownership_governance | 0.91 / 0.09 | 0.99 / 0.01 | **0.53** / 0.14 / 0.00 / 0.33 | independent |
| E-12 | sole_ownership_assertion → coownership_partition | 0.71 / 0.25 | 0.94 / 0.05 | **0.56** / 0.22 / 0.03 / 0.19 | independent |
| E-12 | sole_ownership_assertion → exclusive_use_settlement | 0.78 / 0.19 | 1.00 / 0.00 | **0.51** / 0.09 / 0.01 / 0.39 | independent |
| X1 | contract_change_request_notice_lifecycle → (S) | 0.90 / 0.10 | 0.99 / 0.01 | 0.07 / 0.03 / 0.00 / **0.90** | unrelated |
| X1 | contract_rescission_notice_lifecycle → (S) | 0.95 / 0.05 | 0.99 / 0.01 | 0.19 / 0.04 / 0.00 / **0.77** | unrelated |
| X1 | registry_cancellation_demand_notice_lifecycle → (S) | 0.86 / 0.14 | 0.98 / 0.02 | 0.13 / 0.04 / 0.00 / **0.83** | unrelated |
| X1 | lease_termination_notice_lifecycle → (S) | 0.93 / 0.07 | 1.00 / 0.00 | 0.18 / 0.09 / 0.00 / **0.73** | unrelated |
| X1 | oral_demand_notice_lifecycle → (S) | 0.81 / 0.18 | 1.00 / 0.00 | 0.31 / 0.33 / 0.00 / **0.36** | unrelated(근소) |
| X1 | demand_notice_lifecycle → (S) | 0.77 / 0.22 | 1.00 / 0.00 | 0.26 / **0.39** / 0.00 / 0.35 | part_of(근소) |
(S) = succession_notice_lien_asset_defense
### 기대값 대비
| 기대값(2:39pm 머리말) | 결과 |
|---|---|
| E-02: part_of 상승. 효과는 예시에 이름이 없는 두 쌍으로 판단 | **충족.** `due_date_modification` 0.11 → 0.99. `guarantor_procurement_promise`는 0.12 → 0.36으로 올랐지만 셋으로 갈렸다. 예시에 이름이 있는 세 쌍은 1.00(예시 효과와 분리할 수 없다) |
| E-02: unrelated 질량은 part_of가 아니라 independent에서 빠져야 한다 | **충족.** 4쌍은 u 0.00. guarantor만 u 0.31 |
| X1 → unrelated | **6쌍 중 5쌍 충족**(u 0.36~0.90). `demand_notice_lifecycle`은 part_of 0.39로 근소하게 앞섰고, `oral_demand_notice_lifecycle`은 u 0.36으로 근소하다. 두 후보 모두 "최고(demand)" 계열이다 |
| E-12: 공유 유형 쌍 → independent 또는 part_of, 경계 쌍 → unrelated 또는 independent | **충족.** 공유 3쌍은 independent 0.51~0.56, 경계·집합건물 2쌍은 unrelated |
| E-15: 기록만 | unrelated 0.69 |
### 시작 임계값(0.80 / 0.20 / 0.80 / floor 0.50)으로 다시 계산
| 결과 | 후보 | 붙는 BO |
|---|---|---|
| **수용 4** | E-02 partial_payment, demand_notice, debt_acknowledgement, due_date_modification → `money_claim`(attach 0.99~1.00, T가 하나라 마진 조건 없음) | bh3, bh7, bh31, bh42, bh40 = **5건** |
| 승격 제안 0 | — | — |
| 무결정 9 | E-02 guarantor(attach 0.36), E-12 sole_ownership(최고 attach 0.25, 비부착 질량이 0.80 미만인 쌍 있음), E-15, X1 6종 | — |
- 그림자 실행을 끄면 미부착 BO는 15건에서 **10건**으로 줄어든다. 남는 10건은 bh41, bh44, bh51, X1 7건이다.
- 1·2차에서는 같은 계산으로 붙는 BO가 0건이었다.
- 승격 제안은 0건이다. 2차의 12건이 모두 사라졌다. X1처럼 목표가 하나이고 그것이 무관한 후보는 설계상 승격되지 않는다.
## 4. 해석과 주의
1. **criteria와 `unrelated`가 함께 작동했다.** 2차에서 17쌍 모두 independent 쪽(0.68~1.00)으로 기울던 분포가 셋으로 갈렸다. 생애 사건은 part_of, 경합 구조는 independent, 무관한 목표는 unrelated다. 이번 변경으로 질문 틀과 목적(부착 여부)이 맞춰졌다.
2. **E-02의 1.00은 예시 효과와 섞여 있다.** part_of 설명의 예시가 partial_payment·demand_notice·debt_acknowledgement를 직접 부른다. 예시에 없는 due_date_modification도 0.99라서 규칙 자체가 통했다는 근거는 있다. 하지만 세 쌍의 확신도는 예시를 빼면 낮아질 수 있다.
3. **약한 판정이 세 곳에 있다.**
- `guarantor_procurement_promise`(0.33/0.36/0.31)
- X1 `demand_notice_lifecycle`(p 0.39 / u 0.35)
- X1 `oral_demand_notice_lifecycle`(u 0.36 / p 0.33)
- 시작 임계값에서는 모두 무결정이라 잘못 붙지는 않는다. 다만 "최고" 계열 통지가 승계 항변의 part_of로 끌리는 것은 예시의 "demand for performance"가 X1에도 함께 실리기 때문일 수 있다(1차 검증 MINOR-1이 예상한 위험).
4. **"같은 입력"이 아니다.** glossary가 다시 생성됐다(`1e3b5fab`, 2차는 `3cb6348f`). 그래서 이번 변화는 criteria·`unrelated`·정의 차이가 합쳐진 결과다.
5. **조문·정의는 여전히 미검증이다.** 판정의 법률적 타당성은 이 보고서에서 판단하지 않았다.
## 5. 권고
1. **수용 4건(BO 5건)을 사람이 검토한다.** E-02 `money_claim`에 일부변제·최고·채무승인·변제기 변경을 붙이는 것이 맞는지 확인한다. 맞다면 그림자 실행을 끌 근거가 생긴다. 끄더라도 시작 임계값(0.80/0.20/0.80/0.50)이면 이번 데이터에서는 이 4건만 움직인다.
2. **임계값은 지금 값을 유지한다.** 이 회차에서 수용과 무결정이 깔끔하게 갈린다(수용은 0.99 이상, 다음 높은 attach는 0.39).
3. **선택 사항(각각 승인 필요):**
- part_of 예시를 시험 후보가 아닌 항목으로 바꿔 예시 효과를 걷어낸다.
- "목표 무관" 판정을 handoff SOFT 항목으로 알린다. 그러면 X1 7건에 대해 사람이 "레지스트리 승격 또는 다른 도메인 대상"을 판단하기 쉬워진다.
- glossary를 고정해 회차 간 비교의 변수를 하나로 줄인다.
4. **미실측 경로:** glossary 실패, 실패한 jev 인스턴스(P-2), 빈 fan-out 장벽은 여전히 시험되지 않았다.
## 6. 검증 범위
형식, 흐름, 계약 준수, 회차 간 수치 비교, 임계값 재계산만 보았다. 판정과 정의가 법률적으로 맞는지는 판단하지 않았다.
@@ -0,0 +1,124 @@
# Stage 1 Part 3 실행결과보고서 4 (2026-11-05, 그림자 실행 해제 후 첫 실행)
- **대상:** `stage_1_part_3_v.8.yml`(`5b6336bd…`, 2,589행). 3:30pm 사용자 결정 세 가지를 적용한 판이다.
- `SHADOW_RUN = False`
- part_of 예시를 "채무면제·혼동"으로 교체
- SOFT `PART3_RECOMMENDER_TARGET_UNRELATED` 신설
- **실행:** workspace `11월_1일_구성`, 세션 `6ed2a14b`, 2026-11-05 06:43:27 ~ 06:44:24 UTC(**57초**).
- **입력:** 1~3차와 같은 Part 2 4차 산출이다. BO 78건, L0 결과(구조 50, BO 63/15)도 같다.
- **근거(모두 읽기 전용):**
- `agent-backend` 로그(타임스탬프 포함).
- localdocs 산출물: `type_glossary.json`, 요청 파일, L1 영수증 v2, handoff, `legal_effect_structures.json`.
- 3차 쌍별 확률(보고서 3 §3).
## 1. 판정 — **성공 (L1이 처음으로 결과물을 바꿨다)**
| 기준 | 결과 |
|---|---|
| 백엔드 | `task_complete` 39건. `task_error`·`task_retry`·Traceback 0건. `stage_complete`·`execution_complete` 각 1 |
| glossary | Gemini 1회 33.1초. prompt 15,084, output 4,102, thoughts 0 토큰. $0.0267. 48/48 통과, 조문 버림 0. sha `3f875037…`(3차 `1e3b5fab…`와 다름) |
| planner | `PLANNED`, 13후보·17쌍 |
| JEV | 17회, `jev-1.14.0`. 입력 토큰 14,720. ANSWER_MISSING 0 |
| apply | `APPLIED`, `shadow_run: false`. 실제 임계값: 수용 0.80, 마진 0.20, 승격 0.80, 하한 0.50. **ACCEPT 4 · UNDECIDED 9.** 번들·handoff 모두 재기록(`bundle_rewritten`·`handoff_rewritten` true) |
| 부착 | BO **5건** → E-02 `money_claim`. 영수증 `bo_counts`: 부착 63 → 68, 미부착 15 → 10 |
| L2 | `READY_WITH_REVIEW`. 보존 등식 셋 통과 — **BO 68 + 10 = 78**, 선언 50, route 66 + 18 = 84 |
- 그림자 실행을 끈 판이 처음으로 실제 데이터에서 돌았다.
- 번들·handoff 재기록, 쓰기 재읽기 대조, L2 보존 등식 재계산이 모두 정상이었다.
- handoff 검토 항목 가운데 `status`·`blocked` 키를 가진 것은 0건이다.
## 2. IO 구조 (실측 시각)
```
L0 ─▶ bundle · handoff(OPEN, 33)
├▶ glossary (06:43:31→06:44:05, Gemini 33.1s)
└▶ planner (→06:44:08, 3.43s) ─▶ type_glossary.json · recommender_requests.json(13/17)
├▶ recommender_0..16 — "All 17 … aggregate set" 06:44:08
│ └▶ capture_* — "All 17 … aggregate set" 06:44:18
└▶ apply (→06:44:21, 3.28s) ─▶ bundle 재기록(부착 5) · handoff 재기록(33 → 40) · 영수증 v2
L2 (→06:44:24, 3.32s) ─▶ legal_effect_structures.json (READY_WITH_REVIEW) · handoff FINALIZED
```
## 3. 결과물 변화
### 3.1 부착된 BO 5건 (`PART3_BO_ATTACHED_BY_RECOMMENDER`, SOFT, `decided_by: recommender`)
| BO | 후보 유형 | 붙은 구조 | relation | accept_score |
|---|---|---|---|---|
| bh3 | partial_payment | `LES-E-02-money_claim` | part_of_declared_type | 0.99 |
| bh7 | partial_payment | `LES-E-02-money_claim` | part_of_declared_type | 0.99 |
| bh31 | demand_notice | `LES-E-02-money_claim` | part_of_declared_type | 0.99 |
| bh40 | due_date_modification | `LES-E-02-money_claim` | part_of_declared_type | 0.99 |
| bh42 | debt_acknowledgement | `LES-E-02-money_claim` | part_of_declared_type | 0.99 |
- 최종 `money_claim` 레코드의 `source_bo_ids`는 12개다(기존 7 + 5).
- `review_codes`는 `PART3_BO_ATTACHED_BY_RECOMMENDER`, `review_required`는 true다.
- `structure_index.by_bo_id`에서 bh3·bh40 등이 `LES-E-02-money_claim`을 가리킨다. Part 4는 이 색인으로 이 구조를 찾는다.
- 이 5건의 HARD `PART3_BO_UNATTACHED`는 handoff에서 제거됐다.
- 결과는 3차 보고서가 예상한 수용 4건(BO 5건)과 같다.
### 3.2 handoff / L2 review_queue (33 → 40)
| 코드 | 심각도 | 3차 | 4차 |
|---|---|---:|---:|
| UNREGISTERED_EFFECT_TYPE_REVIEW | HARD | 18 | 18 |
| PART3_BO_UNATTACHED | HARD | 15 | **10** |
| PART3_BO_ATTACHED_BY_RECOMMENDER | SOFT | — | **5** |
| PART3_RECOMMENDER_TARGET_UNRELATED | SOFT | — | **7** |
- **목표 무관 7건:**
- E-15 `inheritance_succession_status`
- X1 `contract_change_request` · `contract_rescission` · `demand_notice` · `lease_termination` · `oral_demand` · `registry_cancellation_demand`(각 `*_notice_lifecycle`)
- 3차 데이터로 재현했을 때는 6건이었다. 이번에는 X1 `demand_notice_lifecycle`의 최댓값이 part_of 0.39에서 unrelated 0.42로 바뀌어 한 건이 늘었다.
- 남은 HARD 미부착 10건과 그 판정은 다음과 같다.
| BO | 후보 | 판정 |
|---|---|---|
| bh41 | guarantor | 무결정 |
| bh44 | E-15 | 목표 무관 |
| bh51 | E-12 | 무결정, 공유 유형과 경합 |
| X1 7건 | X1 후보 6종 | 목표 무관 |
## 4. JEV 판정 비교 (3차 → 4차)
i / p / w / u = independent / part_of / wording / unrelated.
| 쌍 | 3차 | 4차 | 4차 최댓값 |
|---|---|---|---|
| E-02 partial_payment → money_claim | 0.00/1.00/0.00/0.00 | 0.01/0.99/0.00/0.00 | part_of |
| E-02 demand_notice → money_claim | 0.00/1.00/0.00/0.00 | 0.01/0.99/0.00/0.00 | part_of |
| E-02 debt_acknowledgement → money_claim | 0.00/1.00/0.00/0.00 | 0.01/0.99/0.00/0.00 | part_of |
| E-02 due_date_modification → money_claim | 0.01/0.99/0.00/0.00 | 0.01/0.99/0.00/0.00 | part_of |
| E-02 guarantor_procurement_promise → money_claim | 0.33/0.36/0.00/0.31 | 0.36/0.43/0.00/0.21 | part_of(0.43, 수용 미달) |
| E-12 sole_ownership → aggregate_building_management | 0.14/0.05/0.00/0.81 | 0.15/0.03/0.00/0.82 | unrelated |
| E-12 sole_ownership → boundary_determination | 0.30/0.04/0.00/0.66 | 0.40/0.02/0.00/0.58 | unrelated |
| E-12 sole_ownership → coownership_governance | 0.53/0.14/0.00/0.33 | 0.55/0.34/0.00/0.11 | independent |
| E-12 sole_ownership → coownership_partition | 0.56/0.22/0.03/0.19 | 0.67/0.16/0.07/0.10 | independent |
| E-12 sole_ownership → exclusive_use_settlement | 0.51/0.09/0.01/0.39 | 0.55/0.14/0.01/0.30 | independent |
| E-15 inheritance_succession_status → (S) | 0.15/0.16/0.00/0.69 | 0.16/0.20/0.00/0.64 | unrelated |
| X1 contract_change_request → (S) | 0.07/0.03/0.00/0.90 | 0.06/0.06/0.00/0.88 | unrelated |
| X1 contract_rescission → (S) | 0.19/0.04/0.00/0.77 | 0.07/0.06/0.00/0.87 | unrelated |
| X1 demand_notice_lifecycle → (S) | 0.26/0.39/0.00/0.35 | 0.22/0.36/0.00/0.42 | unrelated(근소) |
| X1 lease_termination → (S) | 0.18/0.09/0.00/0.73 | 0.07/0.05/0.00/0.88 | unrelated |
| X1 oral_demand → (S) | 0.31/0.33/0.00/0.36 | 0.23/0.32/0.00/0.45 | unrelated |
| X1 registry_cancellation_demand → (S) | 0.13/0.04/0.00/0.83 | 0.18/0.19/0.00/0.63 | unrelated |
(S) = succession_notice_lien_asset_defense
- **예시 교체의 효과:** E-02 예시를 시험 후보 셋(일부변제·최고·채무승인)에서 채무면제·혼동으로 바꿨는데도, 그 셋은 0.99를 유지했다. 3차의 1.00은 예시 효과가 아니라 기준 문장 자체의 효과였다고 볼 수 있다.
- **안정성:** 정의표가 다시 생성됐지만(sha가 바뀜) 17쌍 모두 최댓값이 3차와 같거나 근소한 쌍에서만 바뀌었다(X1 `demand_notice_lifecycle`). 수용·무결정 경계는 그대로다. 수용 4건은 모두 0.99이고, 그다음으로 높은 attach는 guarantor 0.43이다.
- 근소한 쌍은 여전히 남아 있다. X1의 최고 계열 두 후보(u 0.42·0.45)와 E-12 `boundary_determination`(u 0.58 / i 0.40)이다.
## 5. 남은 확인 사항과 권고
1. **Part 4 확인(3:30pm 머리말 예고):** 붙은 BO 5건 행에 Part 4가 `money_claim`의 `calculation_request_refs`·`domain_effects`를 복사한다. 다음 Part 4 실행에서 그 행들의 `calculation_requests`가 청구 계산 요청을 되풀이하는지 확인한다. 보존 등식에는 영향이 없다.
2. **사람 검토:** SOFT `PART3_BO_ATTACHED_BY_RECOMMENDER` 5건을 검토한다.
- bh3·bh7은 공사도급의 계약금·중도금 지급이다. E-02 금전채권의 "일부 변제"가 맞는지 확인한다.
- bh31·bh40·bh42는 물품대금 채권에 관한 것이다. E-02 `money_claim`이 가리키는 청구와 같은지 확인한다.
3. **목표 무관 7건(SOFT):** 검토자가 다음 처리를 고른다. 레지스트리 승격, 다른 도메인 유형에 붙이기, 또는 버리기다.
4. **정의표 고정:** 추후 Liti-agent 개정 사항(3:30pm 결정)이다. 이번 회차에서도 정의표가 바뀌었다(`3f875037`).
5. **미실측 경로:** glossary 실패, 실패한 jev 인스턴스(P-2), 빈 fan-out 장벽은 아직 시험되지 않았다.
## 6. 검증 범위
형식, 흐름, 계약 준수, 회차 간 수치 비교만 보았다. 부착·판정·정의가 법률적으로 맞는지는 판단하지 않았다.
@@ -0,0 +1,68 @@
# 유형 정의표 — Stage 1 Part 3 실행 3 (Gemini 3.8 Flash 초안, 미검증)
- **출처:** workspace `11월_1일_구성`, 세션 `2650ba1a`(2026-11-05 05:52Z). `Task_C_LE_L1_glossary`(gemini-3.8-flash, llm_reasoning low)가 쓰고, `Task_C_LE_L1_candidate_planner`가 검증해 기록한 `stage1_tmp/task_le/type_glossary.json`을 옮겼다.
- **판:** 파일 sha256 `1e3b5fab2fa3…` · 영수증 `glossary_sha256` `1e3b5fab2fa3…`(planner가 기록한 canonical 본문 sha). 상태 `OK`, 요청 48 = 수용 48, 버린 항목 0.
- **주의:** LLM 초안이다. 모든 항목이 `verified:false`다. law.go.kr 원문으로 조문 번호와 내용을 대조하지 않았으므로 정의와 조문을 사실로 쓰지 않는다. 이 문서는 사람 검토용 사본이고 파이프라인이 읽지 않는다.
- **열:** 도메인 = 그 유형이 선언됐거나(선언 유형) 미부착 BO로 나타난(후보 유형) 도메인. module·role_projection은 선언 유형만 있다.
## 1. 선언 유형 (33개, `general_legal_effect` 제외)
| # | type_id | 도메인 | module / role_projection | 정의(definition_ko) | 근거 조문(statutes) |
|---|---|---|---|---|---|
| 1 | `actio_remedy_or_cap` | E-13 | `actio` / `linked_actio_structures` | 사해행위취소소송에서 원상회복 방법 또는 취소 및 가액배상의 한도액이다. | 민법 제406조 |
| 2 | `aggregate_building_management` | E-12 | `aggregate_building` / `management_body_unit_owner_roles` | 집합건물의 공용부분 관리 및 관리단 운영 등에 관한 법률관계다. | 집합건물의 소유 및 관리에 관한 법률 제16조, 집합건물의 소유 및 관리에 관한 법률 제23조 |
| 3 | `apparent_agency` | E-01 | `agency` / `principal_apparent_agent_relying_party_roles` | 대리권이 없음에도 외관에 터 잡아 본인에게 법률행위 효과를 귀속시키는 제도다. | 민법 제125조, 민법 제126조, 민법 제129조 |
| 4 | `asset_state` | X2 | `asset_state` / `asset_state_projection` | 채무자 등의 적극재산 및 소극재산의 귀속과 현황을 나타내는 상태다. | 민법 제406조 |
| 5 | `boundary_determination` | E-12 | `boundary` / `adjacent_owner_parcel_boundary_roles` | 인접한 토지 상호 간의 경계를 확정하여 법률관계를 명확히 하는 재판상 형성권이다. | 민법 제214조, 민법 제242조 |
| 6 | `cancellation_effect` | E-01 | `juristic_act` / `canceller_counterparty_third_party_roles` | 취소권 행사에 의하여 일단 효력이 발생한 법률행위를 소급하여 무효로 만드는 효력이다. | 민법 제141조 |
| 7 | `commercial_successor` | E-03 | `commercial_successor` / `claim_chain_ref` | 영업양도나 합병 등으로 상사 법률관계상의 지위와 채무를 승계하는 자다. | 상법 제42조 |
| 8 | `condition_term_effect` | E-01 | `juristic_act` / `condition_beneficiary_obligor_roles` | 조건 성취나 기한 도래로 인하여 법률행위의 효력이 발생하거나 소멸하는 효과다. | 민법 제147조, 민법 제152조 |
| 9 | `construction_defect_remedy` | E-07 | `construction_defect` / `construction_defect_roles` | 완성물에 하자가 있는 경우 도급인이 하자보수나 손해배상을 청구하는 권리다. | 민법 제667조 |
| 10 | `construction_defect_setoff` | E-07 | `construction_defect` / `construction_setoff_roles` | 도급인이 수급인에 대한 하자보수 손해배상채권으로 공사대금채권과 대등액에서 상계하는 효력이다. | 민법 제492조, 민법 제667조 |
| 11 | `construction_payment_claim` | E-07 | `construction_contract` / `construction_payment_roles` | 수급인이 도급인에게 완성된 일의 보수 지급을 청구하는 권리다. | 민법 제665조 |
| 12 | `construction_progress_settlement` | E-07 | `construction_contract` / `construction_progress_roles` | 공사 진행 기성에 따라 발생한 공사대금을 정산하여 지급을 구하는 권리다. | 민법 제665조 |
| 13 | `coownership_governance` | E-12 | `coownership` / `coowner_act_consent_roles` | 공유물의 보존 관리 및 처분 변경에 관한 공유자 상호 간의 의사결정 및 권한관계다. | 민법 제264조, 민법 제265조 |
| 14 | `coownership_partition` | E-12 | `partition` / `partitioner_coowner_object_roles` | 공유관계를 해소하고 공유물을 단독소유 또는 가격배상 등의 방식으로 분할하는 청구권이다. | 민법 제268조, 민법 제269조 |
| 15 | `declaration_defect` | E-01 | `juristic_act` / `declarant_counterparty_roles` | 비진의표시 통정허위표시 착오 사기 강박 등으로 흠이 있는 의사표시다. | 민법 제107조, 민법 제108조, 민법 제109조 |
| 16 | `exclusive_use_settlement` | E-12 | `coownership` / `using_coowner_nonusing_coowner_roles` | 공유자 1인이 공유물을 배타적으로 사용수익함에 따라 다른 공유자에게 부당이득을 정산하는 의무다. | 민법 제263조, 민법 제741조 |
| 17 | `fraudulent_transfer` | E-13 | `actio` / `actio_roles` | 채무자가 일반채권자를 해함을 알면서 자기의 재산을 제3자에게 처분하는 사해행위다. | 민법 제406조 |
| 18 | `juristic_act_validity` | E-01 | `juristic_act` / `act_party_object_roles` | 당사자가 의도한 법률효과를 완전히 발생시키는 법률행위의 유효성이다. | 민법 제105조 |
| 19 | `land_use_gain` | E-04, E-11 | `land_use_gain` / `legal_calculation_object` | 권원 없이 타인의 토지를 점유 및 사용하여 얻은 차임 상당의 부당이득 반환의무다. | 민법 제741조 |
| 20 | `lease_attached_property_purchase` | E-08 | `lease_contract` / `lease_purchase_claim_roles` | 임차인이 임대인의 동의를 얻어 부속시킨 물건의 매수를 임대인에게 청구하는 권리다. | 민법 제646조 |
| 21 | `lease_delivery_concurrent_performance` | E-08 | `lease_lifecycle` / `lease_concurrent_performance_roles` | 임대차 종료 시 목적물 인도와 보증금 반환 의무가 상호 동시이행 관계에 있는 항변권이다. | 민법 제536조 |
| 22 | `lease_deposit_return` | E-08 | `lease_contract` / `lease_deposit_return_roles` | 임대차 종료 시 임차인이 임대인에게 보증금의 반환을 청구하는 권리다. | 민법 제317조, 민법 제618조 |
| 23 | `lease_rent_payment` | E-08 | `lease_contract` / `lease_rent_roles` | 임대인이 임차인에게 목적물 사용 수익의 대가인 차임 지급을 청구하는 권리다. | 민법 제618조 |
| 24 | `lease_termination` | E-08 | `lease_lifecycle` / `lease_termination_roles` | 기간 만료나 해지 통고로 인하여 유효하던 임대차관계를 장래를 향해 소멸시키는 효력이다. | 민법 제635조, 민법 제636조 |
| 25 | `money_claim` | E-02, E-03 | `money_claim` / `claim_chain_ref` | 채권자가 채무자에게 금전의 지급을 청구할 수 있는 권리다. | 민법 제390조 |
| 26 | `possession_vindication` | E-11 | `possession_vindication` / `linked_structures` | 소유자가 그 소유에 속한 물건을 정당한 권원 없이 점유하는 자에게 반환을 청구하는 권리다. | 민법 제213조 |
| 27 | `preserved_claim` | E-13 | `actio` / `claim_chain_ref` | 채권자취소권이나 채권자대위권 행사에 의하여 보전되는 채권자의 권리다. | 민법 제404조, 민법 제406조 |
| 28 | `registry_invalidity` | E-09, E-10 | `registry_invalidity` / `linked_structures` | 실체적 권리관계에 부합하지 않거나 원인무효인 등기의 효력이 부정되는 상태다. | 민법 제186조 |
| 29 | `secured_debt` | E-10 | `secured_property` / `linked_structures` | 저당권이나 질권 등 담보물권에 의하여 우선변제가 담보되는 피담보채권이다. | 민법 제356조, 민법 제360조 |
| 30 | `succession_notice_lien_asset_defense` | E-10, E-11, E-15, X1, X3 | `succession_notice_lien_asset_defense` / `linked_structures` | 권리승계 통지나 유치권 등 실체적 권리에 터 잡아 목적물 인도나 청구를 거절하는 항변이다. | 민법 제320조, 민법 제450조 |
| 31 | `unauthorized_agency` | E-01 | `agency` / `principal_agent_counterparty_roles` | 대리권 없는 자가 본인을 대리하여 행한 법률행위로 본인에 대해 무효인 상태다. | 민법 제130조 |
| 32 | `unjust_enrichment` | E-04 | `unjust_enrichment` / `restitution_roles` | 법률상 원인 없이 타인의 재산 또는 노무로 인하여 이익을 얻고 손해를 가한 자의 반환의무다. | 민법 제741조 |
| 33 | `valuation` | E-04, X2 | `valuation` / `legal_calculation_object` | 재산이나 물건 또는 사용이익 등의 경제적 가치액을 금전으로 산정하는 효력이다. | 민법 제748조 |
## 2. 후보 유형 (15개, 레지스트리 미등록)
| # | type_id | 도메인 | 정의(definition_ko) | 근거 조문(statutes) |
|---|---|---|---|---|
| 1 | `contract_change_request_notice_lifecycle` | X1 | 계약 내용의 변경을 구하는 청약 또는 통지의 발송 도달 및 효력발생 과정이다. | 민법 제111조, 민법 제527조 |
| 2 | `contract_rescission_notice_lifecycle` | X1 | 채무불이행 등을 이유로 한 계약해제 의사표시의 발송 도달 및 효력발생 과정이다. | 민법 제111조, 민법 제543조 |
| 3 | `debt_acknowledgement` | E-02 | 시효의 이익을 받는 자가 채권자에 대하여 채무의 존재를 알고 있음을 표시하는 통지다. | 민법 제168조 제3호 |
| 4 | `demand_notice` | E-02 | 채권자가 채무자에 대하여 채무의 이행을 구하는 최고다. | 민법 제174조, 민법 제387조 제2항 |
| 5 | `demand_notice_lifecycle` | X1 | 채무자에 대한 이행청구 또는 최고 통지의 발송부터 상대방 도달 및 최고 효력의 과정이다. | 민법 제111조, 민법 제174조 |
| 6 | `due_date_modification` | E-02 | 당사자의 합의로 기존 채무의 변제기를 연기하거나 변경하는 효력이다. | 민법 제152조 |
| 7 | `guarantor_procurement_promise` | E-02 | 주채무자가 채권자에게 장래에 보증인을 세우기로 약속하는 법률관계다. | 민법 제431조 |
| 8 | `inheritance_succession_status` | E-15 | 피상속인의 사망으로 인하여 재산에 관한 포괄적 권리의무를 승계하는 지위다. | 민법 제1005조 |
| 9 | `lease_contract_formation` | —(미부착 BO 없음, route만) | 당사자 일방이 사용수익하게 하고 상대방이 차임 지급을 약정함으로써 성립하는 계약이다. | 민법 제618조 |
| 10 | `lease_relationship` | —(미부착 BO 없음, route만) | 임대차계약 체결로 인하여 당사자 간에 발생하는 사용수익권과 차임채무 등의 권리의무관계다. | 민법 제618조 |
| 11 | `lease_termination_notice_lifecycle` | X1 | 임대차계약 해지 의사표시의 통지 발송부터 도달 및 계약 종료 효력까지의 과정이다. | 민법 제111조, 민법 제635조 |
| 12 | `oral_demand_notice_lifecycle` | X1 | 구두로 행해진 이행청구 또는 최고 의사표시의 발화부터 상대방 요지 및 효력발생 과정이다. | 민법 제111조, 민법 제174조 |
| 13 | `partial_payment` | E-02 | 채무의 전액 중 일부에 관하여 채무를 이행하는 변제다. | 민법 제460조 |
| 14 | `registry_cancellation_demand_notice_lifecycle` | X1 | 원인무효 등기의 말소를 구하는 청구 의사표시의 통지 발송 도달 및 최고 효력 과정이다. | 민법 제111조, 민법 제214조 |
| 15 | `sole_ownership_assertion` | E-12 | 특정 목적물이 타인과의 공유가 아닌 자신의 단독 소유에 속함을 주장하는 효력이다. | 민법 제211조 |
## 3. 이 회차 JEV 판정에 쓰인 항목
17쌍 state에 실린 것은 후보 13종의 정의와, 선언 유형 `money_claim`·`succession_notice_lien_asset_defense`·E-12 5종의 정의·조문이다. 판정 결과는 `실행결과보고서_3_part_3.md` §3에 있다.
@@ -0,0 +1,9 @@
# 실행법
임시 폴더 X/w 를 만들고 이 폴더 파일을 복사한다. X/asset_backup 에 ../../p2rev/asset_backup 을 복사한다.
X/w 에서:
mkdir -p new/stage1_runtime new/signals/adapters
cp <v.8>/stage_1_part_2_v.8.yml p2_orig.yml ; cp <v.8>/stage_1_part_3_v.8.yml p3_orig.yml ; cp <v.8>/stage_1_part_4_v.8.yml .
python3 patch_p3.py # p3_orig.yml -> p3_new.yml (Part 3 전략서 적용본)
python3 patch_p2.py <Default_Agent 절대경로> # new/*, p2_new.yml 생성
python3 t2.py ; python3 t3v1.py # 또는 r1/ 의 시험 (r1base.py 사용, 같은 폴더로 복사)
base2.py: mode "V2"=패치본(자산 overlay 포함), "CUR"=현행. 프로젝트 안에서 돌리지 않는다(tmp 캐시 생성). Bearer 줄 출력 금지.
@@ -0,0 +1,77 @@
exec(open('h2.py').read())
import re as _re, math
from collections import Counter
NEW=pathlib.Path("new")
_ol={"Default_Agent/"+str(p.relative_to(NEW)):p.read_text(encoding="utf-8") for p in NEW.rglob("*") if p.is_file()}
_ol["Default_Agent/signals/adapters/s3_domain_seed_adapter.py"]=_ol["Default_Agent/signals/adapters/s3_domain_seed_adapter.txt"]
_ol["Default_Agent/stage1_runtime/structure_index_compiler.py"]=_ol["Default_Agent/stage1_runtime/structure_index_compiler.txt"]
_ol["Default_Agent/stage1_runtime/fact_ledger_compiler.py"]=_ol["Default_Agent/stage1_runtime/fact_ledger_compiler.txt"]
def overlay(mode): return dict(_ol) if mode=="V2" else {}
pn=open("p2_new.yml",encoding="utf-8").read().split("\n"); po=open("p2_orig.yml",encoding="utf-8").read().split("\n")
R0SRC=code("Task_C_BO_R0_seed_reducer_and_exception_planner",pn);F0SRC=code("Task_C_BO_F0_final_bo_compiler_gate_writer",pn);S0SRC=code("Task_C_BO_S0_signal_bundle_writer",pn)
OLD_R0=code("Task_C_BO_R0_seed_reducer_and_exception_planner",po);OLD_F0=code("Task_C_BO_F0_final_bo_compiler_gate_writer",po);OLD_S0=code("Task_C_BO_S0_signal_bundle_writer",po)
p3=open("p3_new.yml",encoding="utf-8").read().split("\n"); p4=open("stage_1_part_4_v.8.yml",encoding="utf-8").read().split("\n")
L0=code("Task_C_LE_L0_structure_seed_reducer",p3); L2=code("Task_C_LE_L2_final_structure_index_writer",p3); FL=code("Task_C_FL_F0_fact_ledger_reducer",p4)
def R_(extra=(),n=7,**ov):
r=seedroot([good(i) for i in range(1,n+1)]+list(extra)); r.update(ov); return r
def down(src,fs,tag):
purge()
src=src.replace(" _init()\n RESULT = main()\n"," RESULT = None\n")
g=load(src,fs,tag)
g["_call"]=lambda n,a,m=None: fs.call(n,a)
buf=io.StringIO()
with contextlib.redirect_stdout(buf):
r=g["main"]()
return r
idx=json.loads((D/"domains/_registry_index.json").read_text(encoding="utf-8")); IR=idx["domain_registry_index"]; rv=IR["registry_version"]
rsha=hashlib.sha256((D/"domains/_registry_index.json").read_bytes()).hexdigest()
ALLD=[e["domain_id"] for e in IR["entries"]]
def mkact(ds=("E-02",),exp=None):
a=activation(); m=a["domain_activation_manifest"]; m["registry_version"]=rv; m["registry_index_sha256"]=rsha
exp=list(exp or ds)
m["domain_entries"]=[dict(m["domain_entries"][0],domain_id=x) for x in dict.fromkeys(exp)]
m["active_domain_ids"]=list(dict.fromkeys(exp)); m["expected_runnable_domain_ids"]=exp
return a
L=lambda **k: dict({"type_id":"money_claim","registered":True,"source_refs":["EV-1"]},**k)
def wrapfs(fs):
_c=fs.call
def call(n,a,_c=_c,fs=fs):
if n=="list_docs": return {"result":{"content":[{"text":json.dumps({"results":[]})}]}}
return _c(n,a)
fs.call=call
def reseal(fs):
p="signals/signal_manifest.json"; m=json.loads(fs.docs[p]); r=m.get("signal_manifest",m)
r["files"]=[row for row in r["files"] if "signals/"+row["path"] in fs.docs]
for row in r["files"]:
row["file_sha256"]=hashlib.sha256(fs.docs["signals/"+row["path"]].encode()).hexdigest()
fs.docs[p]=json.dumps(m,ensure_ascii=False)
def rj(fs,p): return json.loads(fs.docs[p])
def wj(fs,p,o): fs.docs[p]=(json.dumps(o,ensure_ascii=False,sort_keys=True,indent=2)+"\n")
def run(name,docs,tamper=None,hook=None,fl=False,lzero=None,mode="V2"):
v,fs=go(mode,docs,hook=hook)
s0=v.get("S0")
res={"S0":str(s0)[:230] if s0 else (str(v.get("R0"))[:230],str(v.get("F0"))[:230]),"man":v.get("man")}
if s0 in ("READY","READY_WITH_REVIEW","BLOCKED"):
wrapfs(fs)
if tamper: tamper(fs); reseal(fs)
for lab,src in (("L0",lzero or L0),("L2",L2))+((("FL",FL),) if fl else ()):
cnt[0]+=1
try:
r=down(src,fs,"x%s%d"%(lab,cnt[0])); res[lab]=r.get("status")
if lab=="L0":
h=rj(fs,"quality_gates/stage1_part3_review_handoff.json")["stage1_part3_review_handoff"]
b=rj(fs,"stage1_tmp/task_le/structure_seed_bundle.json")["structure_seed_bundle"]
res["codes"]=dict(Counter("%s/%s"%(i.get("review_code"),i.get("severity")[0]) for i in h["review_items"]))
res["counts"]={k:b["counts"][k] for k in("structure_records","sg13_route_total","routes_attached","routes_unattached","bo_total","bo_attached","bo_unattached","sg11_linked","sg11_unlinked")}
res["_b"]=b; res["_h"]=h
if lab=="L2": res["gate"]=r.get("quality_gate_pass")
except BaseException as e:
res[lab]="EXC %s %s"%(type(e).__name__,str(e)[:330]); break
res["_fs"]=fs
return res
def pr(name,r,extra=()):
d={k:v for k,v in r.items() if not k.startswith("_")}
print("##",name,json.dumps(d,ensure_ascii=False)[:900])
for k in extra: print(" ",k,json.dumps(r.get(k),ensure_ascii=False)[:400])
def single(extra,n=7,**kw):
return run("",multi_docs({"E-02":dict(R_(extra,n),registry_version=rv,registry_index_sha256=rsha)},act=mkact()),**kw)
@@ -0,0 +1,265 @@
"""w2: 실제 R0 main → (R1 무예외) → F0 main → S0 build/compile 를 가짜 MCP 위에서 돌린다.
CUR = 현행, V2 = 전략서 v2 현재 문구 구현. 프로젝트 파일은 읽기만 한다."""
import ast, hashlib, json, os, pathlib, re, shutil, sys, tempfile, types, copy, io, contextlib, traceback
ROOT=pathlib.Path("/Users/hogyujhang/Library/CloudStorage/Dropbox/Business/Eroom AI Partners/Legal POC portfolio/민사에이전트-사해행위취소및대여금청구/POC - Law-aid Agent/프롬프트/prompt_updates_sequential/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1")
D=ROOT/"v.7/extension_research/Default_Agent"; P2=ROOT/"v.8/stage_1_part_2_v.8.yml"
fake=types.ModuleType("httpx")
class _C:
def __init__(self,*a,**k): pass
def post(self,*a,**k): raise RuntimeError("no network")
fake.Client=_C; sys.modules["httpx"]=fake
work=pathlib.Path(tempfile.mkdtemp(dir=".",prefix="tmp"))
lines=open(P2,encoding="utf-8").read().split("\n")
old_lines=open(ROOT/"v.8/stage_1_part_2_v.8_10_31_old_1.yml",encoding="utf-8").read().split("\n")
def code(name,lines=None):
lines=lines or globals()["lines"]
i=next(k for k,l in enumerate(lines) if "task_name: "+name in l)
j=next(k for k in range(i,len(lines)) if lines[k].strip()=="code: |-")
ind=len(lines[j+1])-len(lines[j+1].lstrip()); body=[]
for l in lines[j+1:]:
if l.strip() and (len(l)-len(l.lstrip()))<ind: break
body.append(l[ind:] if l.strip() else "")
return "\n".join(body)
R0SRC=code("Task_C_BO_R0_seed_reducer_and_exception_planner")
F0SRC=code("Task_C_BO_F0_final_bo_compiler_gate_writer")
S0SRC=code("Task_C_BO_S0_signal_bundle_writer")
OLD_R0=code("Task_C_BO_R0_seed_reducer_and_exception_planner",old_lines)
OLD_F0=code("Task_C_BO_F0_final_bo_compiler_gate_writer",old_lines)
OLD_S0=code("Task_C_BO_S0_signal_bundle_writer",old_lines)
def sub1(s,o,n):
assert s.count(o)>=1,o
return s.replace(o,n,1)
# ---- V2 R0 ----
def v2_r0(src):
# A1 _sink_for 문구 그대로
s=sub1(src," if local_name:\n".replace(" ","",1) if False else "if local_name:\n","if local_name and not norm.endswith(\".\" + local_name):\n")
# A2 ① 분기
m=re.search(r'^( +)if not done and enum_unmapped == "repair_evict":',s,re.M); i=m.group(1)
new="\n".join(i+l for l in [
'_fb = _dict(_dict(policy.get("enum_unmapped_fallback")).get(norm))',
'if not done and _fb and isinstance(parent, dict) and key in parent:',
' rec["received"], rec["applied"] = _clip(parent.get(key)), _fb.get("value")',
' rec["rule_id"] = "enum_unmapped_fallback:%s" % norm',
' parent[key] = _fb.get("value")',
' if _fb.get("review_code") and not parent.get("review_code"):',
' parent["review_code"] = _fb.get("review_code")',
' done = True'])+"\n"
s=s[:m.start()]+new+s[m.start():]
# A2 ② slot_id 소문자
m=re.search(r'^( +)rec\["rule_id"\] = "surplus_sink:%s" % norm\n',s,re.M); i=m.group(1)
new="\n".join(i+l for l in [
'if norm.endswith("evidence_slot_status[].slot_id"):',
' _pp, _kk = _resolve_parent(seed_obj, tokens)',
' _vv = _pp.get(_kk) if isinstance(_pp, dict) else None',
' if isinstance(_vv, str) and _vv != _vv.lower():',
' _pp[_kk] = _vv.lower(); rec["applied"] = _vv.lower(); rec["rule_id"] = "slot_id_lower"; records.append(rec); progressed = True; continue'])+"\n"
s=s[:m.start()]+new+s[m.start():]
# A2 ③
m=re.search(r'^( +)validate_seed_object\(seed_obj, domain_id, _plan_row, guard_warnings, _echo_mismatches\)\n',s,re.M); i=m.group(1)
s=s[:m.start()]+i+'_st = seed_obj.get("status"); _tb = _dict(_dict(admission_policy.get("enum_synonyms")).get("status"))\n'+i+'if isinstance(_st, str) and _st.casefold() in _tb: seed_obj["status"] = _tb[_st.casefold()]\n'+s[m.start():]
# A1 쓰기
m=re.search(r'^( +)seed_objects\[domain_id\] = seed_obj\n',s,re.M); i=m.group(1)
s=s[:m.end()]+i+'write_doc("stage1_tmp/task_c_bo/admitted_seeds/%s.json" % domain_id, json.dumps({"stage_b_domain_bo_seed_output": seed_obj}, ensure_ascii=False, indent=2))\n'+s[m.end():]
return s
# ---- V2 S0 ----
def v2_s0(src):
m=re.search(r'^( +)document = read_json_doc\(path\)\n',src,re.M); ind=m.group(1)
new="\n".join(ind+l for l in [
'raw_document = read_json_doc(path)',
'_ad_path = "stage1_tmp/task_c_bo/admitted_seeds/%s.json" % domain_id',
'try:',
' document = read_json_doc(_ad_path)',
'except RuntimeError as _ex:',
' if "not found" in str(_ex).lower(): raise RuntimeError("S0_ADMITTED_SEED_MISSING:%s" % _ad_path)',
' raise',
'_raw_root = raw_document.get("stage_b_domain_bo_seed_output") if isinstance(raw_document, dict) else None',
'_raw_cands = (_raw_root.get("bo_seed_candidates") if isinstance(_raw_root, dict) else None) or []',
'_adm_cands = (document.get("stage_b_domain_bo_seed_output") or {}).get("bo_seed_candidates") or []',
'if len(_raw_cands) != len(_adm_cands):',
' raise RuntimeError("S0_ADMITTED_SEED_DRIFT:%s" % domain_id)',
'RAW_ROW_KEYS = ("element_fact_candidates", "opposing_fact_candidates", "defense_candidates",',
' "legal_effect_candidates", "calculation_requests")',
'for raw_cand, cand in zip(_raw_cands, _adm_cands):',
' if not (isinstance(raw_cand, dict) and isinstance(cand, dict)):',
' continue',
' for key in RAW_ROW_KEYS:',
' rows = raw_cand.get(key)',
' if isinstance(rows, list):',
' cand[key] = [{**r, "payload": {"raw_payload": r["payload"]}}',
' if isinstance(r, dict) and "payload" in r and not isinstance(r["payload"], dict) else r',
' for r in rows]'])+"\n"
return src[:m.start()]+new+src[m.end():]
# ---- V2 adapter ----
def v2_adapter(a):
def R(o,n,c=None):
nonlocal a
assert o in a,o
a=a.replace(o,n) if c is None else a.replace(o,n,c)
R('def _known_refs_only(node: Any, universe: dict[str, Any]) -> Any:','def _known_refs_only(node: Any, universe: dict[str, Any], removed=None) -> Any:')
R('return [_known_refs_only(item, universe) for item in node]','return [_known_refs_only(item, universe, removed) for item in node]')
R(" out[key] = [ref for ref in value if str(ref) in allowed]\n"," out[key] = [ref for ref in value if str(ref) in allowed]\n if removed is not None:\n removed.extend({\"field\": key, \"value\": str(ref)} for ref in value if str(ref) not in allowed)\n")
R(" out[key] = value if str(value) in allowed else None\n"," out[key] = value if str(value) in allowed else None\n if removed is not None and out[key] is None:\n removed.append({\"field\": key, \"value\": str(value)})\n")
R('out[key] = _known_refs_only(value, universe)','out[key] = _known_refs_only(value, universe, removed)')
for w in ('element_rows.append(_known_refs_only(fact, universe))','opposing_rows.append(_known_refs_only(fact, universe))','defense_rows.append(_known_refs_only(defense, universe))'):
R(w,w.replace('universe))','universe, removed))'))
R('def _source_fields(','def _rows(v: Any) -> list[Any]:\n return v if isinstance(v, list) else []\n\n\ndef _source_fields(',1)
R('review_items.extend(_known_refs_only(seed.get("review_items", []), universe))','review_items.extend(_known_refs_only(_rows(seed.get("review_items")), universe, removed))')
R('review_items: list[Any] = _known_refs_only(list(root.get("unknown_or_unrouted_reviews", [])), universe)','removed: list[dict[str, str]] = []\n review_items: list[Any] = _known_refs_only(_rows(root.get("unknown_or_unrouted_reviews")), universe, removed)')
R('for position, seed in enumerate(root.get("bo_seed_candidates", []), start=1):','for position, seed in enumerate(_rows(root.get("bo_seed_candidates")), start=1):')
for k in ("source_refs","element_fact_candidates","opposing_fact_candidates","defense_candidates","calculation_requests","legal_effect_candidates","evidence_slot_status","dependency_refs"):
a=a.replace('seed.get("%s", [])'%k,'_rows(seed.get("%s"))'%k)
R('defense.get("source_refs", seed_refs)','(_rows(defense.get("source_refs")) if "source_refs" in defense else seed_refs)')
R('effect.get("source_refs", seed_refs)','(_rows(effect.get("source_refs")) if "source_refs" in effect else seed_refs)')
R('request.get("source_refs", [])','_rows(request.get("source_refs"))')
R('slot.get("source_refs", [])','_rows(slot.get("source_refs"))')
R('details.get("negative_or_conflicting_refs", [])','_rows(details.get("negative_or_conflicting_refs"))')
R(' stamped = deepcopy(request)\n',' stamped = deepcopy(request)\n for _k in ("source_bo_ids", "source_fact_ids", "law_version_refs", "negative_or_conflicting_refs", "proof_grade", "confidence"):\n _v = stamped.pop(_k, None)\n if _k.endswith(("ids", "refs")):\n removed.extend({"field": _k, "value": str(x)} for x in _rows(_v))\n')
R(""" extensions: dict[str, Any] = {}
""",""" extensions: dict[str, Any] = {}
if removed:
extensions["unverified_refs"] = removed
review_items.append({"review_code": "UNVERIFIED_REF_REVIEW", "severity": "review", "source_refs": [], "reason": "%d건" % len(removed)})
""",1)
R('"domain_registry_version": root.get("registry_version", "UNKNOWN"),','"domain_registry_version": _sg01["registry_version"],')
R('"registry_index_sha256": root.get("registry_index_sha256", "0" * 64),','"registry_index_sha256": _sg01["registry_index_sha256"],')
R(' universe = adapted.get("source_universe", {})\n',' universe = adapted.get("source_universe", {})\n _sg01 = adapted["domain_activation_manifest"]["domain_activation_manifest"]\n')
R('"READY" if root.get("bo_seed_candidates") else','"READY" if _rows(root.get("bo_seed_candidates")) else')
return a
POLV=json.loads((D/"stage1_runtime/seed_admission_policy.v1.json").read_text(encoding="utf-8"))
POLV["_x"]={"bo_seed_candidates[].evidence_slot_status[].status":{"value":"missing","review_code":"SLOT_STATUS_UNMAPPED_REVIEW"},
"bo_seed_candidates[].review_items[].severity":{"value":"review"},"unknown_or_unrouted_reviews[].severity":{"value":"review"}}
def overlay(mode):
if mode=="V2": return {}
B=pathlib.Path("../asset_backup")
return {"Default_Agent/stage1_runtime/seed_admission_policy.v1.json":(B/"seed_admission_policy.v1.json").read_text(encoding="utf-8"),
"Default_Agent/signals/adapters/s3_domain_seed_adapter.txt":(B/"s3_domain_seed_adapter.txt").read_text(encoding="utf-8")}
class Fs:
def __init__(self,mode,docs):
self.docs=dict(docs); self.ov=overlay(mode)
man=json.loads((D/"runtime_manifest.json").read_text(encoding="utf-8"))
for e in man["entries"]:
k="Default_Agent/"+e["path"]
if k in self.ov: e["sha256"]=hashlib.sha256(self.ov[k].encode("utf-8")).hexdigest()
self.ov["Default_Agent/runtime_manifest.json"]=json.dumps(man)
def get(self,p):
if p in self.docs: return self.docs[p]
if p in self.ov: return self.ov[p]
if p.startswith("Default_Agent/"):
f=D/p[len("Default_Agent/"):]
if f.exists(): return f.read_text(encoding="utf-8")
return None
def call(self,name,args):
if name=="read_docs":
p=args["doc_names"][0]; t=self.get(p)
row={"doc":p,"error":"not found"} if t is None else {"doc":p,"content":t}
return {"result":{"content":[{"text":json.dumps({"results":[row]},ensure_ascii=False)}]}}
if name=="write_file":
self.docs[args["path"]]=args["content"]; return {"result":{"content":[{"text":"ok"}]}}
raise RuntimeError(name)
def load(src,fs,tag):
wd=work/tag; wd.mkdir(exist_ok=True)
src=src.replace('"/tmp/s1_r0"','%r'%str(wd/"r0")).replace('"/tmp/s1"','%r'%str(wd/"s1"))
g={"__name__":"loaded"}; exec(compile(src,tag,"exec"),g)
g["_call"]=fs.call; g["_init"]=lambda:None
return g
EV=["EV-1","EV-2","EV-3","EV-4"]; EVT=["EVT-1"]; MC=["MC-1"]
VF="E-001-VF-001"; VF2="E-001-VF-002"
d="E-02"
def slice_doc():
return {"stage_b_domain_slice":{"domain_id":d,"source_universe":[{"source_id":x} for x in EV+EVT+MC],"allowed_legal_effect_bo_types":["event","state","claim"],
"domain_declarations":{"structure_type_ids":["money_claim"],"calculation_domains":[],"element_slot_ids":["e.el01"]}}}
def good(i):
return {"seed_id":"g%d"%i,"bo_type":"event","source_refs":["EV-%d"%(i%4+1)],"element_fact_candidates":[{"source_id":"EV-%d"%(i%4+1),"source_kind":"evidence","excerpt":"본문%d"%i,"payload":{}}],"opposing_fact_candidates":[],"defense_candidates":[],
"evidence_slot_status":[],"calculation_requests":[],"dependency_refs":[],"legal_effect_candidates":[{"type_id":"money_claim","registered":True,"source_refs":["EV-1"]}],"review_items":[],
"extensions":{"domain_payload":{"action_summary":"행위%d"%i,"action_type":"법률행위(legal acts)"}}}
def cand(seed="t1",**k):
c=good(9); c["seed_id"]=seed; c["extensions"]={"domain_payload":{"action_summary":"시험행위","action_type":"법률행위(legal acts)"}}
c.update(k); return c
ev=lambda **k: dict({"source_id":"EV-1","source_kind":"evidence","excerpt":"본문","payload":{}},**k)
def seedroot(cands,import_wv=None):
tid=TID(d); ids=[c.get("seed_id") for c in cands if isinstance(c,dict)]
return {"schema_version":"task_c_bo_stage_b_domain_bo_seed.v3","status":"READY","task_instance_id":tid,"domain_id":d,
"registry_version":"vvv","registry_index_sha256":"a"*64,"domain_config_sha256":"0"*64,"slice_sha256":"0"*64,"compiled_prompt_sha256":"0"*64,
"bo_seed_candidates":cands,"unknown_or_unrouted_reviews":[],
"completion_receipt":{"task_instance_id":tid,"domain_id":d,"seed_count":len(cands),"emitted_seed_ids":ids,"r0_membership_key":"x"},
"contract_guards":{"final_conclusion_forbidden":True,"unknown_values_require_review":True,"source_membership_required":True,"strict_json_output":True}}
rt0=work/"_rt0"; rt0.mkdir()
for m in ["runtime_common","schema_subset_validator","registry_loader","worker_output_validator"]:
shutil.copy(D/"stage1_runtime"/(m+".txt"),rt0/(m+".py"))
sys.path.insert(0,str(rt0)); import worker_output_validator as _w; TID=_w.stable_task_instance_id
def activation():
return {"domain_activation_manifest":{"schema_version":"stage1_domain_activation_manifest.v1","signal_id":"SG-01","status":"READY","registry_version":"vvv",
"domain_entries":[{"domain_id":d,"execution_eligible":True,"positive_refs":[],"negative_refs":[],"conflict_refs":[]}],
"active_domain_ids":[d],"supporting_domain_ids":[],"monitor_domain_ids":[],"required_calculation_domains":[],"unrouted_material":[],
"conservation_gate":{"conservation_pass":True,"candidate_count":0,"classified_count":0,"unrouted_count":0},
"fail_open_policy":{"candidate_downgrade_forbidden":True,"negative_cue_blocks_activation":False,"silent_fallback_forbidden":True,"unrouted_to_residual_collector":True},
"review_items":[],"contract_guards":{"source_membership_required":True,"meeting_only_evidence_promotion_forbidden":True},
"expected_runnable_domain_ids":[d],"registry_index_sha256":"a"*64,"screening_sha256":"0"*64}}
SIG={"SG-05":"legal_relation_lifecycle_signals.json","SG-09":"defense_exception_signals.json","SG-11":"calculation_requirements.json","SG-13":"legal_effect_routes.json"}
def docs_for(rootobj,catalog=None):
st=json.dumps(slice_doc(),ensure_ascii=False)
slc_sha=hashlib.sha256(st.encode()).hexdigest()
rootobj=copy.deepcopy(rootobj); rootobj["slice_sha256"]=slc_sha; rootobj["compiled_prompt_sha256"]="c"*64
cat=catalog or {"binding":{"status":"ABSENT","reason":"x"},"records":[]}
vf=[r["value_id"] for r in cat["records"]]
return {"runtime/domain_seed_outputs/E-02.json":json.dumps({"stage_b_domain_bo_seed_output":rootobj},ensure_ascii=False),
"runtime/domain_slices/E-02.json":st,
"fanout/domain_fanout_plan.json":json.dumps({"domain_fanout_plan":{"task_instances":[{"domain_id":d,"expected_output_path":"runtime/domain_seed_outputs/E-02.json","slice_sha256":slc_sha,"compiled_prompt_sha256":"c"*64,"task_instance_id":TID(d)}]}}),
"stage1_tmp/task_c_bo/stage_a_context.json":json.dumps({"stage_a_context":{"schema_version":"task_c_bo_stage_a_context.v1","status":"READY","created_at_utc":"2026-10-31T00:00:00Z","input_digests_sha256":{}}}),
"stage1_tmp/task_c_bo/source_universe_manifest.json":json.dumps({"evidence_index_set":EV,"event_candidate_ids":EVT,"meeting_clause_ids":MC,"value_fact_ids":vf}),
"stage1_tmp/task_c_bo/value_facts_catalog.json":json.dumps(cat,ensure_ascii=False),
"routing/domain_activation_manifest.json":json.dumps(activation()),
"stage1_tmp/task_c_bo/postb_adjudication_decisions.json":json.dumps({"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":[]}})}
def purge():
for k in list(sys.modules):
if k.split(".")[0] in ("compiler","adapters","emitters","worker_output_validator","runtime_common","schema_subset_validator","registry_loader") or k.startswith("emit_"): del sys.modules[k]
sys.path[:]=[p for p in sys.path if not (str(work.resolve()) in str(pathlib.Path(p).resolve()))]
cnt=[0]
def pipe(mode,rootobj,catalog=None):
cnt[0]+=1; tag="%s%d"%(mode,cnt[0]); fs=Fs(mode,docs_for(rootobj,catalog)); out={}
r0src=R0SRC if mode=="V2" else OLD_R0; s0src=S0SRC if mode=="V2" else OLD_S0; f0src=F0SRC if mode=="V2" else OLD_F0
purge()
buf=io.StringIO()
try:
with contextlib.redirect_stdout(buf):
g=load(r0src,fs,tag); g["main"]()
out["R0"]="OK"
except Exception as ex:
out["R0"]=type(ex).__name__+":"+str(ex)[:220]; return out,fs
led=json.loads(fs.docs["stage1_tmp/task_c_bo/postb_seed_ledger.json"])["postb_seed_ledger"]
out["ledger"]=len(led["ledger_candidates"]); hand=json.loads(fs.docs["quality_gates/stage1_part2_review_handoff.json"])
out["adm"]=[(x.get("source_review_code"),x["template_note"][:110]) for x in hand["review_items"] if x["review_id"].startswith("R0:admission")]
try:
buf=io.StringIO()
with contextlib.redirect_stdout(buf):
g=load(f0src,fs,tag+"f"); g["main"]()
out["F0"]="OK"
except Exception as ex:
out["F0"]=type(ex).__name__+":"+str(ex)[:220]; return out,fs
bo=json.loads(fs.docs["BO.json"]); out["BO"]=len(bo);
comp=json.loads(fs.docs["stage1_tmp/task_c_bo/postb_compiled_bundle_compact.json"]); out["map"]=sorted(comp["candidate_ref_to_bo_id"])
purge()
try:
buf=io.StringIO()
with contextlib.redirect_stdout(buf):
g=load(s0src,fs,tag+"s"); g["main"]()
res=json.loads(buf.getvalue().strip().split("\n")[-1])
out["S0"]=res["status"]; out["man"]=res["manifest_status"]; out["abs"]=res["inputs"]["bo_absent_candidates"]
c={k:len(json.loads(fs.docs["signals/"+v])["records"]) for k,v in SIG.items()}
out["cnt"]=c
e=json.loads(fs.docs["signals/domain_signals/E-02.json"])["domain_signal_envelope"]
out["env"]=dict(st=e["status"],el=len(e["element_fact_candidates"]),op=len(e["opposing_fact_candidates"]),df=len(e["defense_candidates"]),sl=[(x["slot_id"],x["status"],x["review_code"]) for x in e["evidence_slot_status"]],rv=[x.get("review_code") if isinstance(x,dict) else x for x in e["review_items"]],dep=e["dependency_refs"],ext=e["extensions"])
except Exception as ex:
out["S0"]=type(ex).__name__+":"+str(ex)[:300]
return out,fs
def show(title,rootobj,catalog=None,keys=("R0","ledger","F0","BO","S0","man","abs","cnt","env")):
print("==",title)
res={}
for m in ("CUR","V2"):
o,fs=pipe(m,rootobj,catalog); res[m]=(o,fs)
print(" ",m,json.dumps({k:o.get(k) for k in keys if k in o},ensure_ascii=False)[:520])
return res
def base(extra,ov=None):
cs=[good(i) for i in range(1,8)]+list(extra)
r=seedroot(cs); r.update(ov or {}); return r
@@ -0,0 +1,90 @@
exec(open('h.py').read())
import glob
FIX=ROOT/"v.7/extension_research/선행구축/S_3_GPT/e2e/run_2"
_ov0=overlay
EXTRA={}
def overlay(mode):
r=_ov0(mode); r.update(EXTRA.get(mode,{}) or EXTRA.get("*",{})); return r
def policy_mod(**kw):
p=json.loads((D/"stage1_runtime/seed_admission_policy.v1.json").read_text(encoding="utf-8")); p.update(kw)
return {"Default_Agent/stage1_runtime/seed_admission_policy.v1.json":json.dumps(p,ensure_ascii=False)}
def run_task(src,fs,tag,stage):
purge(); buf=io.StringIO()
with contextlib.redirect_stdout(buf):
g=load(src,fs,tag); g["main"]()
return buf.getvalue()
def multi_docs(roots,catalog=None,slices=None,act=None,ev=None):
"""roots: {domain: root}"""
cat=catalog or {"binding":{"status":"ABSENT","reason":"x"},"records":[]}
docs={}; ti=[]
for dm,root in roots.items():
if slices and dm in slices: st=slices[dm]
else:
s=slice_doc(); s["stage_b_domain_slice"]["domain_id"]=dm; st=json.dumps(s,ensure_ascii=False)
sh=hashlib.sha256(st.encode()).hexdigest()
path="runtime/domain_seed_outputs/%s.json"%dm
if isinstance(root,dict):
root=copy.deepcopy(root)
if not slices:
root["slice_sha256"]=sh; root["compiled_prompt_sha256"]="c"*64
root["domain_id"]=dm; root["task_instance_id"]=TID(dm)
if "completion_receipt" in root: root["completion_receipt"]["task_instance_id"]=TID(dm); root["completion_receipt"]["domain_id"]=dm
docs[path]=json.dumps({"stage_b_domain_bo_seed_output":root},ensure_ascii=False); docs["runtime/domain_slices/%s.json"%dm]=st
ti.append({"domain_id":dm,"expected_output_path":path,"slice_sha256":sh,"compiled_prompt_sha256":(root or {}).get("compiled_prompt_sha256","c"*64),"task_instance_id":(root or {}).get("task_instance_id",TID(dm))})
base=docs_for(seedroot([]),cat)
for k in list(base):
if k.startswith("runtime/"): del base[k]
base.update(docs)
base["fanout/domain_fanout_plan.json"]=json.dumps({"domain_fanout_plan":{"task_instances":ti}})
a=act or activation()
if act is None:
inner=a["domain_activation_manifest"]; inner["domain_entries"]=[dict(inner["domain_entries"][0],domain_id=x) for x in roots]; inner["active_domain_ids"]=list(roots); inner["expected_runnable_domain_ids"]=list(roots)
base["routing/domain_activation_manifest.json"]=json.dumps(a)
if ev is not None:
u=json.loads(base["stage1_tmp/task_c_bo/source_universe_manifest.json"]); u["evidence_index_set"]=ev; base["stage1_tmp/task_c_bo/source_universe_manifest.json"]=json.dumps(u)
return base
def go(mode,docs,tag=None,hook=None,stop=None):
cnt[0]+=1; tag="%s%d"%(mode,cnt[0]); fs=Fs(mode,docs); out={}
r0,f0,s0=(R0SRC,F0SRC,S0SRC) if mode=="V2" else (OLD_R0,OLD_F0,OLD_S0)
try: run_task(r0,fs,tag,"r"); out["R0"]="OK"
except BaseException as e: out["R0"]=type(e).__name__+":"+str(e)[:300]; return out,fs
try: run_task(f0,fs,tag+"f","f"); out["F0"]="OK"
except BaseException as e: out["F0"]=type(e).__name__+":"+str(e)[:300]; return out,fs
if hook: hook(fs)
try:
o=run_task(s0,fs,tag+"s","s"); res=json.loads(o.strip().split("\n")[-1]); out["S0"]=res["status"]; out["man"]=res["manifest_status"]; out["res"]=res
except BaseException as e: out["S0"]=type(e).__name__+":"+str(e)[:400]
out["_tag"]=tag
return out,fs
def sigdocs(fs):
r={}
for k,v in fs.docs.items():
if k.startswith("signals/") or k in("BO.json",):
try: r[k]=json.loads(v)
except Exception: r[k]=v
return r
def ddiff(a,b,p="$",out=None,lim=40):
out=[] if out is None else out
if len(out)>=lim: return out
if type(a)!=type(b): out.append((p,str(a)[:100],str(b)[:100])); return out
if isinstance(a,dict):
for k in sorted(set(a)|set(b)):
if k not in a: out.append((p+"."+k,"<none>",str(b[k])[:120]))
elif k not in b: out.append((p+"."+k,str(a[k])[:120],"<none>"))
else: ddiff(a[k],b[k],p+"."+k,out,lim)
elif isinstance(a,list):
if len(a)!=len(b): out.append((p+"#len",len(a),len(b)))
for i,(x,y) in enumerate(zip(a,b)): ddiff(x,y,p+"[%d]"%i,out,lim)
elif a!=b: out.append((p,str(a)[:120],str(b)[:120]))
return out
NOISE=("file_sha256","transaction_id","sha256","generated","created_at","input_digests","bundle_sha","manifest_sha","_sha256")
def cmp(name,docs,show=8):
print("==",name)
c,fc=go("CUR",docs); v,fv=go("V2",docs)
print(" CUR",{k:c.get(k) for k in("R0","F0","S0","man")})
print(" V2 ",{k:v.get(k) for k in("R0","F0","S0","man")})
if str(c.get("S0")).startswith("READY") and str(v.get("S0")).startswith("READY"):
a,b=sigdocs(fc),sigdocs(fv); dd=[d for d in ddiff(a,b) if not any(n in d[0] for n in NOISE)]
print(" diff",len(dd));
for d in dd[:show]: print(" ",d)
return c,fc,v,fv
@@ -0,0 +1,164 @@
import sys
DA=sys.argv[1]
def sub(s,o,n,c=1):
assert s.count(o)==c,(o,s.count(o))
return s.replace(o,n)
# ---- adapter
a=open(DA+'/signals/adapters/s3_domain_seed_adapter.py',encoding='utf-8').read()
a=sub(a,'''def _candidate(domain_id: str,''','''_SEED_ROW_KEYS = ("source_id", "source_kind", "excerpt", "payload")
_EFFECT_ROW_KEYS = ("type_id", "source_refs", "registered", "review_code", "candidate_ref", "bo_absent")
_CALCULATION_ROW_KEYS = ("calculation_domain", "completeness", "source_refs", "review_code")
def _schema_row(row: dict[str, Any], keys: tuple[str, ...]) -> dict[str, Any]:
"""S0 restores raw rows. Keys outside the seed schema must not reach signal consumers.
The worker's values stay in worker_extra as JSON text, so no key inside it can act as a field.
"""
kept = {name: value for name, value in row.items() if name in keys}
extra = {name: value for name, value in row.items() if name not in keys}
if extra:
kept["worker_extra"] = json.dumps(extra, ensure_ascii=False, sort_keys=True)
return kept
def _without(row: dict[str, Any], key: str) -> dict[str, Any]:
return {name: value for name, value in row.items() if name != key}
def _candidate(domain_id: str,''')
a=sub(a,'"details": {"source_seed_id": seed_id, **deepcopy(details)},','"details": {"source_seed_id": seed_id, **_schema_row(deepcopy(details), _EFFECT_ROW_KEYS if record_type == "legal_effect_route" else _SEED_ROW_KEYS)},')
a=sub(a,', refs, defense, universe, str(defense.get("status") or "inferred")))',', refs, defense, universe))')
a=sub(a,''' stamped.update({
"request_id"''',''' stamped = _schema_row(_without(stamped, "bo_absent"), _CALCULATION_ROW_KEYS)
stamped.update({
"request_id"''')
a=sub(a,'marked = {**effect, "candidate_ref": candidate_ref, **bo_mark}','marked = {**_without(effect, "bo_absent"), "candidate_ref": candidate_ref, **bo_mark}')
if 'import json' not in a: a=sub(a,'from copy import deepcopy\n','from copy import deepcopy\nimport json\n')
open('new/signals/adapters/s3_domain_seed_adapter.txt','w',encoding='utf-8').write(a)
# ---- structure compiler
c=open(DA+'/stage1_runtime/structure_index_compiler.py',encoding='utf-8').read()
c=sub(c,''' attached_here = False
for domain_id in resolved:
for type_id in keywords:
record = records.get((domain_id, type_id))
if record is not None:
attached_here = True
if isinstance(bo_id, str) and bo_id not in record["source_bo_ids"]:
record["source_bo_ids"].append(bo_id)
record["source_bo_ids"].sort()
''',''' attached_here = False
# 도메인을 건너 병합된 BO — 유형마다 그 유형을 낸 도메인에만 붙인다. F0 가 provenance 에 남긴다.
absorbed_sources = [_dict(row) for row in provenance.get("absorbed_sources") or []]
own_keywords = _strings(provenance.get("source_keywords")) if absorbed_sources else keywords
pairs = [(domain_id, type_id) for domain_id in resolved for type_id in own_keywords]
for source in absorbed_sources:
pairs.extend((domain_id, type_id)
for domain_id in resolve_source_domains(source.get("source_domain"), alias_targets, known_domain_ids)
for type_id in _strings(source.get("Legal_Keywords")))
for key in pairs:
record = records.get(key)
if record is not None:
attached_here = True
if isinstance(bo_id, str) and bo_id not in record["source_bo_ids"]:
record["source_bo_ids"].append(bo_id)
record["source_bo_ids"].sort()
''')
open('new/stage1_runtime/structure_index_compiler.txt','w',encoding='utf-8').write(c)
# ---- policy
p=open(DA+'/stage1_runtime/structure_index_policy.v1.json',encoding='utf-8').read()
p=sub(p,'t ∈ BO.Legal_Keywords 인 구조 레코드 (d, t) 에 source_bo_ids 로 부착을 시도한다.','t ∈ BO.Legal_Keywords 인 구조 레코드 (d, t) 에 source_bo_ids 로 부착을 시도한다. provenance.absorbed_sources 가 있으면 남는 도메인은 provenance.source_keywords 로, 흡수 도메인은 그 항목의 Legal_Keywords 로 시도하고, 그 도메인이 선언하지 않은 유형은 선언 도메인에 붙인다.')
open('new/stage1_runtime/structure_index_policy.v1.json','w',encoding='utf-8').write(p)
# ---- fact ledger compiler
f=open(DA+'/stage1_runtime/fact_ledger_compiler.py',encoding='utf-8').read()
head=' for record in attached:\n for ref in _strings(record.get("calculation_request_refs")):\n'
tail=' # (다) 증거력'
assert f.count(head)==1
i=f.index(head); j=f.index(tail,i)
body=f[i+len(head):j]
body=''.join(l[4:] if l.strip() else l for l in body.splitlines(True))
f=f[:i]+' # 계산 조인은 도메인 단위라 한 도메인의 레코드마다 같은 ref 가 있다. 행에는 한 번만 싣는다.\n for ref in sorted({ref for record in attached\n for ref in _strings(record.get("calculation_request_refs"))}):\n'+body+f[j:]
open('new/stage1_runtime/fact_ledger_compiler.txt','w',encoding='utf-8').write(f)
# ---- P2 YAML
y=open('p2_orig.yml',encoding='utf-8').read()
I=' '*18
y=sub(y,I+'''absorbed_keywords: list[str] = []
'''+I+'''for source_ref in absorbed_by.get(candidate_ref, []):
'''+I+''' value_refs.update(_strings(_dict(_dict(by_ref.get(source_ref)).get("seed_payload")).get("value_refs")))
'''+I+''' absorbed_keywords.extend(_strings(_dict(_dict(by_ref.get(source_ref)).get("seed_payload")).get("Legal_Keywords")))
''',I+'''absorbed_keywords: list[str] = []
'''+I+'''source_keywords = _keywords(seed, juristic)
'''+I+'''absorbed_domains: dict[str, list[str]] = {}
'''+I+'''for source_ref in absorbed_by.get(candidate_ref, []):
'''+I+''' absorbed_seed = _dict(_dict(by_ref.get(source_ref)).get("seed_payload"))
'''+I+''' seed_keywords = _strings(absorbed_seed.get("Legal_Keywords"))
'''+I+''' value_refs.update(_strings(absorbed_seed.get("value_refs")))
'''+I+''' absorbed_keywords.extend(seed_keywords)
'''+I+''' if absorbed_seed.get("source_domain") == seed.get("source_domain"):
'''+I+''' source_keywords.extend(seed_keywords)
'''+I+''' elif seed_keywords:
'''+I+''' absorbed_domains.setdefault(str(absorbed_seed.get("source_domain")), []).extend(seed_keywords)
''')
y=sub(y,I+'''bo_items.append({
'''+I+''' "BO_ID": bo_id,
''',I+'''provenance = {
'''+I+''' "source_event_candidate_ids": _strings(refs.get("source_event_candidate_ids")),
'''+I+''' "source_meeting_clause_ids": _strings(refs.get("source_meeting_clause_ids")),
'''+I+''' "source_domain": seed.get("source_domain"),
'''+I+'''}
'''+I+'''if absorbed_domains:
'''+I+''' # 도메인을 건너 병합된 BO — Part 3 조인이 유형마다 그 유형을 낸 도메인에만 붙인다.
'''+I+''' provenance["source_keywords"] = sorted(set(source_keywords))
'''+I+''' provenance["absorbed_sources"] = [{"source_domain": domain, "Legal_Keywords": sorted(set(keywords))}
'''+I+''' for domain, keywords in sorted(absorbed_domains.items())]
'''+I+'''bo_items.append({
'''+I+''' "BO_ID": bo_id,
''')
y=sub(y,I+''' "provenance": {
'''+I+''' "source_event_candidate_ids": _strings(refs.get("source_event_candidate_ids")),
'''+I+''' "source_meeting_clause_ids": _strings(refs.get("source_meeting_clause_ids")),
'''+I+''' "source_domain": seed.get("source_domain"),
'''+I+''' },
''',I+''' "provenance": provenance,
''')
y=sub(y,'if not isinstance(provenance, dict) or set(provenance.keys()) != {"source_event_candidate_ids", "source_meeting_clause_ids", "source_domain"}:','if not isinstance(provenance, dict) or set(provenance.keys()) - {"source_keywords", "absorbed_sources"} != {"source_event_candidate_ids", "source_meeting_clause_ids", "source_domain"}:')
y=sub(y,''' cand["candidate_ref"] = "%s:%03d" % (domain_id, position)
if cand["candidate_ref"] not in bo_refs:''',''' cand["candidate_ref"] = "%s:%03d" % (domain_id, position)
cand.pop("bo_absent", None) # 수용 전 worker 값이 남는 경로(shadow·검증기 미가용)가 있다
if cand["candidate_ref"] not in bo_refs:''')
open('p2_new.yml','w',encoding='utf-8').write(y)
# ---- 2회차 수정 통합
a=open('new/signals/adapters/s3_domain_seed_adapter.txt',encoding='utf-8').read()
def sub(s,o,n):
assert s.count(o)==1,o
return s.replace(o,n)
a=sub(a,'element_rows.append(_known_refs_only(fact, universe, removed))','element_rows.append(_schema_row(_known_refs_only(fact, universe, removed), _SEED_ROW_KEYS))')
a=sub(a,'opposing_rows.append(_known_refs_only(fact, universe, removed))','opposing_rows.append(_schema_row(_known_refs_only(fact, universe, removed), _SEED_ROW_KEYS))')
a=sub(a,'defense_rows.append(_known_refs_only(defense, universe, removed))','defense_rows.append(_schema_row(_known_refs_only(defense, universe, removed), _SEED_ROW_KEYS))')
a=sub(a,', refs, defense, universe))',', refs, defense, universe, "inferred" if defense.get("status") in (None, "inferred", "observed") else "review"))')
a=sub(a,'refs = [str(ref) for ref in _rows(defense.get("source_refs", seed_refs))]','refs = seed_refs')
a=sub(a,'"calculation_id": request.get("calculation_domain") or request.get("calculation_id"),','"calculation_id": request.get("calculation_domain"),')
a=sub(a,'kept["worker_extra"] = json.dumps(extra, ensure_ascii=False, sort_keys=True)','kept["worker_extra"] = json.dumps(extra, ensure_ascii=False, sort_keys=True).encode("utf-8", "backslashreplace").decode("utf-8")')
c=open('new/stage1_runtime/structure_index_compiler.txt',encoding='utf-8').read()
c=sub(c,''' for key in pairs:
record = records.get(key)
if record is not None:
attached_here = True
if isinstance(bo_id, str) and bo_id not in record["source_bo_ids"]:
record["source_bo_ids"].append(bo_id)
record["source_bo_ids"].sort()
''',''' if absorbed_sources:
# 그 도메인이 선언하지 않은 유형의 route 는 L0-4 가 선언 도메인에 붙였다. BO 도 같은 곳에 붙인다.
pairs = [target for key in pairs for target in
([key] if key in records else
[(d, key[1]) for d in declaring_domains.get(key[1], []) if (d, key[1]) in records])]
for key in pairs:
record = records.get(key)
if record is not None:
attached_here = True
if isinstance(bo_id, str) and bo_id not in record["source_bo_ids"]:
record["source_bo_ids"].append(bo_id)
record["source_bo_ids"].sort()
''')
open('new/signals/adapters/s3_domain_seed_adapter.txt','w',encoding='utf-8').write(a); open('new/stage1_runtime/structure_index_compiler.txt','w',encoding='utf-8').write(c)
@@ -0,0 +1,129 @@
import sys
DA=sys.argv[1]
def sub(s,o,n,c=1):
assert s.count(o)==c,(o,s.count(o))
return s.replace(o,n)
# ---- adapter
a=open(DA+'/signals/adapters/s3_domain_seed_adapter.py',encoding='utf-8').read()
a=sub(a,'''def _candidate(domain_id: str,''','''_SEED_ROW_KEYS = ("source_id", "source_kind", "excerpt", "payload")
_EFFECT_ROW_KEYS = ("type_id", "source_refs", "registered", "review_code", "candidate_ref", "bo_absent")
_CALCULATION_ROW_KEYS = ("calculation_domain", "completeness", "source_refs", "review_code")
def _schema_row(row: dict[str, Any], keys: tuple[str, ...]) -> dict[str, Any]:
"""S0 restores raw rows. Keys outside the seed schema must not reach signal consumers.
The worker's values stay in worker_extra as JSON text, so no key inside it can act as a field.
"""
kept = {name: value for name, value in row.items() if name in keys}
extra = {name: value for name, value in row.items() if name not in keys}
if extra:
kept["worker_extra"] = json.dumps(extra, ensure_ascii=False, sort_keys=True)
return kept
def _without(row: dict[str, Any], key: str) -> dict[str, Any]:
return {name: value for name, value in row.items() if name != key}
def _candidate(domain_id: str,''')
a=sub(a,'"details": {"source_seed_id": seed_id, **deepcopy(details)},','"details": {"source_seed_id": seed_id, **_schema_row(deepcopy(details), _EFFECT_ROW_KEYS if record_type == "legal_effect_route" else _SEED_ROW_KEYS)},')
a=sub(a,', refs, defense, universe, str(defense.get("status") or "inferred")))',', refs, defense, universe))')
a=sub(a,''' stamped.update({
"request_id"''',''' stamped = _schema_row(_without(stamped, "bo_absent"), _CALCULATION_ROW_KEYS)
stamped.update({
"request_id"''')
a=sub(a,'marked = {**effect, "candidate_ref": candidate_ref, **bo_mark}','marked = {**_without(effect, "bo_absent"), "candidate_ref": candidate_ref, **bo_mark}')
if 'import json' not in a: a=sub(a,'from copy import deepcopy\n','from copy import deepcopy\nimport json\n')
open('new/signals/adapters/s3_domain_seed_adapter.txt','w',encoding='utf-8').write(a)
# ---- structure compiler
c=open(DA+'/stage1_runtime/structure_index_compiler.py',encoding='utf-8').read()
c=sub(c,''' attached_here = False
for domain_id in resolved:
for type_id in keywords:
record = records.get((domain_id, type_id))
if record is not None:
attached_here = True
if isinstance(bo_id, str) and bo_id not in record["source_bo_ids"]:
record["source_bo_ids"].append(bo_id)
record["source_bo_ids"].sort()
''',''' attached_here = False
# 도메인을 건너 병합된 BO — 유형마다 그 유형을 낸 도메인에만 붙인다. F0 가 provenance 에 남긴다.
absorbed_sources = [_dict(row) for row in provenance.get("absorbed_sources") or []]
own_keywords = _strings(provenance.get("source_keywords")) if absorbed_sources else keywords
pairs = [(domain_id, type_id) for domain_id in resolved for type_id in own_keywords]
for source in absorbed_sources:
pairs.extend((domain_id, type_id)
for domain_id in resolve_source_domains(source.get("source_domain"), alias_targets, known_domain_ids)
for type_id in _strings(source.get("Legal_Keywords")))
for key in pairs:
record = records.get(key)
if record is not None:
attached_here = True
if isinstance(bo_id, str) and bo_id not in record["source_bo_ids"]:
record["source_bo_ids"].append(bo_id)
record["source_bo_ids"].sort()
''')
open('new/stage1_runtime/structure_index_compiler.txt','w',encoding='utf-8').write(c)
# ---- policy
p=open(DA+'/stage1_runtime/structure_index_policy.v1.json',encoding='utf-8').read()
p=sub(p,'t ∈ BO.Legal_Keywords 인 구조 레코드 (d, t) 에 source_bo_ids 로 부착을 시도한다.','t ∈ BO.Legal_Keywords 인 구조 레코드 (d, t) 에 source_bo_ids 로 부착을 시도한다. provenance.absorbed_sources 가 있으면 남는 도메인은 provenance.source_keywords 로, 흡수 도메인은 그 항목의 Legal_Keywords 로 시도한다.')
open('new/stage1_runtime/structure_index_policy.v1.json','w',encoding='utf-8').write(p)
# ---- fact ledger compiler
f=open(DA+'/stage1_runtime/fact_ledger_compiler.py',encoding='utf-8').read()
head=' for record in attached:\n for ref in _strings(record.get("calculation_request_refs")):\n'
tail=' # (다) 증거력'
assert f.count(head)==1
i=f.index(head); j=f.index(tail,i)
body=f[i+len(head):j]
body=''.join(l[4:] if l.strip() else l for l in body.splitlines(True))
f=f[:i]+' # 계산 조인은 도메인 단위라 한 도메인의 레코드마다 같은 ref 가 있다. 행에는 한 번만 싣는다.\n for ref in sorted({ref for record in attached\n for ref in _strings(record.get("calculation_request_refs"))}):\n'+body+f[j:]
open('new/stage1_runtime/fact_ledger_compiler.txt','w',encoding='utf-8').write(f)
# ---- P2 YAML
y=open('p2_orig.yml',encoding='utf-8').read()
I=' '*18
y=sub(y,I+'''absorbed_keywords: list[str] = []
'''+I+'''for source_ref in absorbed_by.get(candidate_ref, []):
'''+I+''' value_refs.update(_strings(_dict(_dict(by_ref.get(source_ref)).get("seed_payload")).get("value_refs")))
'''+I+''' absorbed_keywords.extend(_strings(_dict(_dict(by_ref.get(source_ref)).get("seed_payload")).get("Legal_Keywords")))
''',I+'''absorbed_keywords: list[str] = []
'''+I+'''source_keywords = _keywords(seed, juristic)
'''+I+'''absorbed_domains: dict[str, list[str]] = {}
'''+I+'''for source_ref in absorbed_by.get(candidate_ref, []):
'''+I+''' absorbed_seed = _dict(_dict(by_ref.get(source_ref)).get("seed_payload"))
'''+I+''' seed_keywords = _strings(absorbed_seed.get("Legal_Keywords"))
'''+I+''' value_refs.update(_strings(absorbed_seed.get("value_refs")))
'''+I+''' absorbed_keywords.extend(seed_keywords)
'''+I+''' if absorbed_seed.get("source_domain") == seed.get("source_domain"):
'''+I+''' source_keywords.extend(seed_keywords)
'''+I+''' elif seed_keywords:
'''+I+''' absorbed_domains.setdefault(str(absorbed_seed.get("source_domain")), []).extend(seed_keywords)
''')
y=sub(y,I+'''bo_items.append({
'''+I+''' "BO_ID": bo_id,
''',I+'''provenance = {
'''+I+''' "source_event_candidate_ids": _strings(refs.get("source_event_candidate_ids")),
'''+I+''' "source_meeting_clause_ids": _strings(refs.get("source_meeting_clause_ids")),
'''+I+''' "source_domain": seed.get("source_domain"),
'''+I+'''}
'''+I+'''if absorbed_domains:
'''+I+''' # 도메인을 건너 병합된 BO — Part 3 조인이 유형마다 그 유형을 낸 도메인에만 붙인다.
'''+I+''' provenance["source_keywords"] = sorted(set(source_keywords))
'''+I+''' provenance["absorbed_sources"] = [{"source_domain": domain, "Legal_Keywords": sorted(set(keywords))}
'''+I+''' for domain, keywords in sorted(absorbed_domains.items())]
'''+I+'''bo_items.append({
'''+I+''' "BO_ID": bo_id,
''')
y=sub(y,I+''' "provenance": {
'''+I+''' "source_event_candidate_ids": _strings(refs.get("source_event_candidate_ids")),
'''+I+''' "source_meeting_clause_ids": _strings(refs.get("source_meeting_clause_ids")),
'''+I+''' "source_domain": seed.get("source_domain"),
'''+I+''' },
''',I+''' "provenance": provenance,
''')
y=sub(y,'if not isinstance(provenance, dict) or set(provenance.keys()) != {"source_event_candidate_ids", "source_meeting_clause_ids", "source_domain"}:','if not isinstance(provenance, dict) or set(provenance.keys()) - {"source_keywords", "absorbed_sources"} != {"source_event_candidate_ids", "source_meeting_clause_ids", "source_domain"}:')
y=sub(y,''' cand["candidate_ref"] = "%s:%03d" % (domain_id, position)
if cand["candidate_ref"] not in bo_refs:''',''' cand["candidate_ref"] = "%s:%03d" % (domain_id, position)
cand.pop("bo_absent", None) # 수용 전 worker 값이 남는 경로(shadow·검증기 미가용)가 있다
if cand["candidate_ref"] not in bo_refs:''')
open('p2_new.yml','w',encoding='utf-8').write(y)
@@ -0,0 +1,85 @@
import re,sys
s=open('p3_orig.yml',encoding='utf-8').read()
IND=' '*10
def ind(t): return ''.join((IND+l if l.strip() else l) for l in t.splitlines(True))
HELP=ind('''def _raw_text(value):
return json.dumps(value, ensure_ascii=False, sort_keys=True)[:200]
def normalize_route_fields(rows):
# S0 는 효과 행을 worker 원본으로 싣는다. 닫힌 스키마가 받지 못하는 두 칸을 이 사본에서만 고친다.
# 봉인된 SG-13 파일과 L2 의 route 총수는 그대로다. 온전한 원값은 SG-13 에 남는다.
# type_id null 로 바꿔 Θ 밖 경로로 보낸다. 앞 200자는 그 review 항목의 raw_type_id 에 싣는다.
# source_seed_id 붙은 route 에는 review 항목이 없어 JSON 문자열로 칸에 남긴다.
normalized = []
raw_type_ids = {}
raw_seed_ids = {}
for row in rows:
details = row.get("details")
if row.get("record_type") != "legal_effect_route" or not isinstance(details, dict):
normalized.append(row)
continue
signal_id = str(row.get("signal_id"))
fixed = dict(details)
type_id = details.get("type_id")
if type_id is not None and not isinstance(type_id, str):
raw_type_ids[signal_id] = _raw_text(type_id)
fixed["type_id"] = None
seed_id = details.get("source_seed_id")
if seed_id is not None and not isinstance(seed_id, str):
raw_seed_ids[signal_id] = _raw_text(seed_id)
fixed["source_seed_id"] = raw_seed_ids[signal_id]
normalized.append(dict(row, details=fixed))
return normalized, raw_type_ids, raw_seed_ids
def mark_route_gaps(bundle, review_items, review_code, raw_seed_ids):
# 표시만 한다. 부착과 등식은 바꾸지 않는다.
# structure_routes_without_bo 도메인을 건너 병합된 BO 는 남은 도메인에만 붙는다.
# route_source_seed_id_not_string 후보를 추적할 수 없는 route 다.
for record in bundle.get("structure_records") or []:
routes = record.get("routes") or []
found = []
if routes and not record.get("source_bo_ids") and review_code not in record["review_codes"]:
found.append({"detail": "structure_routes_without_bo"})
for ref in routes:
signal_id = str(ref.get("signal_id"))
if signal_id in raw_seed_ids:
found.append({"detail": "route_source_seed_id_not_string", "signal_id": signal_id})
if not found:
continue
for extra in found:
item = {"review_code": review_code, "severity": "SOFT_WARNING",
"domain_id": record.get("domain_id"), "type_id": record.get("type_id")}
item.update(extra)
review_items.append(item)
if review_code not in record["review_codes"]:
record["review_codes"].append(review_code)
record["review_codes"].sort()
record["review_required"] = True
''')
def rep(o,n,c=1):
global s
assert s.count(o)>=c,o
s=s.replace(o,n,c) if c==1 else s.replace(o,n)
# L0 main only: first 'def main():' after gate_manifest
anchor=IND+'def main():\n'+IND+' gate_manifest = assert_deployment()\n'
rep(anchor,HELP+anchor)
rep(IND+' sg13_records = records_of(read_json(SG13_PATH))\n',
IND+' sg13_records, raw_type_ids, raw_seed_ids = normalize_route_fields(\n'+IND+' records_of(read_json(SG13_PATH)))\n')
rep(IND+' review_items = result["review_items"]\n',
IND+' review_items = result["review_items"]\n'+
IND+' for item in review_items:\n'+
IND+' if str(item.get("signal_id")) in raw_type_ids:\n'+
IND+' item["raw_type_id"] = raw_type_ids[str(item.get("signal_id"))]\n'+
IND+' mark_route_gaps(bundle, review_items, structure_index_compiler.REVIEW_ROUTE_NO_BO, raw_seed_ids)\n'+
IND+' if review_items:\n'+
IND+' bundle["status"] = "READY_WITH_REVIEW"\n')
rep('"input_gaps": audit.get("input_gaps"),\n','"input_gaps": audit.get("input_gaps"),\n'+IND+' "raw_type_id_routes": sorted(raw_type_ids),\n'+IND+' "raw_source_seed_id_routes": sorted(raw_seed_ids),\n')
old='"배포 원본 extension_research/Default_Agent 트리를 서버 Default_Agent/ 에 통째로 배포하고 "\n'+IND+' "runtime_manifest.json 의 등재·sha256 과 대조해 결손 경로를 복원한다. 부분 복사는 허용되지 않는다.")'
new='"배포 원본 extension_research/Default_Agent 의 미배포 파일 전체와 runtime_manifest.json 을 서버 Default_Agent/ 에 "\n'+IND+' "덮어쓰고 등재·sha256 과 대조해 결손 경로를 복원한다. 부분 복사와 삭제 동기화는 허용되지 않는다.")'
assert s.count(old)==2
s=s.replace(old,new)
open('p3_new.yml','w',encoding='utf-8').write(s)
@@ -0,0 +1,80 @@
s=open('p2_addendum.yml',encoding='utf-8').read()
I=' '*18
def R(o,n,c=1):
global s
assert s.count(o)==c,(o,s.count(o))
s=s.replace(o,n)
R(I+''' _removes = action in ("repair_harvest", "repair_evict")
''',I+''' _removes = action in ("repair_harvest", "repair_evict")
'''+I+''' evictions: list[tuple[list[Any], str, dict[str, Any]]] = []
''')
R(I+''' if not done and enum_unmapped == "repair_evict":
'''+I+''' rec["rule_id"] = "enum_unmapped:%s" % norm
'''+I+''' done = _evict(seed_obj, tokens, policy, norm, rec, quarantined)
''',I+''' if not done and enum_unmapped == "repair_evict":
'''+I+''' rec["rule_id"] = "enum_unmapped:%s" % norm
'''+I+''' evictions.append((tokens, norm, rec))
''')
R(I+''' if not done and derive_failed == "repair_evict":
'''+I+''' rec["rule_id"] = "derivation_failed:%s" % norm
'''+I+''' done = _evict(seed_obj, tokens, policy, norm, rec, quarantined)
''',I+''' if not done and derive_failed == "repair_evict":
'''+I+''' rec["rule_id"] = "derivation_failed:%s" % norm
'''+I+''' evictions.append((tokens, norm, rec))
''')
R(I+''' elif action == "repair_evict":
'''+I+''' rec["rule_id"] = "evict:%s" % norm
'''+I+''' done = _evict(seed_obj, tokens, policy, norm, rec, quarantined)
''',I+''' elif action == "repair_evict":
'''+I+''' rec["rule_id"] = "evict:%s" % norm
'''+I+''' evictions.append((tokens, norm, rec))
''')
R(I+''' if done:
'''+I+''' cand_idx = _candidate_index(tokens)
'''+I+''' if cand_idx is not None:
'''+I+''' cand = _list(seed_obj.get("bo_seed_candidates"))
'''+I+''' if cand_idx < len(cand):
'''+I+''' rec["candidate_ref"] = _dict(cand[cand_idx]).get("candidate_ref") or _dict(cand[cand_idx]).get("seed_id")
'''+I+''' records.append(rec)
'''+I+''' progressed = True
''',I+''' if done:
'''+I+''' _record_repair(seed_obj, tokens, rec, records)
'''+I+''' progressed = True
'''+I+''' # 행 제거는 값 처분이 끝난 뒤 내림차순으로, 행마다 한 번만 한다. 앞 행을 먼저 지우면 뒤 경로가 밀린다.
'''+I+''' evicted_rows: set[tuple[Any, ...]] = set()
'''+I+''' for tokens, norm, rec in sorted(evictions, key=lambda row: _path_sort_key(row[2]["path"]), reverse=True):
'''+I+''' row = list(tokens)
'''+I+''' while row and not isinstance(row[-1], int):
'''+I+''' row.pop()
'''+I+''' # 같은 행이나 바깥 행을 이미 처리했으면 이 경로는 다른 행을 가리킨다. 지우지 않고 기록만 남긴다.
'''+I+''' if any(tuple(row[:n]) in evicted_rows for n in range(1, len(row) + 1)):
'''+I+''' rec["applied"] = "quarantined_candidate" if len(row) == 2 and row[0] == "bo_seed_candidates" else "row_already_evicted"
'''+I+''' else:
'''+I+''' if not _evict(seed_obj, tokens, policy, norm, rec, quarantined):
'''+I+''' continue
'''+I+''' evicted_rows.add(tuple(row))
'''+I+''' _record_repair(seed_obj, tokens, rec, records)
'''+I+''' progressed = True
''')
R(I+''' for err in sorted(buckets.get(action) or [],
'''+I+''' key=lambda e: PATH_INDEX_RE.sub(
'''+I+''' lambda m: "[%05d]" % int(m.group(1)), str(e.get("path") or "")),
'''+I+''' reverse=_removes):
''',I+''' for err in sorted(buckets.get(action) or [],
'''+I+''' key=lambda e: _path_sort_key(e.get("path")),
'''+I+''' reverse=_removes):
''')
J=' '*10
R(J+'''def admit_seed(seed_obj, domain_id, schema,''',J+'''def _path_sort_key(path: Any) -> str:
'''+J+''' return PATH_INDEX_RE.sub(lambda m: "[%05d]" % int(m.group(1)), str(path or ""))
'''+J+'''def _record_repair(seed_obj, tokens, rec, records):
'''+J+''' cand_idx = _candidate_index(tokens)
'''+J+''' if cand_idx is not None:
'''+J+''' cand = _list(seed_obj.get("bo_seed_candidates"))
'''+J+''' if cand_idx < len(cand):
'''+J+''' rec["candidate_ref"] = _dict(cand[cand_idx]).get("candidate_ref") or _dict(cand[cand_idx]).get("seed_id")
'''+J+''' records.append(rec)
'''+J+'''def admit_seed(seed_obj, domain_id, schema,''')
open('p2_new.yml','w',encoding='utf-8').write(s)
@@ -0,0 +1,69 @@
exec(open('base2.py').read())
import traceback
SPATH=ROOT.parent/"2. Stage_2/Default_Agent/Stage_2_Clean/agent_scripts/Stage_2_S2_00.yml"
sl=open(SPATH,encoding="utf-8").read().split("\n")
_i=next(k for k,l in enumerate(sl) if "task_name: Task_S2_00_relationship_clusters" in l)
_j=next(k for k in range(_i,len(sl)) if sl[k].strip()=="code: |")
_ind=len(sl[_j+1])-len(sl[_j+1].lstrip()); _body=[]
for l in sl[_j+1:]:
if l.strip() and (len(l)-len(l.lstrip()))<_ind: break
_body.append(l[_ind:] if l.strip() else "")
_m=types.ModuleType("s200"); sys.modules["s200"]=_m
exec(compile("\n".join(_body),"s200","exec"),_m.__dict__)
S2=_m.__dict__
EX={}
_ov_b2=overlay
def overlay(mode):
r=_ov_b2(mode); r.update(EX); return r
F2T=code("Task_C_FL_F2_final_fact_ledger_gate_and_writer",p4)
def rootw(cs): return dict(seedroot(cs),registry_version=rv,registry_index_sha256=rsha)
def seedset(t,n=3,**kw):
out=[]
for i in range(1,n+1):
c=good(i); c["legal_effect_candidates"]=[L(type_id=t)] if t else []; c.update(kw); out.append(c)
return out
ADJ="stage1_tmp/task_c_bo/postb_adjudication_decisions.json"
def adjdoc(canon):
return json.dumps({"postb_exception_adjudication":{"schema_version":"task_c_bo_postb_exception_adjudication.v1","status":"READY","exception_count":len(canon),"canonical_decisions":canon,"field_decisions":[],"link_decisions":[],"semantic_gate_decisions":[],"blocked_review_items":[]}})
def P(docs,mode="V2",pre_f0=None,tamper=None,fl=True,s0=True,lzero=None,skipL=False):
"""R0 -> (pre_f0) -> F0 -> S0 -> L0 -> L2 -> FL F0 -> FL F2"""
cnt[0]+=1; tag="%s%d"%(mode,cnt[0]); fs=Fs(mode,docs); out={}
r0,f0,s0src=(R0SRC,F0SRC,S0SRC) if mode=="V2" else (OLD_R0,OLD_F0,OLD_S0)
out["_fs"]=fs
try: run_task(r0,fs,tag,"r"); out["R0"]="OK"
except BaseException as e: out["R0"]=type(e).__name__+":"+str(e)[:400]; return out
if pre_f0: pre_f0(fs)
try: run_task(f0,fs,tag+"f","f"); out["F0"]="OK"
except BaseException as e: out["F0"]=type(e).__name__+":"+str(e)[:500]; return out
try:
o=run_task(s0src,fs,tag+"s","s"); res=json.loads(o.strip().split("\n")[-1]); out["S0"]=res["status"]; out["man"]=res["manifest_status"]; out["res"]=res
except BaseException as e: out["S0"]=type(e).__name__+":"+str(e)[:500]; return out
if skipL: return out
wrapfs(fs)
if tamper: tamper(fs); reseal(fs)
seq=[("L0",lzero or L0),("L2",L2)]+([("FL",FL),("F2",F2T)] if fl else [])
for lab,src in seq:
cnt[0]+=1
try:
r=down(src,fs,"x%s%d"%(lab,cnt[0])); out[lab]=r.get("status")
if lab=="L0":
h=rj(fs,"quality_gates/stage1_part3_review_handoff.json")["stage1_part3_review_handoff"]
b=rj(fs,"stage1_tmp/task_le/structure_seed_bundle.json")["structure_seed_bundle"]
out["codes"]=dict(Counter("%s/%s"%(i.get("review_code"),str(i.get("severity"))[0]) for i in h["review_items"]))
out["counts"]={k:b["counts"][k] for k in("sg13_route_total","routes_attached","routes_unattached","bo_total","bo_attached","bo_unattached")}
out["_b"]=b; out["_h"]=h
except BaseException as e:
out[lab]="EXC %s %s"%(type(e).__name__,str(e)[:420]); break
return out
def recs(o): return [(x["domain_id"],x["type_id"],len(x["routes"]),x["source_bo_ids"],x["review_codes"]) for x in o["_b"]["structure_records"] if x["routes"] or x["source_bo_ids"]]
def S(o): return {k:(str(o.get(k))[:200]) for k in("R0","F0","S0","man","L0","L2","FL","F2") if k in o}
def boinfo(fs): return [(b["BO_ID"],b["provenance"]["source_domain"],b["Legal_Keywords"],b["provenance"].get("absorbed_sources")) for b in rj(fs,"BO.json")]
def p2h(fs): return rj(fs,"quality_gates/stage1_part2_review_handoff.json")
def p2items(fs,code=None):
h=p2h(fs); h=h.get("stage1_part2_review_handoff",h); it=h["review_items"]
return [i for i in it if code is None or i.get("source_review_code")==code]
_purge0=purge
def purge():
_purge0()
for k in list(sys.modules):
if k in("structure_index_compiler","fact_ledger_compiler"): del sys.modules[k]
@@ -0,0 +1,33 @@
exec(open('r1base.py').read())
def dseed(i,ts,act=None,**kw):
c=good(i); c["seed_id"]="s%d"%i; c["legal_effect_candidates"]=[L(type_id=t) for t in ts]
c["extensions"]={"domain_payload":{"action_summary":act or ("행위%d"%i),"action_type":"법률행위(legal acts)"}}
c.update(kw); return c
CALC=[{"calculation_domain":"CE-01","completeness":"ready","source_refs":["EV-1"]}]
FC=(D/"stage1_runtime/fact_ledger_compiler.py").read_text(encoding="utf-8")
FIX=FC.replace(''' for record in attached:
for ref in _strings(record.get("calculation_request_refs")):
route_refs.append(ref)
''',''' for ref in sorted({ref for record in attached
for ref in _strings(record.get("calculation_request_refs"))}):
if True:
route_refs.append(ref)
''')
assert FIX!=FC
sc={"A 단일도메인 2유형+계산(병합없음)":{"E-02":[dseed(1,["money_claim","general_legal_effect"],calculation_requests=CALC)]},
"B 병합 후 흡수도메인 2유형+계산":{"E-02":[dseed(1,["money_claim"],"같은행위")],"E-03":[dseed(1,["money_claim","commercial_successor"],"같은행위",calculation_requests=CALC)]},
"C 정상 병합 1유형씩+계산":{"E-02":[dseed(1,["money_claim"],"같은행위")],"E-03":[dseed(1,["commercial_successor"],"같은행위",calculation_requests=CALC)]},
"D 교차부착+계산":{"E-02":[dseed(1,["general_legal_effect"],"같은행위",calculation_requests=CALC)],"E-03":[dseed(1,["money_claim"],"같은행위")]}}
def row(o):
fs=o["_fs"]
if "Fact_Ledger_base.json" not in fs.docs:
b=[k for k in fs.docs if "fact_ledger" in k.lower() or k.startswith("stage1_tmp/task_fl")]
return "no ledger "+str(b[:4])
fl=json.loads(fs.docs["Fact_Ledger_base.json"]); return [(r["source_bo_id"],[c.get("request_id") for c in r["calculation_requests"]]) for r in fl]
for nm,roots in sc.items():
for lab,m,ex in (("현행","CUR",{}),("시안","V2",{}),("시안+Part4 수정","V2",{"Default_Agent/stage1_runtime/fact_ledger_compiler.txt":FIX})):
EX.clear(); EX.update(ex)
o=P(multi_docs({k:rootw(v) for k,v in roots.items()},act=mkact(list(roots))),mode=m)
print(nm,"|",lab,"| FL",str(o.get("FL"))[:30],"| F2",str(o.get("F2"))[:130],"|",row(o),"|",recs(o) if "_b" in o else "")
EX.clear()
open("fc_fix.txt","w",encoding="utf-8").write(FIX)
@@ -0,0 +1,13 @@
exec(open('r1base.py').read())
def dseed(i,t,act=None,**kw):
c=good(i); c["seed_id"]="s%d"%i; c["legal_effect_candidates"]=[L(type_id=t)] if t else []
c["extensions"]={"domain_payload":{"action_summary":act or ("행위%d"%i),"action_type":"법률행위(legal acts)"}}
c.update(kw); return c
def pf2(fs): fs.docs[ADJ]=adjdoc([{"decision":"MERGE","input_candidate_refs":["E-03:001","E-02:001"],"merge_target_ref":"E-02:001"}])
o=P(multi_docs({"E-02":rootw([dseed(1,"money_claim")]),"E-03":rootw([dseed(2,"commercial_successor")])},act=mkact(["E-02","E-03"])),pre_f0=pf2)
b=rj(o["_fs"],"BO.json"); print("R1 MERGE evidence",[(x["source_evidence_indexes"],x["provenance"]["source_domain"]) for x in b],dict(Counter(i.get("issue_type") for i in p2items(o["_fs"]))))
o=P(multi_docs({"E-02":rootw([dseed(1,"money_claim",calculation_requests=[{"calculation_domain":"CE-01","completeness":"ready","source_refs":["EV-1"],"missing_operands":["위조값"]}])])},act=mkact()))
fl=json.loads(o["_fs"].docs["Fact_Ledger_base.json"]); print(json.dumps(fl[0]["calculation_requests"],ensure_ascii=False)[:220])
a=P(multi_docs({"E-02":rootw([good(1)])},act=mkact()),mode="CUR"); b=P(multi_docs({"E-02":rootw([good(1)])},act=mkact()),mode="V2")
for k in ("validation_assets/routing/part3_receipt.json","validation_assets/routing/part4_receipt.json"):
print(k[-18:],[d[0] for d in ddiff(rj(a["_fs"],k),rj(b["_fs"],k))])
@@ -0,0 +1,24 @@
exec(open('r1base.py').read())
# 1. 어떤 worker 키가 어떤 signal 행의 어떤 칸까지 내려가나 (행별 전수)
K=dict(source_seed_id="FORGED",candidate_ref="E-99:999",bo_absent=True,request_id="E-99:999:1",signal_id="SIG-FORGED",record_type="fake",status="missing_required",review_required=True,
domain_ids=["E-99"],source_bo_ids=["bh1"],source_fact_ids=["FF"],evidence_refs=["EV-3"],meeting_clause_refs=["MC-1"],negative_or_conflicting_refs=["EV-2"],law_version_refs=["LV"],
confidence="high",proof_grade="direct",operand_state="ready",calculation_id="CE-99",missing_operands=["forged"],blocked=True,blocking=True)
print(json.dumps({k:1 for k in K}))
def rows(fs,f): return rj(fs,"signals/"+f)["records"]
for dm in ("E-02","E-05"):
for rowname,mk in (("element",lambda:dict(element_fact_candidates=[ev(**K)])),("opposing",lambda:dict(opposing_fact_candidates=[ev(**K)])),("defense",lambda:dict(defense_candidates=[ev(**K)])),
("effect",lambda:dict(legal_effect_candidates=[L(**K)])),("calc",lambda:dict(calculation_requests=[dict({"calculation_domain":"CE-01","completeness":"partial","source_refs":["EV-1"]},**K)]))):
if dm=="E-05" and rowname not in("element",): continue
r=rootw([good(i) for i in range(1,8)]+[cand("a",**mk())])
docs=multi_docs({dm:r},act=mkact((dm,)))
o=P(docs,fl=True)
print("##",dm,rowname,S(o),o.get("codes"))
fs=o["_fs"]
if "S0" not in o or not str(o["S0"]).startswith("READY"): continue
for f in sorted(p[8:] for p in fs.docs if p.startswith("signals/") and p.endswith(".json") and "domain_signals" not in p and "manifest" not in p):
if "records" not in rj(fs,"signals/"+f): continue
for x in rows(fs,f):
dt=x["details"]
if dt.get("source_seed_id")=="a" or "E-02:008" in str(dt.get("candidate_ref")) or dt.get("candidate_ref")=="E-99:999" or "E-02:008" in str(x.get("signal_id")) or x.get("signal_id")=="SIG-FORGED":
print(" ",f[:22],"TOP",{k:x[k] for k in x if k!="details"})
print(" DET",{k:dt[k] for k in dt if k in K or k in("calculation_domain","completeness")})
@@ -0,0 +1,21 @@
exec(open('r1base.py').read())
def one(dm,row,kw,mode):
mk={"element":lambda:dict(element_fact_candidates=[ev(**kw)]),"effect":lambda:dict(legal_effect_candidates=[L(**kw)]),"defense":lambda:dict(defense_candidates=[ev(**kw)])}[row]()
r=rootw([good(i) for i in range(1,8)]+[cand("a",**mk)])
o=P(multi_docs({dm:r},act=mkact((dm,))),mode=mode,fl=False)
fs=o["_fs"]
view=None
if str(o.get("S0")).startswith("READY"):
view={p:rj(fs,p) for p in ("legal_effect_signals.json","case_liability_signals.json")}
view={k[:12]:(v.get("status"),v.get("bo_legal_effect_routes") or v.get("case_liability_signals")) for k,v in view.items()}
print(mode,dm,row,sorted(kw),"->",str(o.get("S0"))[:120],o.get("man"),"view",json.dumps(view,ensure_ascii=False)[:230] if view else None, "codes",o.get("codes"))
for mode in ("CUR","V2"):
one("E-02","element",dict(compatibility_key="c",relation_component={}),mode)
one("E-02","element",dict(compatibility_key="legacy-liability-0000",compatibility_order="x",relation_component={}),mode)
one("E-02","element",dict(compatibility_key="legacy-liability-0000",compatibility_order=0,relation_component={}),mode)
one("E-05","element",dict(compatibility_key="legacy-liability-0000",compatibility_order=0,relation_component={"related_bo_ids":["bh1"]},liability_component={"liability_candidate_type":"forged"}),mode)
one("E-02","effect",dict(compatibility_route={"bo_id":"bh1"}),mode)
one("E-02","effect",dict(compatibility_route={"bo_id":"bh1","type_id":"forged"},compatibility_order=0),mode)
one("E-02","defense",dict(status="missing_required"),mode)
one("E-02","defense",dict(payload={"status":"missing_required"}),mode)
one("E-02","element",dict(status="missing_required"),mode)
@@ -0,0 +1,36 @@
exec(open("r1base.py").read())
sl=slice_doc(); sl["stage_b_domain_slice"]["domain_declarations"]["structure_type_ids"]=["general_legal_effect","money_claim"]
slice_doc=lambda: copy.deepcopy(sl)
def st(r): return (r.get("man"),str(r.get("S0"))[:80],str(r.get("L0"))[:150],str(r.get("L2"))[:100],str(r.get("FL"))[:60],r.get("gate"))
def ids(r): return [(z["source_seed_id"]) for x in r["_b"]["structure_records"] for z in x["routes"] if z["source_seed_id"][0]!="g" ]
print("== forge")
for nm,x,m in (("seed str",[cand("a",legal_effect_candidates=[L(source_seed_id="forged")])],"V2"),("seed str old",[cand("a",legal_effect_candidates=[L(source_seed_id="forged")])],"CUR"),
("seed dict",[cand("a",legal_effect_candidates=[L(source_seed_id={"a":1})])],"V2"),
("elem seed",[cand("a",element_fact_candidates=[ev(source_seed_id="forged")])],"V2"),
("bo_absent eff",[cand("a",legal_effect_candidates=[L(bo_absent=True)])],"V2"),("bo_absent eff old",[cand("a",legal_effect_candidates=[L(bo_absent=True)])],"CUR"),
("bo_absent calc",[cand("a",calculation_requests=[{"calculation_domain":"CE-01","completeness":"ready","source_refs":["EV-1"],"bo_absent":True}])],"V2"),
("bo_absent cand",[cand("a",bo_absent=True)],"V2"),("cand ref cand",[cand("a",candidate_ref="E-02:999")],"V2")):
r=single(x,mode=m,fl=True); sg=rj(r["_fs"],"signals/legal_effect_routes.json")["records"]
print(nm,st(r),r.get("codes"),"seed",sorted(set(ids(r))),"absent",sum(1 for z in sg if z.get("details",{}).get("bo_absent")))
print("== merge")
def seedset(t,n=3):
out=[]
for i in range(1,n+1):
c=good(i); c["legal_effect_candidates"]=[L(type_id=t)]; out.append(c)
return out
def rootw(cs): return dict(seedroot(cs),registry_version=rv,registry_index_sha256=rsha)
for ds,tt in ((["E-02","E-03"],("money_claim","commercial_successor")),(["E-00","E-02"],("general_legal_effect","money_claim")),(["E-02","E-13"],("money_claim","fraudulent_transfer"))):
for m in ("CUR","V2"):
roots={d:rootw(seedset(t)) for d,t in zip(ds,tt)}
r=run("",multi_docs(roots,act=mkact(ds)),fl=True,mode=m); print(m,ds,st(r),r.get("codes"))
print(" recs",[(x["domain_id"],x["type_id"],len(x["routes"]),len(x["source_bo_ids"]),x["review_codes"]) for x in r["_b"]["structure_records"] if x["routes"] or x["source_bo_ids"]])
print(" prov",json.dumps(rj(r["_fs"],"BO.json")[0]["provenance"],ensure_ascii=False)[:170])
print("== regression bytes")
CASES={"clean":[],"null":[cand("a",legal_effect_candidates=[L(type_id=None)])],"unknown":[cand("a",legal_effect_candidates=[L(type_id="nonexistent_type")])],"reg false":[cand("a",legal_effect_candidates=[L(registered=False)])],
"calc":[cand("a",calculation_requests=[{"calculation_domain":"CE-01","completeness":"ready","source_refs":["EV-1"]}])],"blocked":[cand("b",element_fact_candidates=[ev(payload={"status":"missing_required"})])],
"gen":[cand("a",legal_effect_candidates=[L(type_id="general_legal_effect")])],"dup same dom":[cand("d3"),cand("d3")],"seed int":[cand(77)]}
for k,x in CASES.items():
a=single(x,mode="CUR",fl=True); b=single(x,fl=True)
da,db=a["_fs"].docs,b["_fs"].docs
diff=[p for p in sorted(set(da)|set(db)) if da.get(p)!=db.get(p) and not p.startswith("Default_Agent")]
print(k,"docs",len(db),"diff",diff[:8])
@@ -0,0 +1,45 @@
exec(open('r1base.py').read())
_G=Fs.get
MISS=set()
def _get(self,p):
if p in MISS: return None
return _G(self,p)
Fs.get=_get
F=dict(source_seed_id="FORGED_S",bo_absent=True)
def rows():
return dict(element_fact_candidates=[ev(**F)],defense_candidates=[ev(**F)],legal_effect_candidates=[L(**F)],calculation_requests=[dict({"calculation_domain":"CE-01","completeness":"partial","source_refs":["EV-1"]},**F)],opposing_fact_candidates=[ev(**F)])
def show(nm,cands,dm="E-02",extra=None):
r=rootw([good(i) for i in range(1,8)]+cands)
o=P(multi_docs({dm:r},act=mkact((dm,))),fl=False)
fs=o["_fs"]
print("##",nm,S(o),o.get("codes"))
if "p" in str(o.get("R0"))[:0]: pass
try: it=p2items(fs)
except Exception as e: print(" no handoff",e); return o
adm=[i for i in it if str(i.get("review_id","")).startswith("R0:admission")]
c=Counter(i.get("source_review_code") for i in adm); print(" admission codes",dict(c))
sap=[i for i in adm if i.get("source_review_code")=="SCHEMA_ADDITIONAL_PROPERTY"]
print(" SAP on forged",sum(1 for i in sap if "source_seed_id" in i.get("template_note","")+json.dumps(i,ensure_ascii=False) or "bo_absent" in json.dumps(i,ensure_ascii=False)), "sample",json.dumps(sap[:1],ensure_ascii=False)[:520] if sap else None)
if str(o.get("S0")).startswith("READY"):
sg=[x for x in rj(fs,"signals/legal_effect_routes.json")["records"] if x["details"].get("candidate_ref","").endswith(":008")]
print(" SG13",[(x["details"].get("source_seed_id"),x["details"].get("bo_absent")) for x in sg])
print(" raw seed has key", "FORGED_S" in fs.docs["runtime/domain_seed_outputs/%s.json"%dm], "admitted has", "FORGED_S" in fs.docs["stage1_tmp/task_c_bo/admitted_seeds/%s.json"%dm], "BO has","FORGED_S" in fs.docs["BO.json"])
print(" p3 route bo", [ (x["type_id"],len(x["routes"]),x["review_codes"]) for x in o["_b"]["structure_records"] if x["routes"]] if "_b" in o else None)
return o
print("=== A enforce"); show("enforce all rows",[cand("a",**rows())])
print("=== B shadow"); EX["Default_Agent/stage1_runtime/seed_admission_policy.v1.json"]=policy_mod(enforcement="shadow")["Default_Agent/stage1_runtime/seed_admission_policy.v1.json"]
show("shadow all rows",[cand("a",**rows())])
show("shadow cand bo_absent",[cand("a",bo_absent=True)])
show("shadow cand ref unknown",[cand("a",candidate_ref="E-02:999")])
show("shadow cand ref collide",[cand("a",candidate_ref="E-02:001")])
EX.clear()
print("=== C crash probes")
for nm,kw in (("seed dict",dict(seed_id={"x":1})),("seed list",dict(seed_id=["x"])),("refs dict",dict(source_refs=[{"x":1}])),("bo_type dict",dict(bo_type={"a":1})),("dep dict",dict(dependency_refs=[{"a":1}])),("elems nonlist",dict(element_fact_candidates="x")),("eff dictype",dict(legal_effect_candidates=[L(type_id={"a":1})])),("calc dict",dict(calculation_requests=[{"calculation_domain":{"a":1},"completeness":"ready","source_refs":["EV-1"]}])),("slot",dict(evidence_slot_status=[{"slot_id":{"a":1},"status":"filled","source_refs":[]}])),("rev",dict(review_items=[{"review_code":{"x":1},"severity":"review","reason":"r","source_refs":[]}])),("struct",dict(calculation_requests=[1],legal_effect_candidates=[2],element_fact_candidates=[3]))):
c=cand("a") ; c.update(kw); c.update({k:v for k,v in rows().items() if k not in kw})
show("crash? "+nm,[c])
print("=== D validator unavailable")
MISS.add("Default_Agent/stage1_runtime/worker_output_validator.txt")
show("no validator all rows",[cand("a",**rows())])
show("no validator cand bo_absent",[cand("a",bo_absent=True)])
show("no validator cand_ref",[cand("a",candidate_ref="E-02:001")])
MISS.clear()
@@ -0,0 +1,190 @@
## R1 MERGE cross CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "commercial_successor"], null]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## R1 MERGE cross V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "commercial_successor"], [{"source_domain": "E-03", "Legal_Keywords": ["commercial_successor"]}]]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, ['bh1'], [])]
unatt []
bo reviews []
## chain A>B>C CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 3, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 2} {'sg13_route_total': 3, 'routes_attached': 3, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-13", ["fraudulent_transfer", "money_claim", "commercial_successor"], null]]
recs [('E-02', 'money_claim', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO']), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO']), ('E-13', 'fraudulent_transfer', 1, ['bh1'], [])]
unatt []
bo reviews []
## chain A>B>C V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 3} {'sg13_route_total': 3, 'routes_attached': 3, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-13", ["fraudulent_transfer", "money_claim", "commercial_successor"], [{"source_domain": "E-02", "Legal_Keywords": ["money_claim"]}, {"source_domain": "E-03", "Legal_Keywords": ["commercial_successor"]}]]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, ['bh1'], []), ('E-13', 'fraudulent_transfer', 1, ['bh1'], [])]
unatt []
bo reviews []
## exact+R1 chain CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 3, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 2} {'sg13_route_total': 3, 'routes_attached': 3, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-13", ["fraudulent_transfer", "commercial_successor", "money_claim"], null]]
recs [('E-02', 'money_claim', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO']), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO']), ('E-13', 'fraudulent_transfer', 1, ['bh1'], [])]
unatt []
bo reviews []
## exact+R1 chain V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 3} {'sg13_route_total': 3, 'routes_attached': 3, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-13", ["fraudulent_transfer", "commercial_successor", "money_claim"], [{"source_domain": "E-02", "Legal_Keywords": ["money_claim"]}, {"source_domain": "E-03", "Legal_Keywords": ["commercial_successor"]}]]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, ['bh1'], []), ('E-13', 'fraudulent_transfer', 1, ['bh1'], [])]
unatt []
bo reviews []
## mixed same+other CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 3, 'routes_attached': 3, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "general_legal_effect", "commercial_successor"], null]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO']), ('E-02', 'general_legal_effect', 1, ['bh1'], [])]
unatt []
bo reviews []
## mixed same+other V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2} {'sg13_route_total': 3, 'routes_attached': 3, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "general_legal_effect", "commercial_successor"], [{"source_domain": "E-03", "Legal_Keywords": ["commercial_successor"]}]]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, ['bh1'], []), ('E-02', 'general_legal_effect', 1, ['bh1'], [])]
unatt []
bo reviews []
## 3 domains exact CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 3, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 2} {'sg13_route_total': 3, 'routes_attached': 3, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "commercial_successor", "fraudulent_transfer"], null]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO']), ('E-13', 'fraudulent_transfer', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## 3 domains exact V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 3} {'sg13_route_total': 3, 'routes_attached': 3, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "commercial_successor", "fraudulent_transfer"], [{"source_domain": "E-03", "Legal_Keywords": ["commercial_successor"]}, {"source_domain": "E-13", "Legal_Keywords": ["fraudulent_transfer"]}]]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, ['bh1'], []), ('E-13', 'fraudulent_transfer', 1, ['bh1'], [])]
unatt []
bo reviews []
## survivor no kw CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_BO_UNATTACHED/H': 1, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 1, 'routes_attached': 1, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 0, 'bo_unattached': 1}
BO [["bh1", "E-02", ["commercial_successor"], null]]
recs [('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt [{'bo_id': 'bh1', 'reason': 'no_matching_structure'}]
bo reviews [{"bo_id": "bh1", "legal_keywords": ["commercial_successor"], "resolved_domains": ["E-02"], "review_code": "PART3_BO_UNATTACHED", "severity": "HARD_WARNING", "source_domain": "E-02"}]
## survivor no kw V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2} {'sg13_route_total': 1, 'routes_attached': 1, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["commercial_successor"], [{"source_domain": "E-03", "Legal_Keywords": ["commercial_successor"]}]]]
recs [('E-03', 'commercial_successor', 1, ['bh1'], [])]
unatt []
bo reviews []
## absorbed no kw CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2} {'sg13_route_total': 1, 'routes_attached': 1, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim"], null]]
recs [('E-02', 'money_claim', 1, ['bh1'], [])]
unatt []
bo reviews []
## absorbed no kw V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2} {'sg13_route_total': 1, 'routes_attached': 1, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim"], [{"source_domain": "E-03", "Legal_Keywords": []}]]]
recs [('E-02', 'money_claim', 1, ['bh1'], [])]
unatt []
bo reviews []
## both types undeclared in other CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'UNREGISTERED_EFFECT_TYPE_REVIEW/H': 2, 'PART3_BO_UNATTACHED/H': 1} {'sg13_route_total': 2, 'routes_attached': 0, 'routes_unattached': 2, 'bo_total': 1, 'bo_attached': 0, 'bo_unattached': 1}
BO [["bh1", "E-02", ["commercial_successor", "nope_type"], null]]
recs []
unatt [{'bo_id': 'bh1', 'reason': 'no_matching_structure'}]
bo reviews [{"bo_id": "bh1", "legal_keywords": ["commercial_successor", "nope_type"], "resolved_domains": ["E-02"], "review_code": "PART3_BO_UNATTACHED", "severity": "HARD_WARNING", "source_domain": "E-02"}]
## both types undeclared in other V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'UNREGISTERED_EFFECT_TYPE_REVIEW/H': 2, 'PART3_BO_UNATTACHED/H': 1} {'sg13_route_total': 2, 'routes_attached': 0, 'routes_unattached': 2, 'bo_total': 1, 'bo_attached': 0, 'bo_unattached': 1}
BO [["bh1", "E-02", ["commercial_successor", "nope_type"], [{"source_domain": "E-13", "Legal_Keywords": ["nope_type"]}]]]
recs []
unatt [{'bo_id': 'bh1', 'reason': 'no_matching_structure'}]
bo reviews [{"bo_id": "bh1", "legal_keywords": ["commercial_successor", "nope_type"], "resolved_domains": ["E-02"], "review_code": "PART3_BO_UNATTACHED", "severity": "HARD_WARNING", "source_domain": "E-02"}]
## cross attach money in E-02 CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["general_legal_effect", "money_claim"], null]]
recs [('E-02', 'money_claim', 0, ['bh1'], []), ('E-03', 'money_claim', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO']), ('E-02', 'general_legal_effect', 1, ['bh1'], [])]
unatt []
bo reviews []
## cross attach money in E-02 V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["general_legal_effect", "money_claim"], [{"source_domain": "E-03", "Legal_Keywords": ["money_claim"]}]]]
recs [('E-02', 'money_claim', 0, ['bh1'], []), ('E-03', 'money_claim', 1, ['bh1'], []), ('E-02', 'general_legal_effect', 1, ['bh1'], [])]
unatt []
bo reviews []
## same type both CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim"], null]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'money_claim', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## same type both V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim"], [{"source_domain": "E-03", "Legal_Keywords": ["money_claim"]}]]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'money_claim', 1, ['bh1'], [])]
unatt []
bo reviews []
## cycle CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 3, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 2} {'sg13_route_total': 3, 'routes_attached': 3, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-13", ["fraudulent_transfer"], null]]
recs [('E-02', 'money_claim', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO']), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO']), ('E-13', 'fraudulent_transfer', 1, ['bh1'], [])]
unatt []
bo reviews []
## cycle V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 3, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 2} {'sg13_route_total': 3, 'routes_attached': 3, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-13", ["fraudulent_transfer"], null]]
recs [('E-02', 'money_claim', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO']), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO']), ('E-13', 'fraudulent_transfer', 1, ['bh1'], [])]
unatt []
bo reviews []
## target unknown CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim"], null]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## target unknown V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim"], null]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## absorbed source_domain=None CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "commercial_successor"], null]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## absorbed source_domain=None V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "commercial_successor"], [{"source_domain": "None", "Legal_Keywords": ["commercial_successor"]}]]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## absorbed source_domain='' CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "commercial_successor"], null]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## absorbed source_domain='' V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "commercial_successor"], [{"source_domain": "", "Legal_Keywords": ["commercial_successor"]}]]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## absorbed source_domain='E-99' CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "commercial_successor"], null]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## absorbed source_domain='E-99' V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "commercial_successor"], [{"source_domain": "E-99", "Legal_Keywords": ["commercial_successor"]}]]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## absorbed source_domain=7 CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "commercial_successor"], null]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## absorbed source_domain=7 V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "commercial_successor"], [{"source_domain": "7", "Legal_Keywords": ["commercial_successor"]}]]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## absorbed source_domain=['E-03'] CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "commercial_successor"], null]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## absorbed source_domain=['E-03'] V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "commercial_successor"], [{"source_domain": "['E-03']", "Legal_Keywords": ["commercial_successor"]}]]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## absorbed source_domain='X1' CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "commercial_successor"], null]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## absorbed source_domain='X1' V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 1} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 1, 'bo_unattached': 0}
BO [["bh1", "E-02", ["money_claim", "commercial_successor"], [{"source_domain": "X1", "Legal_Keywords": ["commercial_successor"]}]]]
recs [('E-02', 'money_claim', 1, ['bh1'], []), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt []
bo reviews []
## survivor source_domain ZZZ CUR {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_BO_DOMAIN_UNRESOLVED/H': 1, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 2} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 0, 'bo_unattached': 1}
BO [["bh1", "ZZZ", ["money_claim", "commercial_successor"], null]]
recs [('E-02', 'money_claim', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO']), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt [{'bo_id': 'bh1', 'reason': 'source_domain_unresolved'}]
bo reviews [{"bo_id": "bh1", "review_code": "PART3_BO_DOMAIN_UNRESOLVED", "severity": "HARD_WARNING", "source_domain": "ZZZ"}]
## survivor source_domain ZZZ V2 {'R0': 'OK', 'F0': 'OK', 'S0': 'READY_WITH_REVIEW', 'man': 'READY', 'L0': 'READY_WITH_REVIEW', 'L2': 'READY_WITH_REVIEW', 'FL': 'READY_WITH_REVIEW', 'F2': 'READY_WITH_REVIEW'} {'PART3_SLICE_PROJECTION_DIVERGENCE/H': 2, 'PART3_BO_DOMAIN_UNRESOLVED/H': 1, 'PART3_ROUTE_CANDIDATE_NOT_IN_BO/S': 2} {'sg13_route_total': 2, 'routes_attached': 2, 'routes_unattached': 0, 'bo_total': 1, 'bo_attached': 0, 'bo_unattached': 1}
BO [["bh1", "ZZZ", ["money_claim", "commercial_successor"], [{"source_domain": "E-03", "Legal_Keywords": ["commercial_successor"]}]]]
recs [('E-02', 'money_claim', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO']), ('E-03', 'commercial_successor', 1, [], ['PART3_ROUTE_CANDIDATE_NOT_IN_BO'])]
unatt [{'bo_id': 'bh1', 'reason': 'source_domain_unresolved'}]
bo reviews [{"bo_id": "bh1", "review_code": "PART3_BO_DOMAIN_UNRESOLVED", "severity": "HARD_WARNING", "source_domain": "ZZZ"}]
@@ -0,0 +1,45 @@
exec(open('r1base.py').read())
def dseed(i,t,act=None,**kw):
c=good(i); c["seed_id"]="s%d"%i; c["legal_effect_candidates"]=[L(type_id=t)] if t else []
c["extensions"]={"domain_payload":{"action_summary":act or ("행위%d"%i),"action_type":"법률행위(legal acts)"}}
c.update(kw); return c
def scen(nm,roots,canon=(),pre=None,tamper=None):
ds=list(roots)
res={}
for m in ("CUR","V2"):
def pf(fs):
if canon: fs.docs[ADJ]=adjdoc(list(canon))
if pre: pre(fs)
o=P(multi_docs({k:rootw(v) for k,v in roots.items()},act=mkact(ds)),mode=m,pre_f0=pf,tamper=tamper)
fs=o["_fs"]; res[m]=o
print("##",nm,m,S(o),o.get("codes"),o.get("counts"))
if "BO.json" in fs.docs: print(" BO",json.dumps(boinfo(fs),ensure_ascii=False)[:420])
if "_b" in o:
print(" recs",recs(o)); print(" unatt",o["_b"]["unattached_bo"][:4])
rv_=[i for i in o["_h"]["review_items"] if i["review_code"] in("PART3_BO_UNATTACHED","PART3_BO_DOMAIN_UNRESOLVED")]
print(" bo reviews",json.dumps(rv_,ensure_ascii=False)[:300])
return res
T2,T3,T13="money_claim","commercial_successor","fraudulent_transfer"
scen("R1 MERGE cross",{"E-02":[dseed(1,T2)],"E-03":[dseed(2,T3)]},[{"decision":"MERGE","input_candidate_refs":["E-03:001","E-02:001"],"merge_target_ref":"E-02:001"}])
scen("chain A>B>C",{"E-02":[dseed(1,T2)],"E-03":[dseed(2,T3)],"E-13":[dseed(3,T13)]},[{"decision":"MERGE","input_candidate_refs":["E-02:001","E-03:001"],"merge_target_ref":"E-03:001"},{"decision":"MERGE","input_candidate_refs":["E-03:001","E-13:001"],"merge_target_ref":"E-13:001"}])
scen("exact+R1 chain",{"E-02":[dseed(1,T2,"같은행위")],"E-03":[dseed(1,T3,"같은행위")],"E-13":[dseed(3,T13)]},[{"decision":"MERGE","input_candidate_refs":["E-02:001","E-13:001"],"merge_target_ref":"E-13:001"}])
scen("mixed same+other",{"E-02":[dseed(1,T2),dseed(4,"general_legal_effect")],"E-03":[dseed(2,T3)]},[{"decision":"MERGE","input_candidate_refs":["E-02:002","E-03:001","E-02:001"],"merge_target_ref":"E-02:001"}])
scen("3 domains exact",{"E-02":[dseed(1,T2,"같은행위")],"E-03":[dseed(1,T3,"같은행위")],"E-13":[dseed(1,T13,"같은행위")]})
scen("survivor no kw",{"E-02":[dseed(1,None,"같은행위")],"E-03":[dseed(1,T3,"같은행위")]})
scen("absorbed no kw",{"E-02":[dseed(1,T2,"같은행위")],"E-03":[dseed(1,None,"같은행위")]})
scen("both types undeclared in other",{"E-02":[dseed(1,T3,"같은행위")],"E-13":[dseed(1,"nope_type","같은행위")]})
scen("cross attach money in E-02",{"E-02":[dseed(1,"general_legal_effect","같은행위")],"E-03":[dseed(1,"money_claim","같은행위")]})
scen("same type both",{"E-02":[dseed(1,"money_claim","같은행위")],"E-03":[dseed(1,"money_claim","같은행위")]})
scen("cycle",{"E-02":[dseed(1,T2)],"E-03":[dseed(2,T3)],"E-13":[dseed(3,T13)]},[{"decision":"MERGE","input_candidate_refs":["E-02:001","E-03:001"],"merge_target_ref":"E-03:001"},{"decision":"MERGE","input_candidate_refs":["E-03:001","E-02:001"],"merge_target_ref":"E-02:001"}])
scen("target unknown",{"E-02":[dseed(1,T2)],"E-03":[dseed(2,T3)]},[{"decision":"MERGE","input_candidate_refs":["E-03:001"],"merge_target_ref":"E-02:999"}])
def tam(val,which="E-03:001"):
def f(fs):
p="stage1_tmp/task_c_bo/postb_seed_ledger.json"; l=rj(fs,p)
for c in l["postb_seed_ledger"]["ledger_candidates"]:
if c["candidate_ref"]==which: c["seed_payload"]["source_domain"]=val; c["source_domain"]=val
fs.docs[p]=json.dumps(l,ensure_ascii=False)
return f
MG=[{"decision":"MERGE","input_candidate_refs":["E-03:001","E-02:001"],"merge_target_ref":"E-02:001"}]
for v in (None,"","E-99",7,["E-03"],"X1"):
scen("absorbed source_domain=%r"%(v,),{"E-02":[dseed(1,T2)],"E-03":[dseed(2,T3)]},MG,pre=tam(v))
scen("survivor source_domain ZZZ",{"E-02":[dseed(1,T2)],"E-03":[dseed(2,T3)]},MG,pre=tam("ZZZ","E-02:001"))
@@ -0,0 +1,48 @@
exec(open('r1base.py').read())
sl=slice_doc()
def dseed(i,t,act=None,**kw):
c=good(i); c["seed_id"]="s%d"%i; c["legal_effect_candidates"]=[L(type_id=t)] if t else []
c["extensions"]={"domain_payload":{"action_summary":act or ("행위%d"%i),"action_type":"법률행위(legal acts)"}}
c.update(kw); return c
SCH=lambda n: json.loads((D/"platform/schemas"/n).read_text(encoding="utf-8"))
def s2(fs):
docs={"bo":json.loads(fs.docs["BO.json"]),"fact_ledger_base":json.loads(fs.docs["Fact_Ledger_base.json"]),"legal_effect_structures":json.loads(fs.docs["legal_effect_structures.json"]),
"evidence_indexed":{"items":[{"evidence_index":e} for e in EV]},"evidence_event_candidates":{"items":[]}}
c=S2["check_conservation"](docs)
ck=[(k["check_id"],k["status"]) for k in c["checks"]]
hit=[]
for lg,dd in docs.items():
for p,v in S2["_walk_values"](dd):
if isinstance(v,dict) and (v.get("stage2_auto_progression_allowed") is False or v.get("blocking") is True or v.get("blocked") is True or str(v.get("status",v.get("handoff_status",""))).upper()=="BLOCKED"): hit.append(lg+"#"+p)
pj=S2["_project"](docs["bo"][0]) if "_project" in S2 else None
comp=S2["_compact"](docs["bo"][0])
sc={}
for name,lg in (("legal_effect_structures.schema.json","legal_effect_structures"),("fact_ledger_base.schema.json","fact_ledger_base")):
p=D/"platform/schemas"/name
if not p.exists(): sc[name]="absent"; continue
s=json.loads(p.read_text(encoding="utf-8"))
try: S2["_validate_schema_node"](docs[lg],s,root_schema=s,schema_documents={},instance_path=lg); sc[name]="PASS"
except BaseException as e: sc[name]="FAIL "+str(e)[:160]
return ck,hit,("absorbed" in json.dumps(pj,ensure_ascii=False)),("absorbed" in json.dumps(comp,ensure_ascii=False)),sc,[i.get("issue_code") for i in c["issues"]]
def fl(fs):
x=json.loads(fs.docs["Fact_Ledger_base.json"])
rows=x if isinstance(x,list) else x.get("fact_ledger_base") or x.get("records") or x.get("rows") or x
return rows
for nm,roots in (("merge E-02+E-03 calc",{"E-02":[dseed(1,"money_claim","같은행위")],"E-03":[dseed(1,"commercial_successor","같은행위",calculation_requests=[{"calculation_domain":"CE-01","completeness":"ready","source_refs":["EV-2"]}])]}),
("cross false attach",{"E-02":[dseed(1,"general_legal_effect","같은행위")],"E-03":[dseed(1,"money_claim","같은행위")]}),
("merge E-02+E-13",{"E-02":[dseed(1,"money_claim","같은행위")],"E-13":[dseed(1,"fraudulent_transfer","같은행위")]})):
for m in ("CUR","V2"):
o=P(multi_docs({k:rootw(v) for k,v in roots.items()},act=mkact(list(roots))),mode=m)
fs=o["_fs"]; print("##",nm,m,S(o),o.get("codes"))
if "Fact_Ledger_base.json" not in fs.docs: print(" no ledger",[k for k in fs.docs if "edger" in k][:8]); continue
rows=fl(fs)
rs=rows if isinstance(rows,list) else rows
print(" type",type(rs),(list(rs)[:8] if isinstance(rs,dict) else len(rs)))
ls=rs if isinstance(rs,list) else next((v for v in rs.values() if isinstance(v,list) and v and isinstance(v[0],dict) and "domain_effects" in v[0]),[])
for r in ls:
print(" row",{k:r.get(k) for k in("source_bo_id","must_consider","legal_centrality","legal_effect_roles","must_not_drop_in_claim_types","money_claim_effect","commercial_successor_effect","linked_actio_structures")},"dom",{k:v["type_ids"] for k,v in r["domain_effects"].items()},"calc",[c.get("request_id") for c in r["calculation_requests"]],"state",r["state_context"]["domain_ids"])
try:
cand=json.loads(fs.docs.get("stage1_tmp/task_fl/fact_ledger_candidate_bundle.json","{}"))
b=cand.get("fact_ledger_candidate_bundle",cand); print(" eq",json.dumps(b.get("equations") or b.get("conservation"),ensure_ascii=False)[:420]); print(" counts",json.dumps(b.get("counts"),ensure_ascii=False)[:330])
except Exception as e: print(" x",e)
print(" S2",s2(fs))
@@ -0,0 +1,56 @@
exec(open('r1base.py').read())
def dseed(i,t,act=None,**kw):
c=good(i); c["seed_id"]="s%d"%i; c["legal_effect_candidates"]=[L(type_id=t)] if t else []
c["extensions"]={"domain_payload":{"action_summary":act or ("행위%d"%i),"action_type":"법률행위(legal acts)"}}
c.update(kw); return c
print("=== Q6-a _duplicate_key + domain")
R0_ALT=R0SRC.replace(''' tuple(sorted(_strings(seed.get("value_refs")))),
)
def _normalize_juristic''',''' tuple(sorted(_strings(seed.get("value_refs")))),
seed.get("source_domain"),
)
def _normalize_juristic''')
assert R0_ALT!=R0SRC
_R=R0SRC
roots={"E-02":[dseed(1,"money_claim","같은행위")],"E-03":[dseed(1,"commercial_successor","같은행위")]}
for nm,src in (("현행키+F2",_R),("키에도메인",R0_ALT)):
R0SRC=src
o=P(multi_docs({k:rootw(v) for k,v in roots.items()},act=mkact(list(roots))))
fs=o["_fs"]; led=rj(fs,"stage1_tmp/task_c_bo/postb_seed_ledger.json")["postb_seed_ledger"]
print(nm,S(o),o.get("codes")); print(" BO",boinfo(fs)); print(" recs",recs(o)); print(" flags",[(c["candidate_ref"],c["flags"]) for c in led["ledger_candidates"]],"det",len(led["deterministic_decisions"]))
print(" p2 codes",dict(Counter(i.get("issue_type") for i in p2items(fs))))
fl=json.loads(fs.docs["Fact_Ledger_base.json"]); print(" ledger rows",len(fl),[ (r["source_bo_id"],r["action"],sorted(r["domain_effects"])) for r in fl])
R0SRC=_R
print("=== Q6-b M1 분기 도달 (F1 후)")
for v in ({"a":1},["x"],7,1.5,True,"forged"):
r=rootw([good(i) for i in range(1,8)]+[cand("a",legal_effect_candidates=[L(source_seed_id=v)])])
for st,mode in (("fix", "V2"),):
o=P(multi_docs({"E-02":r},act=mkact()),fl=False)
rc=rj(o["_fs"],"validation_assets/routing/part3_receipt.json")
print(repr(v),S(o).get("L2"),"raw_seed_routes",rc.get("raw_source_seed_id_routes"),[d.get("detail") for d in o["_h"]["review_items"] if d.get("detail")],sorted({z["source_seed_id"] for x in o["_b"]["structure_records"] for z in x["routes"] if z["source_seed_id"][0]!="g"}))
print("=== Q6-c structure_routes_without_bo 잔존")
for nm,x in (("registered yes",[cand("a",legal_effect_candidates=[L(type_id="general_legal_effect",registered="yes")])]),
("dict src ref",[cand("a",legal_effect_candidates=[L(type_id="general_legal_effect",source_refs=[{"a":1}])])]),
("cross domain route",[cand("a",legal_effect_candidates=[L(type_id="fraudulent_transfer")])]),
("type int + good",[cand("a",legal_effect_candidates=[L(type_id=7),L(type_id="general_legal_effect")])]),
("registered false",[cand("a",legal_effect_candidates=[L(type_id="general_legal_effect",registered=False)])])):
r=rootw([good(i) for i in range(1,8)]+x)
o=P(multi_docs({"E-02":r},act=mkact()),fl=False)
print(nm,S(o).get("L2"),o.get("codes")); print(" BO8",[b for b in boinfo(o["_fs"])][-1]); print(" det",[(d.get("detail"),d.get("type_id")) for d in o["_h"]["review_items"] if d.get("detail")],[y for y in recs(o) if y[1]!="money_claim"])
print("=== Q3-x 흡수 후보 meeting clause/evidence 손실")
c1=dseed(1,"money_claim","같은행위"); c2=dseed(1,"commercial_successor","같은행위",source_refs=["EV-2","MC-1"]); print(c1["source_refs"],c2["source_refs"])
o=P(multi_docs({"E-02":rootw([c1]),"E-03":rootw([c2])},act=mkact(["E-02","E-03"])))
print(S(o)); bo=rj(o["_fs"],"BO.json"); print(json.dumps([(b["BO_ID"],b["provenance"],b["source_evidence_indexes"]) for b in bo],ensure_ascii=False)[:500])
print("=== Q1 S2_00 details.source_bo_ids 절편")
import re as _r
det={"source_bo_ids":["bh1"],"source_id":"EVT-1"}
rec={"details":det,"evidence_refs":[],"source_bo_ids":[]}
bo_tag={"bh1":{"parties":{"피고갑"},"title":{"t"},"text":"BO본문","source_events":["EVT-1"]}}
_str_list=S2["_str_list"]
parts,title,src,text=set(),set(),[],""
for b_id in _str_list(rec.get("source_bo_ids")) + _str_list(det.get("source_bo_ids")):
bt=bo_tag.get(b_id)
if bt: parts|=bt["parties"]; title|=bt["title"]; text+=" "+bt["text"]; src+=bt["source_events"]
print("parts",parts,"src",src,"compact keeps details",S2["_compact"](dict(rec,record_type="legal_effect_route",status="inferred")))
@@ -0,0 +1,42 @@
exec(open('r1base.py').read())
_a=next(i for i,l in enumerate(pn) if "def assert_deployment" in l)
_st=_a
while "code: |" not in pn[_st]: _st-=1
_ind=len(pn[_st+1])-len(pn[_st+1].lstrip()); _b=[]
for l in pn[_st+1:]:
if l.strip() and (len(l)-len(l.lstrip()))<_ind: break
_b.append(l[_ind:] if l.strip() else "")
A0="\n".join(_b)
print("A0 lines",len(_b),[l for l in _b[:6]])
fs=Fs("V2",{})
nm=fs.get("Default_Agent/runtime_manifest.json")
def a0(src,fsx):
purge(); s=src.replace(" _init()\n RESULT = main()\n"," RESULT = None\n")
s=s.replace("if __name__ == \"__main__\":","if False:")
g=load(s,fsx,"a0x%d"%cnt[0]); cnt[0]+=1
g["_call"]=lambda n,a,m=None: fsx.call(n,a)
return g["assert_deployment"]()
# 시뮬레이션: 재봉인 후 상수 교체
newsha=hashlib.sha256(nm.encode()).hexdigest()
sres=[]
for lab,src,f in (("옛상수+새자산",A0,fs),("새상수+새자산",A0.replace("0cacaef800f1b3c1d75a1c84c42dc0bb312ab7aafe2262e3e15f32313b728d44",newsha),fs)):
try:
m=a0(src,f); print(lab,"PASS",len(m["entries"]))
except BaseException as e: print(lab,"EXC",str(e)[:190])
# 부분배포: manifest 만 새것, 컴파일러 옛것 -> Part2 는 통과? Part3 멈춤?
_FsG=Fs.get
class PF(Fs):
def get(self,p):
if p.endswith("structure_index_compiler.txt") or p.endswith("structure_index_policy.v1.json"):
return (D/p[len("Default_Agent/"):]).read_text(encoding="utf-8")
return _FsG(self,p)
pf=PF("V2",{})
try: a0(A0.replace("0cacaef800f1b3c1d75a1c84c42dc0bb312ab7aafe2262e3e15f32313b728d44",newsha),pf); print("부분배포 A0 PASS (compiler 옛것)")
except BaseException as e: print("부분배포 A0 EXC",str(e)[:200])
# 실행: L0 까지 가는가
_Fs=Fs; Fs=PF
o=P(multi_docs({"E-02":rootw([good(1)])},act=mkact()),fl=False); print("부분배포 pipeline",{k:str(v)[:230] for k,v in S(o).items()})
Fs=_Fs
# manifest 행 수, 변경행
m0=json.loads((D/"runtime_manifest.json").read_text(encoding="utf-8")); m1=json.loads(nm)
print("changed rows",[ (a["path"]) for a,b in zip(m0["entries"],m1["entries"]) if a["sha256"]!=b["sha256"]])
@@ -0,0 +1,20 @@
exec(open('r1base.py').read())
a=''' seed_id = details.get("source_seed_id")
if seed_id is not None and not isinstance(seed_id, str):
raw_seed_ids[signal_id] = _raw_text(seed_id)
fixed["source_seed_id"] = raw_seed_ids[signal_id]
'''
b=''' for ref in routes:
signal_id = str(ref.get("signal_id"))
if signal_id in raw_seed_ids:
found.append({"detail": "route_source_seed_id_not_string", "signal_id": signal_id})
'''
assert a in L0 and b in L0
Lr=L0.replace(a,"").replace(b,"")
print("reduced ok; ast"); import ast; ast.parse(Lr)
CASES={"clean":[],"seed dict":[cand("a",legal_effect_candidates=[L(source_seed_id={"x":1})])],"type dict":[cand("a",legal_effect_candidates=[L(type_id={"x":1})])],"both":[cand("a",legal_effect_candidates=[L(type_id={"x":1},source_seed_id=["y"])])],"reg yes":[cand("a",legal_effect_candidates=[L(type_id="general_legal_effect",registered="yes")])]}
for k,x in CASES.items():
r=rootw([good(i) for i in range(1,8)]+x)
A=P(multi_docs({"E-02":r},act=mkact()),fl=True); B=P(multi_docs({"E-02":r},act=mkact()),fl=True,lzero=Lr)
da,db=A["_fs"].docs,B["_fs"].docs
print(k,S(B).get("L2"),S(B).get("FL"),"diff",[p for p in sorted(set(da)|set(db)) if da.get(p)!=db.get(p)])
@@ -0,0 +1,42 @@
exec(open('r1base.py').read())
import random
rnd=random.Random(int(sys.argv[2]) if len(sys.argv)>2 else 20261031)
if len(sys.argv)>3: EX['Default_Agent/stage1_runtime/fact_ledger_compiler.txt']=open('fc_fix.txt',encoding='utf-8').read()
KEYS=dict(source_seed_id=["F",{"a":1},7,None],bo_absent=[True,False,"true",1],candidate_ref=["E-99:001",5],request_id=["R",9],signal_id=["S"],status=["review","contested"],domain_ids=[["E-13"]],review_required=[True])
TY=["money_claim","commercial_successor","general_legal_effect","fraudulent_transfer","nope",None,7,{"x":1}]
def row(mk):
kw={k:rnd.choice(v) for k,v in KEYS.items() if rnd.random()<.25}
return mk(**kw)
def seed(i,act):
c=good(i); c["seed_id"]="s%d"%i
c["extensions"]={"domain_payload":{"action_summary":act,"action_type":"법률행위(legal acts)"}}
c["legal_effect_candidates"]=[row(lambda **k: L(type_id=rnd.choice(TY),**k)) for _ in range(rnd.randint(0,2))]
c["element_fact_candidates"]=[row(lambda **k: ev(**k)) for _ in range(rnd.randint(0,1))]
c["calculation_requests"]=[row(lambda **k: dict({"calculation_domain":"CE-01","completeness":"partial","source_refs":["EV-1"]},**k)) for _ in range(rnd.randint(0,1))]
return c
bad=0; stat=Counter()
for n in range(int(sys.argv[1]) if len(sys.argv)>1 else 40):
ds=rnd.sample(["E-02","E-03","E-13","E-00"],rnd.randint(2,3))
acts=["같은행위","다른행위"]
roots={d:[seed(rnd.randint(1,4),rnd.choice(acts)) for _ in range(rnd.randint(1,3))] for d in ds}
res={}
for m in ("CUR","V2"):
res[m]=P(multi_docs({k:rootw(v) for k,v in roots.items()},act=mkact(ds)),mode=m)
a,b=S(res["CUR"]),S(res["V2"])
ok=lambda x: "EXC" not in x.get("L0","EXC") and "EXC" not in x.get("L2","EXC") and "EXC" not in x.get("FL","EXC") and "EXC" not in x.get("F2","EXC") and "Error" not in x.get("S0","Error")
stat[(ok(a),ok(b))]+=1
if ok(b):
fs=res["V2"]["_fs"]; bo=rj(fs,"BO.json"); recsx={(x["domain_id"],x["type_id"]):x for x in res["V2"]["_b"]["structure_records"]}
for x in bo:
for s_ in x["provenance"].get("absorbed_sources",[]):
for t in s_["Legal_Keywords"]:
r=recsx.get((s_["source_domain"],t))
if r is not None and x["BO_ID"] not in r["source_bo_ids"]: bad+=1; print("MISS",x["BO_ID"],s_,t)
for x in res["V2"]["_b"]["structure_records"]:
for z in x["routes"]:
if not isinstance(z["source_seed_id"],str) or z["source_seed_id"]=="F": bad+=1; print("SEED",z)
for r in rj(fs,"signals/legal_effect_routes.json")["records"]:
c=r["details"].get("candidate_ref");
if "bo_absent" in r["details"] and r["details"]["bo_absent"] is not True: bad+=1; print("ABS",r["details"])
if ok(a)!=ok(b) or not ok(b): print("DIFF",n,a,b)
print("stat (CUR ok,V2 ok)",dict(stat),"invariant bad",bad)
@@ -0,0 +1,7 @@
cats {'CUR': {('nokw', 'merged', 'otherdom'): 12, ('kw', 'merged', 'otherdom'): 32, ('kw', 'single', 'otherdom'): 374, ('nokw', 'single', 'own'): 34, ('nokw', 'merged', 'own'): 12, ('nokw', 'single', 'otherdom'): 29}, 'V2': {('nokw', 'merged', 'otherdom'): 12, ('kw', 'merged', 'otherdom'): 20, ('kw', 'merged', 'own'): 7, ('kw', 'single', 'otherdom'): 374, ('nokw', 'single', 'own'): 34, ('nokw', 'merged', 'own'): 12, ('nokw', 'single', 'otherdom'): 29}}
rounds 300 seed 20261031 fix False
(CUR+P3orig, CUR+P3new, V2+P3new, V2+P3red) ok -> {(False, True, True, True): 83, (True, True, True, True): 107, (False, False, True, True): 105, (False, False, False, False): 5}
bad {}
link miss {'CUR': 493, 'V2': 488} extra {'CUR': 1, 'V2': 0}
s2 {('LES_BO_JOIN', 'PASS'): 295, ('LES_REVERSE_INDEX', 'PASS'): 295, ('strict_json', True): 205, ('cur_strict', True): 96, ('strict_json', False): 90, ('cur_strict', False): 94}
fails {"{'F0': 'SystemExit:1'}": 5}
@@ -0,0 +1,8 @@
cats {'CUR': {('nokw', 'single', 'own'): 28, ('kw', 'single', 'otherdom'): 327, ('nokw', 'merged', 'own'): 7, ('kw', 'merged', 'otherdom'): 36, ('nokw', 'merged', 'otherdom'): 6, ('nokw', 'single', 'otherdom'): 11}, 'V2': {('nokw', 'single', 'own'): 28, ('kw', 'single', 'otherdom'): 327, ('nokw', 'merged', 'own'): 7, ('kw', 'merged', 'otherdom'): 23, ('nokw', 'merged', 'otherdom'): 6, ('kw', 'merged', 'own'): 11, ('nokw', 'single', 'otherdom'): 11}}
rounds 300 seed 77 fix False
(CUR+P3orig, CUR+P3new, V2+P3new, V2+P3red) ok -> {(False, False, True, True): 104, (True, True, True, True): 110, (False, True, True, True): 81, (False, False, False, False): 5}
CUR 멈춤 사유 {'KeyError': 82, 'RuntimeError': 17, 'SystemExit:1': 5, 'ValueError': 5}
bad {}
link miss {'CUR': 415, 'V2': 413} extra {'CUR': 1, 'V2': 0}
s2 {('LES_BO_JOIN', 'PASS'): 295, ('LES_REVERSE_INDEX', 'PASS'): 295, ('strict_json', True): 203, ('cur_strict', False): 98, ('cur_strict', True): 93, ('strict_json', False): 92}
fails {"{'F0': 'SystemExit:1'}": 5}
@@ -0,0 +1,8 @@
cats {'CUR': {('nokw', 'merged', 'otherdom'): 12, ('kw', 'merged', 'otherdom'): 32, ('kw', 'single', 'otherdom'): 374, ('nokw', 'single', 'own'): 34, ('nokw', 'merged', 'own'): 12, ('nokw', 'single', 'otherdom'): 29}, 'V2': {('nokw', 'merged', 'otherdom'): 12, ('kw', 'single', 'otherdom'): 374, ('nokw', 'single', 'own'): 34, ('nokw', 'merged', 'own'): 12, ('nokw', 'single', 'otherdom'): 29, ('kw', 'merged', 'otherdom'): 11}}
rounds 300 seed 20261031 fix True
(CUR+P3orig, CUR+P3new, V2+P3new, V2+P3red) ok -> {(False, True, True, True): 83, (True, True, True, True): 107, (False, False, True, True): 105, (False, False, False, False): 5}
CUR 멈춤 사유 {'KeyError': 75, 'RuntimeError': 25, 'SystemExit:1': 5, 'ValueError': 5}
bad {}
link miss {'CUR': 493, 'V2': 472} extra {'CUR': 1, 'V2': 0}
s2 {('LES_BO_JOIN', 'PASS'): 295, ('LES_REVERSE_INDEX', 'PASS'): 295, ('strict_json', True): 295, ('cur_strict', True): 96, ('cur_strict', False): 94}
fails {"{'F0': 'SystemExit:1'}": 5}
@@ -0,0 +1,8 @@
cats {'CUR': {('nokw', 'single', 'own'): 28, ('kw', 'single', 'otherdom'): 327, ('nokw', 'merged', 'own'): 7, ('kw', 'merged', 'otherdom'): 36, ('nokw', 'merged', 'otherdom'): 6, ('nokw', 'single', 'otherdom'): 11}, 'V2': {('nokw', 'single', 'own'): 28, ('kw', 'single', 'otherdom'): 327, ('nokw', 'merged', 'own'): 7, ('kw', 'merged', 'otherdom'): 11, ('nokw', 'merged', 'otherdom'): 6, ('nokw', 'single', 'otherdom'): 11, ('kw', 'merged', 'own'): 1}}
rounds 300 seed 77 fix True
(CUR+P3orig, CUR+P3new, V2+P3new, V2+P3red) ok -> {(False, False, True, True): 104, (True, True, True, True): 110, (False, True, True, True): 81, (False, False, False, False): 5}
CUR 멈춤 사유 {'KeyError': 82, 'RuntimeError': 17, 'SystemExit:1': 5, 'ValueError': 5}
bad {}
link miss {'CUR': 415, 'V2': 391} extra {'CUR': 1, 'V2': 0}
s2 {('LES_BO_JOIN', 'PASS'): 295, ('LES_REVERSE_INDEX', 'PASS'): 295, ('strict_json', True): 295, ('cur_strict', False): 98, ('cur_strict', True): 93}
fails {"{'F0': 'SystemExit:1'}": 5}
@@ -0,0 +1,36 @@
# 2회차 제안 수정을 시안에 얹은 새 자산 (fix 판)
import shutil,os
a=open('new/signals/adapters/s3_domain_seed_adapter.txt',encoding='utf-8').read()
def sub(s,o,n):
assert s.count(o)==1,o
return s.replace(o,n)
a=sub(a,'element_rows.append(_known_refs_only(fact, universe, removed))','element_rows.append(_schema_row(_known_refs_only(fact, universe, removed), _SEED_ROW_KEYS))')
a=sub(a,'opposing_rows.append(_known_refs_only(fact, universe, removed))','opposing_rows.append(_schema_row(_known_refs_only(fact, universe, removed), _SEED_ROW_KEYS))')
a=sub(a,'defense_rows.append(_known_refs_only(defense, universe, removed))','defense_rows.append(_schema_row(_known_refs_only(defense, universe, removed), _SEED_ROW_KEYS))')
a=sub(a,', refs, defense, universe))',', refs, defense, universe, "inferred" if defense.get("status") in (None, "inferred", "observed") else "review"))')
a=sub(a,'refs = [str(ref) for ref in _rows(defense.get("source_refs", seed_refs))]','refs = seed_refs')
a=sub(a,'"calculation_id": request.get("calculation_domain") or request.get("calculation_id"),','"calculation_id": request.get("calculation_domain"),')
a=sub(a,'kept["worker_extra"] = json.dumps(extra, ensure_ascii=False, sort_keys=True)','kept["worker_extra"] = json.dumps(extra, ensure_ascii=False, sort_keys=True).encode("utf-8", "backslashreplace").decode("utf-8")')
c=open('new/stage1_runtime/structure_index_compiler.txt',encoding='utf-8').read()
c=sub(c,''' for key in pairs:
record = records.get(key)
if record is not None:
attached_here = True
if isinstance(bo_id, str) and bo_id not in record["source_bo_ids"]:
record["source_bo_ids"].append(bo_id)
record["source_bo_ids"].sort()
''',''' if absorbed_sources:
# 그 도메인이 선언하지 않은 유형의 route 는 L0-4 가 선언 도메인에 붙였다. BO 도 같은 곳에 붙인다.
pairs = [target for key in pairs for target in
([key] if key in records else
[(d, key[1]) for d in declaring_domains.get(key[1], []) if (d, key[1]) in records])]
for key in pairs:
record = records.get(key)
if record is not None:
attached_here = True
if isinstance(bo_id, str) and bo_id not in record["source_bo_ids"]:
record["source_bo_ids"].append(bo_id)
record["source_bo_ids"].sort()
''')
open('fix_adapter.txt','w',encoding='utf-8').write(a); open('fix_compiler.txt','w',encoding='utf-8').write(c)
import ast; ast.parse(a); ast.parse(c); print("ok")
@@ -0,0 +1,17 @@
# Part 3 전략서 축소판: 방안 'Part 3 전략서 조정' 그대로 p3_new 에서 만든다
s=open('p3_new.yml',encoding='utf-8').read()
I=' '*10
def cut(o,n=''):
global s
assert s.count(o)>=1,o
s=s.replace(o,n)
cut(I+' raw_seed_ids = {}\n')
cut(I+' seed_id = details.get("source_seed_id")\n'+I+' if seed_id is not None and not isinstance(seed_id, str):\n'+I+' raw_seed_ids[signal_id] = _raw_text(seed_id)\n'+I+' fixed["source_seed_id"] = raw_seed_ids[signal_id]\n')
cut(I+' return normalized, raw_type_ids, raw_seed_ids\n',I+' return normalized, raw_type_ids\n')
cut('def mark_route_gaps(bundle, review_items, review_code, raw_seed_ids):','def mark_route_gaps(bundle, review_items, review_code):')
cut(I+' # route_source_seed_id_not_string 후보를 추적할 수 없는 route 다.\n')
cut(I+' for ref in routes:\n'+I+' signal_id = str(ref.get("signal_id"))\n'+I+' if signal_id in raw_seed_ids:\n'+I+' found.append({"detail": "route_source_seed_id_not_string", "signal_id": signal_id})\n')
cut('sg13_records, raw_type_ids, raw_seed_ids = normalize_route_fields(','sg13_records, raw_type_ids = normalize_route_fields(')
cut('mark_route_gaps(bundle, review_items, structure_index_compiler.REVIEW_ROUTE_NO_BO, raw_seed_ids)','mark_route_gaps(bundle, review_items, structure_index_compiler.REVIEW_ROUTE_NO_BO)')
cut(I+' "raw_source_seed_id_routes": sorted(raw_seed_ids),\n')
open('p3_red.yml','w',encoding='utf-8').write(s)
@@ -0,0 +1,20 @@
exec(open('r1base.py').read())
def dseed(i,t,act=None,**kw):
c=good(i); c["seed_id"]="s%d"%i
ts=t if isinstance(t,list) else ([t] if t else [])
c["legal_effect_candidates"]=[L(type_id=x) for x in ts]
c["extensions"]={"domain_payload":{"action_summary":act or ("행위%d"%i),"action_type":"법률행위(legal acts)"}}
c.update(kw); return c
def scen(roots,canon=(),pre=None,tamper=None,mode="V2",lzero=None):
def pf(fs):
if canon: fs.docs[ADJ]=adjdoc(list(canon))
if pre: pre(fs)
return P(multi_docs({k:rootw(v) for k,v in roots.items()},act=mkact(list(roots))),mode=mode,pre_f0=pf,tamper=tamper,lzero=lzero)
def rowsof(fs):
x=json.loads(fs.docs["Fact_Ledger_base.json"])
return x if isinstance(x,list) else next(v for v in x.values() if isinstance(v,list))
def sigs(fs,name): return rj(fs,"signals/%s.json"%name)["records"]
def env(fs,d): return rj(fs,"signals/domain_signals/%s.json"%d)["domain_signal_envelope"]
def types_of(d):
j=json.loads((D/("domains/%s/domain_config.json"%d)).read_text(encoding="utf-8")) if (D/("domains/%s/domain_config.json"%d)).exists() else None
return j
@@ -0,0 +1,6 @@
def use_fix(on=True):
EX.clear()
if on:
a=open('fix_adapter.txt',encoding='utf-8').read(); c=open('fix_compiler.txt',encoding='utf-8').read()
for k,v in (("signals/adapters/s3_domain_seed_adapter",a),("stage1_runtime/structure_index_compiler",c)):
EX["Default_Agent/%s.txt"%k]=v; EX["Default_Agent/%s.py"%k]=v
@@ -0,0 +1,18 @@
# S2_00 SIGNAL 수집 절편: 원본 YAML 3253~3272 행 코드를 그대로 뽑아 실행한다
import textwrap
_sp=SPATH.read_text(encoding="utf-8").split("\n")
_a=next(i for i,l in enumerate(_sp) if "for row in signal_all.get(\"ordered_file_rows\", []):" in l and i>3200)
_b=next(i for i,l in enumerate(_sp) if "# ---------------- C15 pairs" in l)
_loop=textwrap.dedent("\n".join(_sp[_a:_b]))
def s2_signal(fs, bo_tag=None, evt=None, evi=None):
mats={}
def put(ref,kind,parties_,title,text,node,*,domain_ids=(),event_kind="",keywords=(),source_events=(),extra=None):
mats[ref]={"parties":sorted(parties_),"title":sorted(title),"domain_ids":sorted({str(d) for d in domain_ids if d}),"src":list(source_events),"text":text[:120],"extra":extra,"compact":S2["_compact"](node)}
rows=[]; parsed={}
for k,v in fs.docs.items():
if k.startswith("signals/") and not k.endswith("signal_manifest.json") and "compatibility" not in k:
p=k[len("signals/"):]; parsed[p]=json.loads(v); rows.append({"file_path":p,"kind":"domain_signal" if "domain_signals" in p else "signal"})
kinds=sorted({r["kind"] for r in rows})
g=dict(S2); g.update(put=put,bo_tag=bo_tag or {},evt=evt or {},evi=evi or {},SEMANTIC_SIGNAL_KINDS=set(kinds),signal_all={"ordered_file_rows":rows,"_parsed_documents_by_path":parsed})
exec(_loop,g)
return mats
@@ -0,0 +1,17 @@
exec(open('r2base.py').read())
CALC=lambda s="ready":{"calculation_domain":"CE-01","completeness":s,"source_refs":["EV-1"]}
T2,T3,T13="money_claim","commercial_successor","fraudulent_transfer"
def rep(nm,roots,canon=()):
for m in("CUR","V2"):
o=scen(roots,canon,mode=m); s={k:v[:110] for k,v in S(o).items() if k in("L2","FL","F2")}
print("##",nm,m,s)
fs=o["_fs"]
if "Fact_Ledger_base.json" in fs.docs:
for r in rowsof(fs):
print(" ",r["source_bo_id"],"sigcount",r["claim_chain_ref"]["signal_count"],[(c["request_id"],c["provenance"]["structure_ids"]) for c in r["calculation_requests"]])
b=rj(fs,"stage1_tmp/fact_ledger/fact_ledger_candidate_bundle.json"); b=b.get("fact_ledger_candidate_bundle",b); print(" eq",json.dumps(b.get("equations") or b.get("audit",{}).get("equations"),ensure_ascii=False)[:300])
rep("한 후보 두 유형 + 계산",{"E-03":[dseed(1,[T2,T3],calculation_requests=[CALC()])]})
rep("같은 도메인 두 BO 가 계산 공유",{"E-03":[dseed(1,T2,"가",calculation_requests=[CALC()]),dseed(2,T3,"나",calculation_requests=[CALC("partial")])]})
rep("병합 2도메인 각 2유형 계산 2건",{"E-02":[dseed(1,[T2,"general_legal_effect"],"같은",calculation_requests=[CALC()])],"E-03":[dseed(1,[T2,T3],"같은",calculation_requests=[CALC(),CALC("blocked")])]})
rep("도메인 순서 E-13+X1 병합",{"E-13":[dseed(1,T13,"같은",calculation_requests=[CALC()])],"X1":[dseed(1,None,"같은",legal_effect_candidates=[L(type_id="general_legal_effect")],calculation_requests=[CALC()])]})
rep("댕글링 없음, 단일",{"E-02":[dseed(1,T2,calculation_requests=[CALC()])]})
@@ -0,0 +1,42 @@
exec(open('r2base.py').read()); exec(open('r2fix.py').read())
import random
rnd=random.Random(5)
L0RED=code("Task_C_LE_L0_structure_seed_reducer",open("p3_red.yml",encoding="utf-8").read().split("\n"))
def comp(i,d):
decl={"E-02":["money_claim","general_legal_effect"],"E-03":["money_claim","commercial_successor"],"E-13":["fraudulent_transfer","preserved_claim"]}[d]
c=dseed(i,rnd.sample(decl,rnd.randint(0,2)),"행위%s%d"%(d,i)) # 도메인마다 다른 행위 → 교차 병합 없음
c["source_refs"]=["EV-%d"%(i%4+1)]
c["element_fact_candidates"]=[ev(payload=rnd.choice([{}, {"status":"contested"},{"status":"review"},{"k":"v"}]),excerpt=rnd.choice(["본문",None])) for _ in range(rnd.randint(0,2))]
c["defense_candidates"]=[ev(payload=rnd.choice([{}, {"status":"contested"}])) for _ in range(rnd.randint(0,1))]
c["opposing_fact_candidates"]=[ev() for _ in range(rnd.randint(0,1))]
if rnd.random()<.4: c["calculation_requests"]=[{"calculation_domain":"CE-01","completeness":rnd.choice(["ready","partial","blocked","deferred"]),"source_refs":["EV-1"],"review_code":rnd.choice([None,"AAA"])}]
return c
tot=Counter(); difs=Counter()
for n in range(120):
ds=rnd.sample(["E-02","E-03","E-13"],rnd.randint(1,3))
roots={d:[comp(i,d) for i in rnd.sample(range(1,9),rnd.randint(1,3))] for d in ds}
use_fix(False); A=scen(roots,mode="CUR")
B=scen(roots,mode="V2")
use_fix(True); C=scen(roots,mode="V2")
use_fix(False); DD=scen(roots,mode="V2",lzero=L0RED)
for nm,X in (("V2",B),("fix",C),("V2red",DD)):
tot[(nm,X.get("F2"))]+=1
da,db=A["_fs"].docs,X["_fs"].docs
dd=[p for p in sorted(set(da)|set(db)) if da.get(p)!=db.get(p)]
for p in dd: difs[(nm,p)]+=1
print(dict(tot)); print(dict(difs))
# 영수증 차이 내용
a=rj(A["_fs"],"validation_assets/routing/part3_receipt.json"); b=rj(B["_fs"],"validation_assets/routing/part3_receipt.json"); print(ddiff(a,b)[:6])
# 결정성: 키 순서 뒤집기
def rev(row): return dict(reversed(list(row.items())))
c1=dseed(1,None,legal_effect_candidates=[L(a=1,b={"y":1,"x":2},z="한글")],element_fact_candidates=[ev(a=1,b=2)],defense_candidates=[ev(a=1)])
c2=copy.deepcopy(c1); c2["legal_effect_candidates"]=[rev(r) for r in c1["legal_effect_candidates"]]; c2["element_fact_candidates"]=[rev(r) for r in c1["element_fact_candidates"]]
for m in("CUR","V2"):
x=[scen({"E-02":[dseed(2,"money_claim"),c]},mode=m)["_fs"] for c in (c1,c1,c2)]
ids=[[r["signal_id"] for f in("legal_effect_routes","legal_relation_lifecycle_signals") for r in sigs(fs,f)] for fs in x]
print(m,"같은입력 동일",ids[0]==ids[1],"키순서 뒤집기 동일",ids[0]==ids[2],ids[0][:2])
# 큰 값
for sz,ch in ((500000,"가"),(500000,'"')):
c=dseed(1,None,legal_effect_candidates=[L(big=ch*sz)])
for m in("CUR","V2"):
o=scen({"E-02":[dseed(2,"money_claim"),c]},mode=m); fs=o["_fs"]; print(repr(ch),sz,m,S(o).get("F2"),"SG-13 bytes",len(fs.docs["signals/legal_effect_routes.json"].encode()),"LES bytes",len(fs.docs["legal_effect_structures.json"].encode()),"FL",len(fs.docs["Fact_Ledger_base.json"].encode()))
@@ -0,0 +1,10 @@
s=open('t_bytes.py').read()
s=s[:s.index('# 영수증 차이 내용')].replace(''' tot[(nm,X.get("F2"))]+=1
''',''' tot[(nm,str(A.get("F2"))[:45],X.get("F2"))]+=1
if "EXC" in str(A.get("F2")): continue
''').replace('for p in dd: difs[(nm,p)]+=1','''for p in dd:
difs[(nm,p)]+=1
if p.endswith("receipt.json"):
for z in ddiff(json.loads(da[p]),json.loads(db[p])): keys[z[0]]+=1''').replace('tot=Counter(); difs=Counter()','tot=Counter(); difs=Counter(); keys=Counter()')
s+='\nprint(dict(keys))\n'
exec(s)
@@ -0,0 +1,24 @@
exec(open('r2base.py').read())
fill=[dseed(i,"money_claim") for i in (2,3,4)]
print("--- 항변 source_refs (스키마 밖) 가 정본 칸 결정")
for nm,kw in (("없음",{}),("source_refs EV",dict(source_refs=["EV-3"])),("source_refs MC",dict(source_refs=["MC-1"])),("source_refs EVT",dict(source_refs=["EVT-1"]))):
for m in("CUR","V2"):
o=scen({"E-02":fill+[dseed(1,"money_claim",defense_candidates=[ev(**kw)])]},mode=m); r=sigs(o["_fs"],"defense_exception_signals")[0]
print(nm,m,r["evidence_refs"],r["meeting_clause_refs"],r["proof_grade"],"details.source_refs",r["details"].get("source_refs"),"wx",r["details"].get("worker_extra"))
print("--- negative_or_conflicting_refs")
for k,kw in (("effect",dict(legal_effect_candidates=[L(negative_or_conflicting_refs=["EV-1","ZZ"])])),("element",dict(element_fact_candidates=[ev(negative_or_conflicting_refs=["EV-1"])]))):
o=scen({"E-02":fill+[dseed(1,"money_claim",**kw)]}); f="legal_effect_routes" if k=="effect" else "legal_relation_lifecycle_signals"
print(k,[(r["negative_or_conflicting_refs"],r["review_required"],r["status"]) for r in sigs(o["_fs"],f) if r["negative_or_conflicting_refs"]],rj(o["_fs"],"signals/%s.json"%f)["status"],o.get("man"))
print("--- calculation_id 폴백")
for req in ({"calculation_id":"FORGED","completeness":"ready","source_refs":["EV-1"]},{"calculation_id":{"x":1},"completeness":"ready","source_refs":["EV-1"]}):
for m in("CUR","V2"):
o=scen({"E-02":fill+[dseed(1,"money_claim",calculation_requests=[req])]},mode=m); fs=o["_fs"]; print(m,S(o).get("F2"),[(r["details"].get("calculation_id"),r["details"].get("worker_extra")) for r in sigs(fs,"calculation_requirements")],[c["calculation_id"] for r in rowsof(fs) for c in r["calculation_requests"]][:1] if "Fact_Ledger_base.json" in fs.docs else None)
print("--- 축소 Part 3 + 현행 Part 2 (순서 역전)")
L0RED=code("Task_C_LE_L0_structure_seed_reducer",open("p3_red.yml",encoding="utf-8").read().split("\n"))
o=scen({"E-02":fill+[dseed(1,None,legal_effect_candidates=[L(source_seed_id={"a":1})])]},mode="CUR",lzero=L0RED); print({k:v[:150] for k,v in S(o).items() if k in("L0","L2")})
o=scen({"E-02":fill+[dseed(1,None,legal_effect_candidates=[L(source_seed_id={"a":1})])]},mode="V2"); print("V2+전체 Part3",{k:v[:60] for k,v in S(o).items() if k in("L0","L2")},rj(o["_fs"],"validation_assets/routing/part3_receipt.json").get("raw_source_seed_id_routes"))
print("--- 흡수 후보 tag·라벨 (R1 MERGE)")
c=dseed(2,"commercial_successor","둘"); c["extensions"]["domain_payload"]["legal_effect_tags"]=["general_legal_effect"]; c["juristic_act_type"]="general_legal_effect"
c3=dseed(2,"commercial_successor","홀로"); c3["extensions"]["domain_payload"]["legal_effect_tags"]=["general_legal_effect"]
o=scen({"E-02":[dseed(1,"money_claim","하나")],"E-03":[c3]},[{"decision":"MERGE","input_candidate_refs":["E-03:001","E-02:001"],"merge_target_ref":"E-02:001"}]); print(boinfo(o["_fs"]),recs(o))
o=scen({"E-03":[c3]}); print("비병합",boinfo(o["_fs"]),recs(o))
@@ -0,0 +1,5 @@
exec(open('r2base.py').read()); exec(open('r2fix.py').read()); use_fix(True)
fill=[dseed(i,"money_claim") for i in (2,3,4)]
o=scen({"E-02":fill+[dseed(1,"money_claim",defense_candidates=[ev(source_refs=["EV-3"])])]}); r=sigs(o["_fs"],"defense_exception_signals")[0]; print(r["evidence_refs"],r["proof_grade"],r["details"].get("worker_extra"))
o=scen({"E-02":fill+[dseed(1,"money_claim",calculation_requests=[{"calculation_id":"FORGED","completeness":"ready","source_refs":["EV-1"]}])]}); fs=o["_fs"]; print(S(o).get("F2"),[(r["details"].get("calculation_id"),r["details"].get("worker_extra")) for r in sigs(fs,"calculation_requirements")],[c["calculation_id"] for r in rowsof(fs) for c in r["calculation_requests"]][:1])
print([k for k in rj(fs,"quality_gates/stage1_part4_review_handoff.json").get("stage1_part4_review_handoff",{}).get("review_items",[]) if k.get("review_code")=="CALCULATION_ID_SUBSTITUTED_REVIEW"][:1])
@@ -0,0 +1,19 @@
exec(open('r2base.py').read()); exec(open('r2s2.py').read())
FORGE=dict(source_bo_ids=["bh1"],domain_ids=["E-13"],review_required=True,signal_id="SIG-FORGED",record_type="forged",status="review",
details={"type_id":"fraudulent_transfer","calculation_domain":"CE-99","source_bo_ids":["bh1"],"source_refs":["EVT-1"],"payload":{"x":1}},
structure_id="LES-E-13-fraudulent_transfer",Action="위조 행위",amount="999",title="위조제목")
tag={"bh1":{"parties":{"위조당사자"},"title":{"위조제목"},"text":"본문","source_events":["EVT-1"]}}
for nm,mk in (("element",lambda c:c.update(element_fact_candidates=[ev(**FORGE)])),("opposing",lambda c:c.update(opposing_fact_candidates=[ev(**FORGE)])),("defense",lambda c:c.update(defense_candidates=[ev(**FORGE)]))):
for m in ("CUR","V2"):
c=dseed(1,"money_claim"); mk(c)
o=scen({"E-02":[c]},mode=m); fs=o["_fs"]
print("##",nm,m,{k:v for k,v in S(o).items() if k in("S0","man","F2") or "EXC" in str(v)},o.get("codes"))
if str(o.get("S0")).startswith("READY"):
e=env(fs,"E-02"); r=(e["element_fact_candidates"]+e["opposing_fact_candidates"]+e["defense_candidates"])
print(" env keys",sorted(r[0]) if r else None)
mats=s2_signal(fs,tag)
for k,v in mats.items():
if "domain_signals" in k: print(" S2 env",k,"parties",v["parties"],"dom",v["domain_ids"],"title",v["title"],"src",v["src"],"extra",v["extra"]); print(" compact",json.dumps(v["compact"],ensure_ascii=False)[:300])
elif v["parties"] or "E-13" in v["domain_ids"]: print(" S2 sg",k,v["parties"],v["domain_ids"])
c=dseed(1,"money_claim"); c.update(element_fact_candidates=[ev(**FORGE)]); o=scen({"E-02":[c]},mode="V2"); print({k:str(v)[:300] for k,v in o.items() if not k.startswith("_")})
c=dseed(1,"money_claim"); c.update(element_fact_candidates=[ev(source_bo_ids=["bh1"])]); o=scen({"E-02":[c]},mode="V2"); print({k:str(v)[:300] for k,v in o.items() if not k.startswith("_") and k!="res"})
@@ -0,0 +1,35 @@
exec(open('r2base.py').read())
T2,T3,T13="money_claim","commercial_successor","fraudulent_transfer"
def show(nm,roots,canon=()):
for m in ("CUR","V2"):
o=scen(roots,canon,mode=m)
print("##",nm,m,{k:v for k,v in S(o).items() if k in("S0","man","L2","F2") or "EXC" in str(v)},o.get("codes"),o.get("counts"))
fs=o["_fs"]
if "BO.json" in fs.docs:
print(" BO",json.dumps([(b["BO_ID"],b["Legal_Keywords"],{k:v for k,v in b["provenance"].items() if k in("source_domain","source_keywords","absorbed_sources")}) for b in rj(fs,"BO.json")],ensure_ascii=False)[:380])
if "_b" in o:
print(" recs",recs(o)); print(" unattBO",o["_b"]["unattached_bo"],"unattR",o["_b"]["unattached_routes"][:3])
if "Fact_Ledger_base.json" in fs.docs:
for r in rowsof(fs): print(" row",r["source_bo_id"],r["linked_structures"]["structure_ids"],"state",r["state_context"]["domain_ids"],"actio",r["linked_actio_structures"],"must",r["must_consider"])
# 1. 흡수 도메인이 선언하지 않은 유형: E-13 이 money_claim(E-02 선언, E-13 미선언)을 낸다
show("A 흡수유형 미선언 + 생존 자기유형",{"E-02":[dseed(1,"general_legal_effect","같은행위")],"E-13":[dseed(1,T2,"같은행위")]})
show("B 흡수유형 미선언 + 생존 키워드 없음",{"E-02":[dseed(1,None,"같은행위")],"E-13":[dseed(1,T2,"같은행위")]})
show("C 생존이 미선언 유형, 흡수가 선언 도메인",{"E-13":[dseed(1,T2,"같은행위")],"E-02":[dseed(1,"general_legal_effect","같은행위")]})
# 2. 사슬 중간 도메인만 낸 유형
show("D 사슬 중간",{"E-02":[dseed(1,T2)],"E-03":[dseed(2,T3)],"E-13":[dseed(3,T13)]},[{"decision":"MERGE","input_candidate_refs":["E-02:001","E-03:001"],"merge_target_ref":"E-03:001"},{"decision":"MERGE","input_candidate_refs":["E-03:001","E-13:001"],"merge_target_ref":"E-13:001"}])
# 3. legal_effect_tags, juristic label
c=dseed(1,None,"같은행위"); c["extensions"]["domain_payload"]["legal_effect_tags"]=[T2]
show("E 생존 tag",{"E-02":[c],"E-03":[dseed(1,T3,"같은행위")]})
c=dseed(1,None,"같은행위"); c["extensions"]["domain_payload"]["legal_effect_tags"]=[T3]
show("F 흡수 tag 만",{"E-02":[dseed(1,T2,"같은행위")],"E-03":[c]})
c=dseed(1,None,"같은행위"); c["juristic_act_type"]=T2
show("G 생존 juristic 라벨=유형",{"E-02":[c],"E-03":[dseed(1,T3,"같은행위")]})
c=dseed(1,T3,"같은행위"); c["juristic_act_type"]="general_legal_effect"
show("H 흡수 juristic 라벨=유형",{"E-02":[dseed(1,T2,"같은행위")],"E-03":[c]})
# 4. 같은 도메인 흡수 + 다른 도메인 흡수 키워드 비어 absorbed 없음
show("I 같은도메인 흡수 + 다른도메인 빈키워드",{"E-02":[dseed(1,T2,"a"),dseed(4,"general_legal_effect","b")],"E-03":[dseed(2,None,"c")]},[{"decision":"MERGE","input_candidate_refs":["E-02:002","E-03:001","E-02:001"],"merge_target_ref":"E-02:001"}])
# 5. 양 도메인 같은 키워드 + 다른 키워드
show("J 양쪽 같은+각자",{"E-02":[dseed(1,[T2,"general_legal_effect"],"같은행위")],"E-03":[dseed(1,[T2,T3],"같은행위")]})
# 6. registered false 흡수
c=dseed(1,None,"같은행위"); c["legal_effect_candidates"]=[L(type_id=T3,registered=False)]
show("K 흡수 registered false",{"E-02":[dseed(1,T2,"같은행위")],"E-03":[c]})
@@ -0,0 +1,9 @@
exec(open('r2base.py').read()); exec(open('r2fix.py').read()); exec(open('r2s2.py').read())
use_fix()
T2,T3="money_claim","commercial_successor"
for nm,roots in (("A",{"E-02":[dseed(1,"general_legal_effect","같은행위")],"E-13":[dseed(1,T2,"같은행위")]}),("B",{"E-02":[dseed(1,None,"같은행위")],"E-13":[dseed(1,T2,"같은행위")]}),("C",{"E-13":[dseed(1,T2,"같은행위")],"E-02":[dseed(1,"general_legal_effect","같은행위")]}),("M5",{"E-02":[dseed(1,"general_legal_effect","같은행위")],"E-03":[dseed(1,T2,"같은행위")]})):
o=scen(roots); print(nm,{k:v for k,v in S(o).items() if k in("S0","L2","F2")},o.get("codes"),recs(o),o["_b"]["unattached_bo"]); print(" ",[(r["source_bo_id"],r["must_consider"],r["linked_structures"]["structure_ids"]) for r in rowsof(o["_fs"])])
FORGE=dict(source_bo_ids=["bh1"],domain_ids=["E-13"],review_required=True,signal_id="SIG-FORGED",details={"type_id":"x","calculation_domain":"CE-99","source_bo_ids":["bh1"]},Action="위조",source_refs=["ZZ-1"])
tag={"bh1":{"parties":{"위조당사자"},"title":{"위조제목"},"text":"본문","source_events":["EVT-1"]}}
c=dseed(1,"money_claim",element_fact_candidates=[ev(z=float("nan"),**FORGE)],opposing_fact_candidates=[ev(**FORGE)],defense_candidates=[ev(status="contested",**FORGE)]); o=scen({"E-02":[dseed(2,"money_claim"),dseed(3,"money_claim"),dseed(4,"money_claim"),c]}); fs=o["_fs"]; print(S(o)); e=env(fs,"E-02"); print(json.dumps(e["element_fact_candidates"][-1],ensure_ascii=False)[:300]); print(e["status"],e["extensions"]); print([ (r["status"],r["review_required"]) for r in sigs(fs,"defense_exception_signals")])
m=s2_signal(fs,tag); print({k.split("#")[1]:(v["parties"],v["domain_ids"]) for k,v in m.items() if "domain_signals" in k})
@@ -0,0 +1,125 @@
# 차등 퍼저 2회차. 인자: N seed [fix]
exec(open('r2base.py').read()); exec(open('r2fix.py').read())
import random
_rt=run_task; LAST=[""]
def run_task(src,fs,tag,stage):
purge(); buf=io.StringIO()
try:
with contextlib.redirect_stdout(buf):
g=load(src,fs,tag); g["main"]()
finally:
LAST[0]=buf.getvalue()
return buf.getvalue()
N=int(sys.argv[1]); SEED=int(sys.argv[2]); FIX=len(sys.argv)>3 and sys.argv[3]=="fix"
rnd=random.Random(SEED)
L0RED=code("Task_C_LE_L0_structure_seed_reducer",open("p3_red.yml",encoding="utf-8").read().split("\n"))
L0ORIG=code("Task_C_LE_L0_structure_seed_reducer",open("p3_orig.yml",encoding="utf-8").read().split("\n"))
KEYS=dict(source_seed_id=["F",{"a":1},7,None,True,1.5],bo_absent=[True,False,"true",1],candidate_ref=["E-99:001",5],request_id=["R",9],signal_id=["S",3],status=["review","contested","missing_required","BLOCKED","junk",7],
domain_ids=[["E-13"],"E-13"],review_required=[True,"x"],source_bo_ids=[["bh1"],["zz"],"bh1"],negative_or_conflicting_refs=[["EV-1"],["nope"],"EV-1"],missing_operands=[["위조"],"x"],compatibility_key=["c","legacy-liability-0001"],
compatibility_order=["x",0,1],relation_component=[{}],liability_component=[{}],compatibility_route=[{"a":1}],worker_extra=["q",{"z":1}],details=[{"type_id":"x","source_bo_ids":["bh1"]}],law_version_refs=[["LV"]],source_refs=[["EV-2"],["ZZ"],"EV-1"],blocked=[True],proof_grade=["document_direct","x"],confidence=["high",3],
operand_state=["blocked"],calculation_id=[{"x":1},"CALC"],review_code=[{"a":1},"X_Y",None],nanv=[float("nan")])
def surplus():
if rnd.random()<.45: return {}
ks=rnd.sample(list(KEYS),rnd.randint(1,4))
return {k:rnd.choice(KEYS[k]) for k in ks}
TY=["money_claim","commercial_successor","general_legal_effect","fraudulent_transfer","preserved_claim","tort_liability","nope",None,7,{"x":1},["l"],True]
GOODTY=["money_claim","commercial_successor","general_legal_effect","fraudulent_transfer"]
def seed(i,act,pool):
c=good(i); c["seed_id"]="s%d"%i
pl={"action_summary":act,"action_type":"법률행위(legal acts)"}
if rnd.random()<.15: pl["legal_effect_tags"]=[rnd.choice(GOODTY)]
c["extensions"]={"domain_payload":pl}
if rnd.random()<.15: c["juristic_act_type"]=rnd.choice(["매매",GOODTY[0]])
c["legal_effect_candidates"]=[L(**dict({"type_id":rnd.choice(pool),"registered":rnd.choice([True,True,True,False,"yes"])},**surplus())) for _ in range(rnd.randint(0,3))]
c["element_fact_candidates"]=[ev(**{k:v for k,v in surplus().items()}) for _ in range(rnd.randint(0,2))]
c["opposing_fact_candidates"]=[ev(**surplus()) for _ in range(rnd.randint(0,1))]
c["defense_candidates"]=[ev(**surplus()) for _ in range(rnd.randint(0,1))]
c["calculation_requests"]=[dict({"calculation_domain":"CE-01","completeness":rnd.choice(["ready","partial","blocked","deferred","junk"]),"source_refs":["EV-1"]},**surplus()) for _ in range(rnd.randint(0,2))]
return c
def k0(o): return okf(S(o))
curstop=Counter()
def okf(x):
return all("EXC" not in x.get(k,"EXC") for k in("L0","L2","FL","F2")) and x.get("R0")=="OK" and x.get("F0")=="OK" and "Error" not in x.get("S0","Error")
def strict_ok(fs):
for k,v in fs.docs.items():
if k.startswith("signals/") or k in("BO.json","legal_effect_structures.json","Fact_Ledger_base.json"):
try: S2["load_json_strict"](v.encode("utf-8"))
except BaseException: return False
return True
def link_miss(o):
"""route 의 후보가 BO 에 들어갔는데 그 route 가 붙은 레코드에 BO 가 없는 수 / 후보 없이 붙은 BO 수"""
fs=o["_fs"]; comp=rj(fs,"stage1_tmp/task_c_bo/postb_compiled_bundle_compact.json")["candidate_ref_to_bo_id"]
r2c={}
for r in sigs(fs,"legal_effect_routes"): r2c[r["signal_id"]]=r["details"].get("candidate_ref")
miss=extra=0; ex=[]
bo={b["BO_ID"]:b for b in rj(fs,"BO.json")}
for rec in o["_b"]["structure_records"]:
need={comp.get(r2c.get(x["signal_id"])) for x in rec["routes"]}-{None}
for b in need:
if b not in rec["source_bo_ids"]:
miss+=1; ex.append(("miss",rec["structure_id"],b))
kw=rec["type_id"] in bo[b]["Legal_Keywords"]; ab=bool(bo[b]["provenance"].get("absorbed_sources")) or any(k!=[x for x,y in comp.items() if y==b][0] for k in [x for x,y in comp.items() if y==b])
cats[(("kw" if kw else "nokw"),("merged" if ab else "single"),("own" if bo[b]["provenance"]["source_domain"]==rec["domain_id"] else "otherdom"))]+=1
for b in rec["source_bo_ids"]:
if b not in need and rec["type_id"] in [c for c in bo[b]["Legal_Keywords"]] and rec["routes"]:
tags=_dict_tags(bo[b]);
if rec["type_id"] not in tags: extra+=1; ex.append(("extra",rec["structure_id"],b))
return miss,extra,ex
def _dict_tags(b):
return set(b.get("extensions",{}).get("domain_payload",{}).get("legal_effect_tags") or [])|({(b.get("JuristicAct") or {}).get("label")} if isinstance(b.get("JuristicAct"),dict) else set())
CATS={"CUR":Counter(),"V2":Counter()}; stat=Counter(); diffs=[]; bad=Counter(); miss={"CUR":0,"V2":0}; extra={"CUR":0,"V2":0}; sc=Counter(); fails=Counter()
for n in range(N):
ds=rnd.sample(["E-02","E-03","E-13","E-00","E-05"],rnd.randint(1,3))
acts=["같은행위","다른행위","셋째행위"]
pool=TY if rnd.random()<.5 else GOODTY
roots={d:[seed(rnd.randint(1,4),rnd.choice(acts),pool) for _ in range(rnd.randint(1,3))] for d in ds}
# 격리 예산을 넘겨 R0 에서 끝나지 않도록 정상 후보를 보탠다
for d in ds: roots[d].extend(dseed(5+i,"general_legal_effect" if d!="E-13" else "fraudulent_transfer","채움%s%d"%(d,i)) for i in range(4))
canon=[]
if rnd.random()<.4 and len(ds)>=2:
a,b=rnd.sample(ds,2); canon=[{"decision":"MERGE","input_candidate_refs":["%s:001"%a,"%s:001"%b],"merge_target_ref":"%s:001"%b}]
if rnd.random()<.3 and len(ds)==3:
c=[x for x in ds if x not in(a,b)][0]; canon.append({"decision":"MERGE","input_candidate_refs":["%s:001"%b,"%s:001"%c],"merge_target_ref":"%s:001"%c})
res={}
use_fix(False)
res["CURo"]=scen(roots,canon,mode="CUR",lzero=L0ORIG)
res["CUR"]=scen(roots,canon,mode="CUR")
if not k0(res["CUR"]):
x=S(res["CUR"]); txt=" ".join(str(v) for v in x.values() if "EXC" in str(v) or "Error" in str(v) or "SystemExit" in str(v))
m_=re.search(r'(PART[0-9]_[A-Z_]+|S0_[A-Z_]+|COMPATIBILITY_[A-Z_]+|[A-Z][a-z]+Error)',txt); curstop[m_.group(1) if m_ else txt[:60]]+=1
use_fix(FIX)
res["V2"]=scen(roots,canon,mode="V2")
res["V2r"]=scen(roots,canon,mode="V2",lzero=L0RED)
k={m:okf(S(res[m])) for m in res}
stat[tuple(k[m] for m in("CURo","CUR","V2","V2r"))]+=1
for m in("CUR","V2"):
if k["CUR"] and k["V2"]:
cats=CATS[m]
a,b,ex=link_miss(res[m]); miss[m]+=a; extra[m]+=b
if k["CUR"] and not k["V2"] or k["CUR"] and not k["V2r"]:
diffs.append(("STOP",n,S(res["V2"]),S(res["V2r"]))); bad["cur_ok_v2_stop"]+=1
if not k["V2"]:
fails[LAST[0][-300:] if False else str({a:str(b)[:110] for a,b in S(res["V2"]).items() if b not in("OK",) and not str(b).startswith("READY")})[:230]]+=1
if k["V2"]:
fs=res["V2"]["_fs"]
if k["V2r"]:
f2=res["V2r"]["_fs"]
dd=[p for p in sorted(set(fs.docs)|set(f2.docs)) if fs.docs.get(p)!=f2.docs.get(p)]
if [p for p in dd if not p.endswith("part3_receipt.json")]: bad["red_diff"]+=1; diffs.append(("REDDIFF",n,dd[:4]))
for x in res["V2"]["_b"]["structure_records"]:
for z in x["routes"]:
if not isinstance(z["source_seed_id"],str) or z["source_seed_id"]=="F": bad["seed"]+=1
for f in ("legal_effect_routes","legal_relation_lifecycle_signals","defense_exception_signals","calculation_requirements","liability_causation_damage_signals"):
allow={"legal_effect_routes":{"source_seed_id","type_id","source_refs","registered","review_code","candidate_ref","bo_absent","worker_extra"},"calculation_requirements":{"calculation_domain","completeness","source_refs","review_code","worker_extra","request_id","domain_ids","calculation_id","operand_state","evidence_refs","meeting_clause_refs","candidate_ref","bo_absent"}}.get(f,{"source_seed_id","source_id","source_kind","excerpt","payload","worker_extra"})
for r in sigs(fs,f):
if set(r["details"])-allow: bad["surplus_top"]+=1; diffs.append(("KEY",f,sorted(set(r["details"])-allow)))
if not isinstance(r["details"].get("worker_extra",""),str): bad["wx_notstr"]+=1
c=S2["check_conservation"]({"bo":rj(fs,"BO.json"),"fact_ledger_base":rj(fs,"Fact_Ledger_base.json"),"legal_effect_structures":rj(fs,"legal_effect_structures.json"),"evidence_indexed":{"items":[{"evidence_index":e} for e in EV]},"evidence_event_candidates":{"items":[]}})
for z in c["checks"]:
if z["check_id"] in("LES_BO_JOIN","LES_REVERSE_INDEX") : sc[(z["check_id"],z["status"])]+=1
sc[("strict_json",strict_ok(fs))]+=1
if res["CUR"]["_fs"].docs.get("BO.json") and k["CUR"]: sc[("cur_strict",strict_ok(res["CUR"]["_fs"]))]+=1
print("cats",{k:dict(v) for k,v in CATS.items()}); print("rounds",N,"seed",SEED,"fix",FIX)
print("(CUR+P3orig, CUR+P3new, V2+P3new, V2+P3red) ok ->",dict(stat))
print("CUR 멈춤 사유",dict(curstop)); print("bad",dict(bad)); print("link miss",miss,"extra",extra); print("s2",dict(sc)); print("fails",dict(fails))
for d in diffs[:8]: print(json.dumps(d,ensure_ascii=False,default=str)[:420])
@@ -0,0 +1,32 @@
exec(open('r2base.py').read()); exec(open('r2fix.py').read())
_G=Fs.get; MISS=set()
def _get(self,p):
if p in MISS: return None
return _G(self,p)
Fs.get=_get
fill=[dseed(i,"money_claim") for i in (2,3,4)]
print("--- 항변 status")
for nm,kw in (("없음",{}),("payload contested",dict(payload={"status":"contested"})),("payload missing",dict(payload={"status":"missing_required"})),("top contested",dict(status="contested")),("top missing",dict(status="missing_required")),("top review",dict(status="review")),("top observed",dict(status="observed")),("top BLOCKED",dict(status="BLOCKED"))):
res=[]
for m,fx in (("CUR",False),("V2",False),("fix",True)):
use_fix(fx)
o=scen({"E-02":fill+[dseed(1,"money_claim",defense_candidates=[ev(**kw)])]},mode="CUR" if m=="CUR" else "V2"); fs=o["_fs"]
r=sigs(fs,"defense_exception_signals")[0]; f=rj(fs,"signals/defense_exception_signals.json")
res.append((m,r["status"],r["review_required"],f["status"],o.get("man"),len(p2items(fs,"SCHEMA_ADDITIONAL_PROPERTY"))))
print(nm,res)
use_fix(False)
print("--- 위조 표시: bo_absent·candidate_ref 값 잔존")
c=dseed(1,None,legal_effect_candidates=[L(bo_absent="X",candidate_ref="Y",q=1)],calculation_requests=[{"calculation_domain":"CE-01","completeness":"ready","source_refs":["EV-1"],"bo_absent":"X","candidate_ref":"Y"}],element_fact_candidates=[ev(bo_absent="X")])
o=scen({"E-02":fill+[c]}); fs=o["_fs"]
print([ (r["details"].get("worker_extra"),r["details"].get("candidate_ref")) for r in sigs(fs,"legal_effect_routes") if "worker_extra" in r["details"]]); print([r["details"].get("worker_extra") for r in sigs(fs,"calculation_requirements")]); print([r["details"].get("worker_extra") for r in sigs(fs,"legal_relation_lifecycle_signals") if "worker_extra" in r["details"]])
print("--- 금지키: shadow·검증기 없음")
FORB=dict(final_conclusion="원고 승소")
def trial(nm):
for m in("CUR","V2"):
for k,kw in (("effect",dict(legal_effect_candidates=[L(**FORB)])),("calc",dict(calculation_requests=[dict({"calculation_domain":"CE-01","completeness":"ready","source_refs":["EV-1"]},**FORB)])),("element",dict(element_fact_candidates=[ev(**FORB)]))):
o=scen({"E-02":fill+[dseed(1,"money_claim",**kw)]},mode=m)
print(nm,m,k,str(o.get("R0"))[:70],str(o.get("S0"))[:110])
trial("enforce")
EX["Default_Agent/stage1_runtime/seed_admission_policy.v1.json"]=policy_mod(enforcement="shadow")["Default_Agent/stage1_runtime/seed_admission_policy.v1.json"]
trial("shadow"); EX.clear()
MISS.add("Default_Agent/stage1_runtime/worker_output_validator.txt"); trial("no-validator"); MISS.clear()
@@ -0,0 +1,6 @@
src=open('t_fuzz2.py').read().replace(''' res["V2r"]=scen(roots,canon,mode="V2",lzero=L0RED)''',''' if "F0" in S(res["V2"]) and S(res["V2"])["F0"].startswith("SystemExit"):
print("F0EXIT",canon,[x[:200] for x in LAST[0].split("{") if "FAIL" in x][:3]);
res["V2r"]=scen(roots,canon,mode="V2",lzero=L0RED)''')
sys_argv=['x','40','77']
import sys; sys.argv=sys_argv
exec(src)
@@ -0,0 +1,5 @@
exec(open('r2base.py').read()); exec(open('r2fix.py').read())
use_fix(True)
c=dseed(1,None,"같은행위"); c["legal_effect_candidates"]=[L(type_id="money_claim",registered="yes")]
o=scen({"E-02":[dseed(5,"money_claim"),dseed(6,"money_claim"),dseed(7,"money_claim"),c],"E-03":[dseed(5,"commercial_successor"),dseed(6,"commercial_successor"),dseed(1,"money_claim","같은행위")]})
print(S(o).get("F2"),boinfo(o["_fs"])); print(recs(o))
@@ -0,0 +1,24 @@
exec(open('r2base.py').read()); exec(open('r2fix.py').read())
_sd0=slice_doc; ORDER=[]
def slice_doc():
s=_sd0()
if ORDER:
d_=ORDER.pop(0); cfg=json.loads((D/("domains/%s/domain_config.json"%d_)).read_text(encoding="utf-8"))
s["stage_b_domain_slice"]["domain_declarations"]["structure_type_ids"]=[r["type_id"] for r in cfg.get("structure_types",[])]
return s
def real(roots,canon=(),mode="V2"):
ORDER[:]=list(roots); return scen(roots,canon,mode=mode)
T2="money_claim"
for nm,reg in (("registered true",True),("registered false",False)):
for fx,m in ((False,"CUR"),(False,"V2"),(True,"V2")):
use_fix(fx)
bad=dseed(1,None,"같은행위"); bad["legal_effect_candidates"]=[L(type_id=T2,registered=reg)]
o=real({"E-02":[dseed(1,"general_legal_effect","같은행위")],"E-13":[bad]},mode=m); fs=o["_fs"]
print(nm,"fix" if fx else m,{k:str(v)[:120] for k,v in S(o).items() if k in("R0","S0","F2")},o.get("codes"))
if "BO.json" in fs.docs: print(" ",boinfo(fs))
if "_b" in o: print(" ",recs(o),o["_b"]["unattached_bo"])
print(" adm",[(i.get("source_review_code"),i.get("template_note","")[:70]) for i in p2items(fs) if str(i.get("review_id","")).startswith("R0:admission")][:3])
# 생존 키워드 없음
bad2=dseed(1,None,"같은행위"); bad2["legal_effect_candidates"]=[L(type_id=T2,registered=reg)]
o=real({"E-02":[dseed(1,None,"같은행위")],"E-13":[bad2]},mode=m); fs=o["_fs"]
print(" 생존무키워드",{k:str(v)[:90] for k,v in S(o).items() if k in("R0","F2")},o.get("codes"),recs(o) if "_b" in o else None,[r["must_consider"] for r in rowsof(fs)] if "Fact_Ledger_base.json" in fs.docs else None)
@@ -0,0 +1,39 @@
import json,hashlib,re,shutil,sys,pathlib,subprocess
DA="../seal/DA/"
sha=lambda p: hashlib.sha256(open(p,'rb').read()).hexdigest()
m=DA+"runtime_manifest.json"
man=json.load(open(m,encoding='utf-8'))
print("top keys",[k for k in man if k!="entries"],{k:(v if not isinstance(v,(list,dict)) else type(v).__name__) for k,v in man.items() if k!="entries"})
print("entries",len(man["entries"]),"before sha",sha(m)[:12])
rels=["signals/adapters/s3_domain_seed_adapter","stage1_runtime/structure_index_compiler","stage1_runtime/fact_ledger_compiler"]
# 1. .txt 는 시안 산출, .py 는 같은 내용으로 복사(원본 .py 를 고치고 .txt 로 복사한 것과 같은 결과)
olds={}
for r in rels:
for e in (".py",".txt"): olds[r+e]=sha(DA+r+e)
olds["stage1_runtime/structure_index_policy.v1.json"]=sha(DA+"stage1_runtime/structure_index_policy.v1.json")
for r in rels:
shutil.copyfile("new/"+r+".txt",DA+r+".txt"); shutil.copyfile("new/"+r+".txt",DA+r+".py")
shutil.copyfile("new/stage1_runtime/structure_index_policy.v1.json",DA+"stage1_runtime/structure_index_policy.v1.json")
# 2. 다른 곳에 옛 sha 가 박혀 있는가
hits={}
for p in pathlib.Path(DA).rglob("*"):
if p.is_file() and p.suffix in(".json",".md",".txt",".py",".yml") and p.name!="runtime_manifest.json":
t=p.read_text(encoding="utf-8",errors="ignore")
for k,v in olds.items():
if v in t: hits.setdefault(k,[]).append(str(p))
print("옛 sha 가 manifest 밖에 있는 곳",hits)
for y in ("p2_new.yml","p3_new.yml","stage_1_part_4_v.8.yml"):
t=open(y,encoding="utf-8").read(); print(y,[k for k,v in olds.items() if v in t or v[:12] in t])
# 3. 치환
r_=open(m,encoding='utf-8').read(); cnt=0
for rel,old in olds.items():
c=r_.count(old); cnt+=c; r_=r_.replace(old,sha(DA+rel))
open(m,'w',encoding='utf-8').write(r_)
print("치환 수",cnt,"after",sha(m)[:12])
man2=json.load(open(m,encoding='utf-8'))
ch=[a["path"] for a,b in zip(man["entries"],man2["entries"]) if a["sha256"]!=b["sha256"]]; print("변경 행",len(ch),ch,"총수",len(man2["entries"]))
bad=[e["path"] for e in man2["entries"] if pathlib.Path(DA+e["path"]).exists() and sha(DA+e["path"])!=e["sha256"]]; miss=[e["path"] for e in man2["entries"] if not pathlib.Path(DA+e["path"]).exists()]
print("불일치",bad,"미존재",miss[:5],len(miss))
y=open('p2_new.yml',encoding='utf-8').read()
y2,n=re.subn(r'EXPECTED_RUNTIME_MANIFEST_SHA256 = "[0-9a-f]{64}"','EXPECTED_RUNTIME_MANIFEST_SHA256 = "%s"'%sha(m),y); print("상수 치환",n)
open('p2_seal.yml','w',encoding='utf-8').write(y2)

Some files were not shown because too many files have changed in this diff Show More