Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e1072fa74 | ||
|
|
a9c948e7bb | ||
|
|
f318f7fa7a | ||
|
|
36b470969f | ||
|
|
8a61c99c9a |
@@ -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
@@ -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
@@ -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
@@ -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()
|
||||
+2
-1
@@ -25,7 +25,8 @@
|
||||
## Candidate and calculation boundary
|
||||
|
||||
- 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.
|
||||
|
||||
## Output and writer boundary
|
||||
|
||||
+17
-17
@@ -1126,7 +1126,7 @@
|
||||
},
|
||||
{
|
||||
"path": "domains/_common/common_worker_contract.md",
|
||||
"sha256": "f133c54c5a9353ae14efc4d7a27d9bee18872b6727713a9a107778eef8990fb1"
|
||||
"sha256": "4dd1bfcb12fef1a2077d670d1d87ffa67f2258b272fa7a0744ddd0692dd7367d"
|
||||
},
|
||||
{
|
||||
"path": "law_versions/_law_source_index.json",
|
||||
@@ -1466,11 +1466,11 @@
|
||||
},
|
||||
{
|
||||
"path": "signals/adapters/s3_domain_seed_adapter.py",
|
||||
"sha256": "0aa58a1dd69bf1653d444477176303ff75ab84052a3162089160669b59d5373f"
|
||||
"sha256": "0372ac56e068206ff0d7ee30e3d88e79fc4afec6cf256dede643f70bb5de79a5"
|
||||
},
|
||||
{
|
||||
"path": "signals/adapters/s3_domain_seed_adapter.txt",
|
||||
"sha256": "0aa58a1dd69bf1653d444477176303ff75ab84052a3162089160669b59d5373f"
|
||||
"sha256": "0372ac56e068206ff0d7ee30e3d88e79fc4afec6cf256dede643f70bb5de79a5"
|
||||
},
|
||||
{
|
||||
"path": "signals/adapters/s3_envelope_migration_adapter.py",
|
||||
@@ -1522,11 +1522,11 @@
|
||||
},
|
||||
{
|
||||
"path": "signals/compiler/signal_compiler.py",
|
||||
"sha256": "b8d4026dcc302321f6580fe1f96d168722635203a8e85d10d1e5b2d5f2561222"
|
||||
"sha256": "faf03415c93cf05ba464f10ba33794fd59db804e4fb427442c1bc61ce170e25b"
|
||||
},
|
||||
{
|
||||
"path": "signals/compiler/signal_compiler.txt",
|
||||
"sha256": "b8d4026dcc302321f6580fe1f96d168722635203a8e85d10d1e5b2d5f2561222"
|
||||
"sha256": "faf03415c93cf05ba464f10ba33794fd59db804e4fb427442c1bc61ce170e25b"
|
||||
},
|
||||
{
|
||||
"path": "signals/compiler/signal_gate.py",
|
||||
@@ -1654,11 +1654,11 @@
|
||||
},
|
||||
{
|
||||
"path": "signals/emitters/emitter_runtime.py",
|
||||
"sha256": "160d717ef77fedfa76ab9b309894f6a711af320387a5cfe619ba166d8eb6e279"
|
||||
"sha256": "0aa03059d1433171cf0288e6e94bd76ff9b9d27da4f33f981f02fc9b5f1718e7"
|
||||
},
|
||||
{
|
||||
"path": "signals/emitters/emitter_runtime.txt",
|
||||
"sha256": "160d717ef77fedfa76ab9b309894f6a711af320387a5cfe619ba166d8eb6e279"
|
||||
"sha256": "0aa03059d1433171cf0288e6e94bd76ff9b9d27da4f33f981f02fc9b5f1718e7"
|
||||
},
|
||||
{
|
||||
"path": "signals/schemas/asset_right_state_signals.schema.json",
|
||||
@@ -1738,7 +1738,7 @@
|
||||
},
|
||||
{
|
||||
"path": "stage1_runtime/bo_surface_projection_policy.v1.json",
|
||||
"sha256": "b3eba1d868ff543d761993396ada4910bd032a6762a8853403426655a3e9505a"
|
||||
"sha256": "d96e96d2178060e935c9309f0dfb59c5567d47ebbb9774d76335358724dab3c2"
|
||||
},
|
||||
{
|
||||
"path": "stage1_runtime/domain_fanout_planner.py",
|
||||
@@ -1758,15 +1758,15 @@
|
||||
},
|
||||
{
|
||||
"path": "stage1_runtime/fact_ledger_compiler.py",
|
||||
"sha256": "f6c4b476f4974104cd57accd559dcd91b31c80391077846dc3920d443c59a996"
|
||||
"sha256": "81df1130a3ab170ff548665547369f8ef5a657c5a1e14183fdabe472aa490f64"
|
||||
},
|
||||
{
|
||||
"path": "stage1_runtime/fact_ledger_compiler.txt",
|
||||
"sha256": "f6c4b476f4974104cd57accd559dcd91b31c80391077846dc3920d443c59a996"
|
||||
"sha256": "81df1130a3ab170ff548665547369f8ef5a657c5a1e14183fdabe472aa490f64"
|
||||
},
|
||||
{
|
||||
"path": "stage1_runtime/fact_ledger_policy.v1.json",
|
||||
"sha256": "fea0cea48d862c6c76774d6fee8ef84401a1b9fd753e86ccca76df32259523f7"
|
||||
"sha256": "08fad0b20e299063b502fd2a0ae1877b9a7074bdce5391110ea5d632c53787f9"
|
||||
},
|
||||
{
|
||||
"path": "stage1_runtime/prompt_compiler.py",
|
||||
@@ -1814,7 +1814,7 @@
|
||||
},
|
||||
{
|
||||
"path": "stage1_runtime/seed_admission_policy.v1.json",
|
||||
"sha256": "af048b2d1c9d01c7943658046dc3e8e9f3caee0901635dc344095982a7e05ba4"
|
||||
"sha256": "b41c7a4b51a0859104d7a2a5edb3b9c3db41d3f1481338fb1a0526d746f77522"
|
||||
},
|
||||
{
|
||||
"path": "stage1_runtime/stage_a_context_builder.py",
|
||||
@@ -1826,23 +1826,23 @@
|
||||
},
|
||||
{
|
||||
"path": "stage1_runtime/structure_index_compiler.py",
|
||||
"sha256": "c400adfb7c58e340a17e67aebcdc4a7cf92c35c422f418451c79ce7c531d201f"
|
||||
"sha256": "fd2f8de3df303f49a337d894c4e5017d06f24cd54799a0f8f66396394be65acb"
|
||||
},
|
||||
{
|
||||
"path": "stage1_runtime/structure_index_compiler.txt",
|
||||
"sha256": "c400adfb7c58e340a17e67aebcdc4a7cf92c35c422f418451c79ce7c531d201f"
|
||||
"sha256": "fd2f8de3df303f49a337d894c4e5017d06f24cd54799a0f8f66396394be65acb"
|
||||
},
|
||||
{
|
||||
"path": "stage1_runtime/structure_index_policy.v1.json",
|
||||
"sha256": "823a7e734a7bc9433966a5629a5a0b153a067c92d8570072fa14a5c42bb722bd"
|
||||
"sha256": "8eeedbcae6f3e4f648aa485b8620b23f4fdc16f43e0b678f224a403e915b1689"
|
||||
},
|
||||
{
|
||||
"path": "stage1_runtime/worker_output_validator.py",
|
||||
"sha256": "e5b46f929082faf621731ffb8f4864ccb9bba461ab23caa56d1bcfe5b073fd9d"
|
||||
"sha256": "5d13a3a70cad1ee73e63c90715feb15b9fdb25e132d93031358a51305af3bed7"
|
||||
},
|
||||
{
|
||||
"path": "stage1_runtime/worker_output_validator.txt",
|
||||
"sha256": "e5b46f929082faf621731ffb8f4864ccb9bba461ab23caa56d1bcfe5b073fd9d"
|
||||
"sha256": "5d13a3a70cad1ee73e63c90715feb15b9fdb25e132d93031358a51305af3bed7"
|
||||
},
|
||||
{
|
||||
"path": "tools/s3_router_v2.py",
|
||||
|
||||
+142
-30
@@ -19,24 +19,102 @@ def _liability_fanout_domains() -> set[str]:
|
||||
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]]:
|
||||
evidence = set(universe.get("evidence_ids", []))
|
||||
meeting = set(universe.get("meeting_clause_ids", []))
|
||||
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]:
|
||||
evidence, meeting = _source_fields(source_refs, universe)
|
||||
return {
|
||||
"record_type": record_type, "status": status, "domain_ids": [domain_id], "source_bo_ids": [],
|
||||
"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"),
|
||||
"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]:
|
||||
adapted = deepcopy(inputs)
|
||||
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", {})
|
||||
deprecated_envelopes = adapted.get("deprecated_domain_signal_envelopes", {})
|
||||
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:
|
||||
if not isinstance(wrapper, dict) or not isinstance(wrapper.get("stage_b_domain_bo_seed_output"), dict):
|
||||
continue
|
||||
@@ -58,56 +138,88 @@ def adapt(inputs: dict[str, Any]) -> dict[str, Any]:
|
||||
slot_rows: list[Any] = []
|
||||
calculation_refs: list[str] = []
|
||||
dependencies: set[str] = set()
|
||||
review_items: list[Any] = list(root.get("unknown_or_unrouted_reviews", []))
|
||||
for seed in root.get("bo_seed_candidates", []):
|
||||
removed: list[dict[str, str]] = []
|
||||
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):
|
||||
continue
|
||||
seed_id = str(seed.get("seed_id") or "unknown-seed")
|
||||
seed_refs = [str(ref) for ref in seed.get("source_refs", [])]
|
||||
for fact in seed.get("element_fact_candidates", []):
|
||||
# R0 candidate_ref formula (worker list position). S0 stamps it in memory, bo_absent too.
|
||||
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):
|
||||
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():
|
||||
candidates.setdefault("SG-08", []).append(_candidate(domain_id, seed_id, "liability_element", refs, fact, universe, str(fact.get("payload", {}).get("status") or "inferred")))
|
||||
element_rows.append(deepcopy(fact))
|
||||
for fact in seed.get("opposing_fact_candidates", []):
|
||||
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(_schema_row(_known_refs_only(fact, universe, removed), _SEED_ROW_KEYS))
|
||||
for fact in _rows(seed.get("opposing_fact_candidates")):
|
||||
if isinstance(fact, dict):
|
||||
opposing_rows.append(deepcopy(fact))
|
||||
for defense in seed.get("defense_candidates", []):
|
||||
opposing_rows.append(_schema_row(_known_refs_only(fact, universe, removed), _SEED_ROW_KEYS))
|
||||
for defense in _rows(seed.get("defense_candidates")):
|
||||
if isinstance(defense, dict):
|
||||
refs = [str(ref) for ref in defense.get("source_refs", seed_refs)]
|
||||
candidates.setdefault("SG-09", []).append(_candidate(domain_id, seed_id, "defense_trigger", refs, defense, universe, str(defense.get("status") or "inferred")))
|
||||
defense_rows.append(deepcopy(defense))
|
||||
for request in seed.get("calculation_requests", []):
|
||||
refs = seed_refs
|
||||
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(_schema_row(_known_refs_only(defense, universe, removed), _SEED_ROW_KEYS))
|
||||
for order, request in enumerate(_rows(seed.get("calculation_requests")), start=1):
|
||||
if isinstance(request, dict):
|
||||
adapted.setdefault("calculation_requests", []).append(deepcopy(request))
|
||||
if request.get("request_id"):
|
||||
calculation_refs.append(str(request["request_id"]))
|
||||
for effect in seed.get("legal_effect_candidates", []):
|
||||
# seed v3 has no request_id; this module builds both sides of the SG-11 join.
|
||||
stamped = deepcopy(request)
|
||||
for key in _CALCULATION_REF_KEYS:
|
||||
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):
|
||||
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"
|
||||
candidates.setdefault("SG-13", []).append(_candidate(domain_id, seed_id, "legal_effect_route", refs, effect, universe, status))
|
||||
for slot in seed.get("evidence_slot_status", []):
|
||||
marked = {**_without(effect, "bo_absent"), "candidate_ref": candidate_ref, **bo_mark}
|
||||
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):
|
||||
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)
|
||||
# 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_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,
|
||||
"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", []))
|
||||
review_items.extend(deepcopy(seed.get("review_items", [])))
|
||||
dependencies.update(str(value) for value in _rows(seed.get("dependency_refs")) if str(value))
|
||||
review_items.extend(_known_refs_only(_rows(seed.get("review_items")), universe, removed))
|
||||
extensions: dict[str, Any] = {}
|
||||
if isinstance(deprecated_envelopes, dict) and domain_id in deprecated_envelopes:
|
||||
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": {
|
||||
"schema_version": "stage1_domain_signals.v2", "domain_id": domain_id,
|
||||
"domain_registry_version": root.get("registry_version", "UNKNOWN"),
|
||||
"registry_index_sha256": root.get("registry_index_sha256", "0" * 64),
|
||||
"domain_registry_version": activation["registry_version"],
|
||||
"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"),
|
||||
"element_fact_candidates": element_rows, "opposing_fact_candidates": opposing_rows,
|
||||
"defense_candidates": defense_rows, "evidence_slot_status": slot_rows,
|
||||
|
||||
+142
-30
@@ -19,24 +19,102 @@ def _liability_fanout_domains() -> set[str]:
|
||||
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]]:
|
||||
evidence = set(universe.get("evidence_ids", []))
|
||||
meeting = set(universe.get("meeting_clause_ids", []))
|
||||
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]:
|
||||
evidence, meeting = _source_fields(source_refs, universe)
|
||||
return {
|
||||
"record_type": record_type, "status": status, "domain_ids": [domain_id], "source_bo_ids": [],
|
||||
"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"),
|
||||
"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]:
|
||||
adapted = deepcopy(inputs)
|
||||
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", {})
|
||||
deprecated_envelopes = adapted.get("deprecated_domain_signal_envelopes", {})
|
||||
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:
|
||||
if not isinstance(wrapper, dict) or not isinstance(wrapper.get("stage_b_domain_bo_seed_output"), dict):
|
||||
continue
|
||||
@@ -58,56 +138,88 @@ def adapt(inputs: dict[str, Any]) -> dict[str, Any]:
|
||||
slot_rows: list[Any] = []
|
||||
calculation_refs: list[str] = []
|
||||
dependencies: set[str] = set()
|
||||
review_items: list[Any] = list(root.get("unknown_or_unrouted_reviews", []))
|
||||
for seed in root.get("bo_seed_candidates", []):
|
||||
removed: list[dict[str, str]] = []
|
||||
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):
|
||||
continue
|
||||
seed_id = str(seed.get("seed_id") or "unknown-seed")
|
||||
seed_refs = [str(ref) for ref in seed.get("source_refs", [])]
|
||||
for fact in seed.get("element_fact_candidates", []):
|
||||
# R0 candidate_ref formula (worker list position). S0 stamps it in memory, bo_absent too.
|
||||
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):
|
||||
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():
|
||||
candidates.setdefault("SG-08", []).append(_candidate(domain_id, seed_id, "liability_element", refs, fact, universe, str(fact.get("payload", {}).get("status") or "inferred")))
|
||||
element_rows.append(deepcopy(fact))
|
||||
for fact in seed.get("opposing_fact_candidates", []):
|
||||
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(_schema_row(_known_refs_only(fact, universe, removed), _SEED_ROW_KEYS))
|
||||
for fact in _rows(seed.get("opposing_fact_candidates")):
|
||||
if isinstance(fact, dict):
|
||||
opposing_rows.append(deepcopy(fact))
|
||||
for defense in seed.get("defense_candidates", []):
|
||||
opposing_rows.append(_schema_row(_known_refs_only(fact, universe, removed), _SEED_ROW_KEYS))
|
||||
for defense in _rows(seed.get("defense_candidates")):
|
||||
if isinstance(defense, dict):
|
||||
refs = [str(ref) for ref in defense.get("source_refs", seed_refs)]
|
||||
candidates.setdefault("SG-09", []).append(_candidate(domain_id, seed_id, "defense_trigger", refs, defense, universe, str(defense.get("status") or "inferred")))
|
||||
defense_rows.append(deepcopy(defense))
|
||||
for request in seed.get("calculation_requests", []):
|
||||
refs = seed_refs
|
||||
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(_schema_row(_known_refs_only(defense, universe, removed), _SEED_ROW_KEYS))
|
||||
for order, request in enumerate(_rows(seed.get("calculation_requests")), start=1):
|
||||
if isinstance(request, dict):
|
||||
adapted.setdefault("calculation_requests", []).append(deepcopy(request))
|
||||
if request.get("request_id"):
|
||||
calculation_refs.append(str(request["request_id"]))
|
||||
for effect in seed.get("legal_effect_candidates", []):
|
||||
# seed v3 has no request_id; this module builds both sides of the SG-11 join.
|
||||
stamped = deepcopy(request)
|
||||
for key in _CALCULATION_REF_KEYS:
|
||||
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):
|
||||
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"
|
||||
candidates.setdefault("SG-13", []).append(_candidate(domain_id, seed_id, "legal_effect_route", refs, effect, universe, status))
|
||||
for slot in seed.get("evidence_slot_status", []):
|
||||
marked = {**_without(effect, "bo_absent"), "candidate_ref": candidate_ref, **bo_mark}
|
||||
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):
|
||||
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)
|
||||
# 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_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,
|
||||
"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", []))
|
||||
review_items.extend(deepcopy(seed.get("review_items", [])))
|
||||
dependencies.update(str(value) for value in _rows(seed.get("dependency_refs")) if str(value))
|
||||
review_items.extend(_known_refs_only(_rows(seed.get("review_items")), universe, removed))
|
||||
extensions: dict[str, Any] = {}
|
||||
if isinstance(deprecated_envelopes, dict) and domain_id in deprecated_envelopes:
|
||||
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": {
|
||||
"schema_version": "stage1_domain_signals.v2", "domain_id": domain_id,
|
||||
"domain_registry_version": root.get("registry_version", "UNKNOWN"),
|
||||
"registry_index_sha256": root.get("registry_index_sha256", "0" * 64),
|
||||
"domain_registry_version": activation["registry_version"],
|
||||
"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"),
|
||||
"element_fact_candidates": element_rows, "opposing_fact_candidates": opposing_rows,
|
||||
"defense_candidates": defense_rows, "evidence_slot_status": slot_rows,
|
||||
|
||||
+3
-2
@@ -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]]:
|
||||
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", {})
|
||||
legacy_actio = inputs.get("legacy_signals", {}).get("actio_case_signals", {})
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
registry_sha = str(manifest.get("registry_index_sha256") or "0" * 64)
|
||||
extension_domains = {item["domain_id"]: item["extension_key"] for item in _EXECUTION["e13_extension_domains"]}
|
||||
for domain_id in active:
|
||||
for domain_id in runnable:
|
||||
provided = deepcopy(supplied.get(domain_id)) if isinstance(supplied, dict) else None
|
||||
if isinstance(provided, dict):
|
||||
envelope = provided
|
||||
|
||||
+3
-2
@@ -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]]:
|
||||
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", {})
|
||||
legacy_actio = inputs.get("legacy_signals", {}).get("actio_case_signals", {})
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
registry_sha = str(manifest.get("registry_index_sha256") or "0" * 64)
|
||||
extension_domains = {item["domain_id"]: item["extension_key"] for item in _EXECUTION["e13_extension_domains"]}
|
||||
for domain_id in active:
|
||||
for domain_id in runnable:
|
||||
provided = deepcopy(supplied.get(domain_id)) if isinstance(supplied, dict) else None
|
||||
if isinstance(provided, dict):
|
||||
envelope = provided
|
||||
|
||||
+4
-1
@@ -100,7 +100,10 @@ def _calculation_candidates(inputs: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
if not isinstance(request, dict):
|
||||
continue
|
||||
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({
|
||||
"signal_id": request.get("request_id") or f"calculation-request-{index:04d}",
|
||||
"record_type": "calculation_requirement",
|
||||
|
||||
+4
-1
@@ -100,7 +100,10 @@ def _calculation_candidates(inputs: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
if not isinstance(request, dict):
|
||||
continue
|
||||
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({
|
||||
"signal_id": request.get("request_id") or f"calculation-request-{index:04d}",
|
||||
"record_type": "calculation_requirement",
|
||||
|
||||
+3
-2
@@ -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": "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": "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": "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.Object", "sources": ["object_refs[]"], "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}
|
||||
],
|
||||
"not_projected": {
|
||||
@@ -50,6 +50,7 @@
|
||||
"additive_keys": ["source_review_code", "action_source"],
|
||||
"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": {
|
||||
"bo_type_membership_source": "extension_payload_key_declarations.v1.json#bo_types_union",
|
||||
"bo_type_default": "event",
|
||||
|
||||
+58
-23
@@ -97,6 +97,23 @@ def compact_bo(bo: dict, policy: dict) -> dict:
|
||||
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갈래 · 순서 그대로)
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -398,7 +415,6 @@ def compile_fact_ledger_candidates(
|
||||
handoff_root = _dict(handoff_root.get("stage1_part2_review_handoff", handoff_root))
|
||||
handoff_items = [r for r in _list(handoff_root.get("review_items"))
|
||||
if isinstance(r, dict)]
|
||||
p2_rules = _dict(policy.get("p2_handoff_rules"))
|
||||
code_pool: dict[str, list[str]] = {}
|
||||
gate_input_counts = {"envelope_review_items": 0, "handoff_codes": 0,
|
||||
"handoff_not_a_code": 0, "handoff_domain_unresolved": 0,
|
||||
@@ -462,12 +478,12 @@ def compile_fact_ledger_candidates(
|
||||
bo_sorted = sorted(bo_records, key=lambda b: str(b.get("BO_ID") or ""))
|
||||
authority = build_evidence_authority(evidence_document)
|
||||
calc_types = set(_strings(policy.get("legal_calculation_object_types")))
|
||||
na_defaults = _dict(policy.get("field_synthesis_na_15"))
|
||||
rows: list[dict] = []
|
||||
attach_stats = {"attached_bo": 0, "unattached_bo": 0}
|
||||
used_structure_ids: set[str] = set()
|
||||
used_sg11: set[str] = set()
|
||||
slack_min = 10 ** 9
|
||||
pack_policy = _dict(policy.get("exception_pack"))
|
||||
for idx, bo in enumerate(bo_sorted, 1):
|
||||
compact = compact_bo(bo, policy)
|
||||
core = compact["core"]
|
||||
@@ -482,7 +498,11 @@ def compile_fact_ledger_candidates(
|
||||
parties.append({"role": "counterparty",
|
||||
"value": _text(core.get("Subject"), 160),
|
||||
"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"))
|
||||
evidence_refs = _strings(bo.get("source_evidence_indexes"))
|
||||
# F0-3 — LES 조인
|
||||
@@ -494,7 +514,8 @@ def compile_fact_ledger_candidates(
|
||||
attach_stats["unattached_bo"] += 1
|
||||
reviews.append({"review_code": "FACT_ROW_UNATTACHED_REVIEW",
|
||||
"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)
|
||||
domain_effects: dict[str, dict] = {}
|
||||
for record in attached:
|
||||
@@ -524,8 +545,9 @@ def compile_fact_ledger_candidates(
|
||||
# F0-5 — SG-11 조인 + operand_state 승계 (재산정 금지)
|
||||
calculation_requests: list[dict] = []
|
||||
route_refs: list[str] = []
|
||||
for record in attached:
|
||||
for ref in _strings(record.get("calculation_request_refs")):
|
||||
# 계산 조인은 도메인 단위라 한 도메인의 레코드마다 같은 ref 가 있다. 행에는 한 번만 싣는다.
|
||||
for ref in sorted({ref for record in attached
|
||||
for ref in _strings(record.get("calculation_request_refs"))}):
|
||||
route_refs.append(ref)
|
||||
sg = sg11_by_signal_id.get(ref)
|
||||
if sg is None:
|
||||
@@ -609,7 +631,10 @@ def compile_fact_ledger_candidates(
|
||||
"must_consider": bool(attached),
|
||||
"state_context": {"bo_type": compact.get("bo_type")
|
||||
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),
|
||||
"structure_ids": money_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
|
||||
if domain_id in r["domain_effects"]]
|
||||
entry["projected_row_count"] = len(projection_rows)
|
||||
reviews.append({"review_code": "GATE_FIRED_REVIEW",
|
||||
"severity": ("HARD_WARNING" if entry["blocks_final_drafting"]
|
||||
else "SOFT_WARNING"),
|
||||
"gate_id": gate_id, "detail": ",".join(emitted)[:160]})
|
||||
fired_by_domain.setdefault(domain_id, []).append({
|
||||
"gate_id": gate_id, "codes": emitted,
|
||||
"row_must_consider": rule["row_must_consider"],
|
||||
@@ -764,6 +793,11 @@ def compile_fact_ledger_candidates(
|
||||
row["must_consider"] = row["must_consider"] or True
|
||||
row["skeleton_validation_codes"] = _dedupe_keep_order(codes + gate_codes)
|
||||
|
||||
# ---- 어느 행에도 닿지 못한 계산 요청 --------------------------------
|
||||
for ref in sorted(set(sg11_by_signal_id) - used_sg11):
|
||||
reviews.append({"review_code": "CALCULATION_REQUEST_UNATTACHED_REVIEW",
|
||||
"severity": "SOFT_WARNING", "detail": ref})
|
||||
|
||||
# ---- STRUCTURE_UNATTACHED_REVIEW -----------------------------------
|
||||
unattached_structures = sorted(set(record_by_id) - used_structure_ids)
|
||||
for structure_id in unattached_structures:
|
||||
@@ -771,19 +805,18 @@ def compile_fact_ledger_candidates(
|
||||
"severity": "SOFT_WARNING", "detail": structure_id})
|
||||
|
||||
# ---- F0-9 — 예외 pack ----------------------------------------------
|
||||
pack_policy = _dict(policy.get("exception_pack"))
|
||||
char_limit = int(pack_policy.get("pack_item_char_limit") or 2000)
|
||||
exceptions: list[dict] = []
|
||||
for row in rows:
|
||||
if row["legal_calculation_object"] is None:
|
||||
continue
|
||||
bo = next((b for b in bo_sorted
|
||||
if str(b.get("BO_ID") or "") == row["source_bo_id"]), {})
|
||||
core = _dict(bo.get("core_field_base"))
|
||||
amount_candidates = [v for v in (bo.get("amount"), core.get("Amount"))
|
||||
if _nonblank(v)]
|
||||
if len(amount_candidates) >= 2:
|
||||
payload = {"amount_candidates": [_text(v, 240) for v in amount_candidates],
|
||||
for row, bo in zip(rows, bo_sorted):
|
||||
provenance = _dict(bo.get("provenance"))
|
||||
alternatives = _list(provenance.get("amount_alternatives"))
|
||||
# 칸은 차 있어도 BO 금액은 없다
|
||||
unbodied = 0 if bo.get("amount") else len(_list(provenance.get("amount_related_values")))
|
||||
if alternatives:
|
||||
payload = {"amount_candidates": alternatives,
|
||||
"current_value_id": _dict(bo.get("amount")).get("value_id"),
|
||||
"action": row["action"],
|
||||
"legal_calculation_object": row["legal_calculation_object"],
|
||||
"object_spec": row["object_spec"],
|
||||
"calculation_request_ids": sorted(
|
||||
str(c.get("calculation_id")) for c in
|
||||
@@ -797,16 +830,19 @@ def compile_fact_ledger_candidates(
|
||||
rendered = json.dumps(item, ensure_ascii=False)
|
||||
if len(rendered) > char_limit:
|
||||
item["oversize_review"] = True
|
||||
reviews.append({"review_code": "CALCULATION_BASIS_INCOMPLETE_REVIEW",
|
||||
reviews.append({"review_code": "CALCULATION_PACK_OVERSIZE_REVIEW",
|
||||
"severity": "SOFT_WARNING",
|
||||
"fact_id": row["fact_id"],
|
||||
"detail": "pack item oversize %d>%d" % (len(rendered),
|
||||
char_limit)})
|
||||
exceptions.append(item)
|
||||
elif (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",
|
||||
"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
|
||||
_dict(policy.get("f1_exception_types")).items()
|
||||
if _dict(meta).get("unreachable_in_v8")}
|
||||
@@ -856,9 +892,8 @@ def compile_fact_ledger_candidates(
|
||||
(set(slot["review_codes"]) & les_review_codes)
|
||||
for row in rows for slot in row["domain_effects"].values()) or any(
|
||||
_dict(r).get("review_required") for r in structure_records)
|
||||
gate_fired_any = any(f for firings in fired_by_domain.values() for f in firings)
|
||||
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")
|
||||
counts = {
|
||||
"rows": len(rows),
|
||||
|
||||
+58
-23
@@ -97,6 +97,23 @@ def compact_bo(bo: dict, policy: dict) -> dict:
|
||||
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갈래 · 순서 그대로)
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -398,7 +415,6 @@ def compile_fact_ledger_candidates(
|
||||
handoff_root = _dict(handoff_root.get("stage1_part2_review_handoff", handoff_root))
|
||||
handoff_items = [r for r in _list(handoff_root.get("review_items"))
|
||||
if isinstance(r, dict)]
|
||||
p2_rules = _dict(policy.get("p2_handoff_rules"))
|
||||
code_pool: dict[str, list[str]] = {}
|
||||
gate_input_counts = {"envelope_review_items": 0, "handoff_codes": 0,
|
||||
"handoff_not_a_code": 0, "handoff_domain_unresolved": 0,
|
||||
@@ -462,12 +478,12 @@ def compile_fact_ledger_candidates(
|
||||
bo_sorted = sorted(bo_records, key=lambda b: str(b.get("BO_ID") or ""))
|
||||
authority = build_evidence_authority(evidence_document)
|
||||
calc_types = set(_strings(policy.get("legal_calculation_object_types")))
|
||||
na_defaults = _dict(policy.get("field_synthesis_na_15"))
|
||||
rows: list[dict] = []
|
||||
attach_stats = {"attached_bo": 0, "unattached_bo": 0}
|
||||
used_structure_ids: set[str] = set()
|
||||
used_sg11: set[str] = set()
|
||||
slack_min = 10 ** 9
|
||||
pack_policy = _dict(policy.get("exception_pack"))
|
||||
for idx, bo in enumerate(bo_sorted, 1):
|
||||
compact = compact_bo(bo, policy)
|
||||
core = compact["core"]
|
||||
@@ -482,7 +498,11 @@ def compile_fact_ledger_candidates(
|
||||
parties.append({"role": "counterparty",
|
||||
"value": _text(core.get("Subject"), 160),
|
||||
"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"))
|
||||
evidence_refs = _strings(bo.get("source_evidence_indexes"))
|
||||
# F0-3 — LES 조인
|
||||
@@ -494,7 +514,8 @@ def compile_fact_ledger_candidates(
|
||||
attach_stats["unattached_bo"] += 1
|
||||
reviews.append({"review_code": "FACT_ROW_UNATTACHED_REVIEW",
|
||||
"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)
|
||||
domain_effects: dict[str, dict] = {}
|
||||
for record in attached:
|
||||
@@ -524,8 +545,9 @@ def compile_fact_ledger_candidates(
|
||||
# F0-5 — SG-11 조인 + operand_state 승계 (재산정 금지)
|
||||
calculation_requests: list[dict] = []
|
||||
route_refs: list[str] = []
|
||||
for record in attached:
|
||||
for ref in _strings(record.get("calculation_request_refs")):
|
||||
# 계산 조인은 도메인 단위라 한 도메인의 레코드마다 같은 ref 가 있다. 행에는 한 번만 싣는다.
|
||||
for ref in sorted({ref for record in attached
|
||||
for ref in _strings(record.get("calculation_request_refs"))}):
|
||||
route_refs.append(ref)
|
||||
sg = sg11_by_signal_id.get(ref)
|
||||
if sg is None:
|
||||
@@ -609,7 +631,10 @@ def compile_fact_ledger_candidates(
|
||||
"must_consider": bool(attached),
|
||||
"state_context": {"bo_type": compact.get("bo_type")
|
||||
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),
|
||||
"structure_ids": money_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
|
||||
if domain_id in r["domain_effects"]]
|
||||
entry["projected_row_count"] = len(projection_rows)
|
||||
reviews.append({"review_code": "GATE_FIRED_REVIEW",
|
||||
"severity": ("HARD_WARNING" if entry["blocks_final_drafting"]
|
||||
else "SOFT_WARNING"),
|
||||
"gate_id": gate_id, "detail": ",".join(emitted)[:160]})
|
||||
fired_by_domain.setdefault(domain_id, []).append({
|
||||
"gate_id": gate_id, "codes": emitted,
|
||||
"row_must_consider": rule["row_must_consider"],
|
||||
@@ -764,6 +793,11 @@ def compile_fact_ledger_candidates(
|
||||
row["must_consider"] = row["must_consider"] or True
|
||||
row["skeleton_validation_codes"] = _dedupe_keep_order(codes + gate_codes)
|
||||
|
||||
# ---- 어느 행에도 닿지 못한 계산 요청 --------------------------------
|
||||
for ref in sorted(set(sg11_by_signal_id) - used_sg11):
|
||||
reviews.append({"review_code": "CALCULATION_REQUEST_UNATTACHED_REVIEW",
|
||||
"severity": "SOFT_WARNING", "detail": ref})
|
||||
|
||||
# ---- STRUCTURE_UNATTACHED_REVIEW -----------------------------------
|
||||
unattached_structures = sorted(set(record_by_id) - used_structure_ids)
|
||||
for structure_id in unattached_structures:
|
||||
@@ -771,19 +805,18 @@ def compile_fact_ledger_candidates(
|
||||
"severity": "SOFT_WARNING", "detail": structure_id})
|
||||
|
||||
# ---- F0-9 — 예외 pack ----------------------------------------------
|
||||
pack_policy = _dict(policy.get("exception_pack"))
|
||||
char_limit = int(pack_policy.get("pack_item_char_limit") or 2000)
|
||||
exceptions: list[dict] = []
|
||||
for row in rows:
|
||||
if row["legal_calculation_object"] is None:
|
||||
continue
|
||||
bo = next((b for b in bo_sorted
|
||||
if str(b.get("BO_ID") or "") == row["source_bo_id"]), {})
|
||||
core = _dict(bo.get("core_field_base"))
|
||||
amount_candidates = [v for v in (bo.get("amount"), core.get("Amount"))
|
||||
if _nonblank(v)]
|
||||
if len(amount_candidates) >= 2:
|
||||
payload = {"amount_candidates": [_text(v, 240) for v in amount_candidates],
|
||||
for row, bo in zip(rows, bo_sorted):
|
||||
provenance = _dict(bo.get("provenance"))
|
||||
alternatives = _list(provenance.get("amount_alternatives"))
|
||||
# 칸은 차 있어도 BO 금액은 없다
|
||||
unbodied = 0 if bo.get("amount") else len(_list(provenance.get("amount_related_values")))
|
||||
if alternatives:
|
||||
payload = {"amount_candidates": alternatives,
|
||||
"current_value_id": _dict(bo.get("amount")).get("value_id"),
|
||||
"action": row["action"],
|
||||
"legal_calculation_object": row["legal_calculation_object"],
|
||||
"object_spec": row["object_spec"],
|
||||
"calculation_request_ids": sorted(
|
||||
str(c.get("calculation_id")) for c in
|
||||
@@ -797,16 +830,19 @@ def compile_fact_ledger_candidates(
|
||||
rendered = json.dumps(item, ensure_ascii=False)
|
||||
if len(rendered) > char_limit:
|
||||
item["oversize_review"] = True
|
||||
reviews.append({"review_code": "CALCULATION_BASIS_INCOMPLETE_REVIEW",
|
||||
reviews.append({"review_code": "CALCULATION_PACK_OVERSIZE_REVIEW",
|
||||
"severity": "SOFT_WARNING",
|
||||
"fact_id": row["fact_id"],
|
||||
"detail": "pack item oversize %d>%d" % (len(rendered),
|
||||
char_limit)})
|
||||
exceptions.append(item)
|
||||
elif (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",
|
||||
"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
|
||||
_dict(policy.get("f1_exception_types")).items()
|
||||
if _dict(meta).get("unreachable_in_v8")}
|
||||
@@ -856,9 +892,8 @@ def compile_fact_ledger_candidates(
|
||||
(set(slot["review_codes"]) & les_review_codes)
|
||||
for row in rows for slot in row["domain_effects"].values()) or any(
|
||||
_dict(r).get("review_required") for r in structure_records)
|
||||
gate_fired_any = any(f for firings in fired_by_domain.values() for f in firings)
|
||||
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")
|
||||
counts = {
|
||||
"rows": len(rows),
|
||||
|
||||
+22
-18
@@ -69,7 +69,7 @@
|
||||
"type": "compact.bo_type 단독 (LES types[0] 폴백 금지)",
|
||||
"date": "first_value(core_field_base.BehaviorTime, bo.date) — bo.date 는 BO 18키에 없어 항상 None. 골든은 BehaviorTime 0/59 라 전건 null",
|
||||
"parties": "core_field_base 단독 — Performer -> role: actor · Subject -> role: counterparty · 값은 text(party, 160) · source: 'BO.core_field_base'. 구 signal 경로 폐지",
|
||||
"amount": "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) — 정규화 계층 통과 후의 소문자 키",
|
||||
"evidence_refs": "BO source_evidence_indexes 단독 — LES 증거는 합집합하지 않는다(합집합하면 v.8 에서 깨진다). LES 증거는 domain_effects 쪽에만 싣는다",
|
||||
"derived_fact": "action 복제 단독 — 구본 4항 서술 분기는 삭제 확정(deprecation 절)"
|
||||
@@ -82,11 +82,11 @@
|
||||
},
|
||||
"legal_centrality": "부착 있으면 high · 없으면 medium",
|
||||
"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: []}",
|
||||
"must_not_drop_in_claim_types": "부착 레코드 module 정렬 합집합 · 기본 []",
|
||||
"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: 해당 정렬 목록}",
|
||||
"commercial_successor_effect": "{enabled: module 'commercial_successor' 부착 여부, structure_ids: 해당 정렬 목록}",
|
||||
"actio_roles": "module 'actio' 부착 레코드의 role_projection 정렬 합집합 · 기본 []",
|
||||
@@ -181,13 +181,13 @@
|
||||
"str_condition_disposition": "GATE_PREDICATE_SPEC_UNIMPLEMENTED_REVIEW — 술어 명세를 코드로 옮기는 것은 판정식 창작이다(D-P4-b=(가))",
|
||||
"orphan_rule_disposition": "GATE_RULE_NOT_IN_REGISTRY",
|
||||
"unknown_or_missing_policy_default": "fail_open_to_review",
|
||||
"block_semantics": "blocks_final_drafting: true 는 Stage 1 기록을 막지 않는다. 행은 기록되고 final_writer_status 가 READY_WITH_REVIEW 가 되며 차단 표지는 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": {
|
||||
"target_rows": "발화 게이트의 도메인 d 에 대해 R(d) = { row | d ∈ row.domain_effects 키 }",
|
||||
"codes": "R(d) 전 행의 skeleton_validation_codes 에 합집합 부착(순서 규칙은 skeleton_checks)",
|
||||
"must_consider": "row_effect.must_consider 보유 규칙 발화 시 R(d) 전 행 OR 갱신(기존 True 미소실)",
|
||||
"preserve_seed": "on_true.preserve_seed 는 행 필드가 아니라 writer report 게이트별 발화 목록에만 기록",
|
||||
"empty_target": "R(d) 공집합이면 행에 닿지 않고 writer report 에만 계수(침묵 아님)"
|
||||
"empty_target": "R(d) 공집합이면 행에 닿지 않고 writer report 와 handoff GATE_FIRED_REVIEW 에 계수(침묵 아님)"
|
||||
},
|
||||
"normalization_axes_17": {
|
||||
"rule_array_keys": [
|
||||
@@ -283,15 +283,17 @@
|
||||
"exception_pack": {
|
||||
"surviving_type": "legal_calculation_required",
|
||||
"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}",
|
||||
"pack_item_char_limit": 2000,
|
||||
"oversize_disposition": "자동 차단이 아니라 exception_id 유지한 채 review",
|
||||
"oversize_disposition": "자동 차단이 아니라 exception_id 유지한 채 CALCULATION_PACK_OVERSIZE_REVIEW",
|
||||
"unreachable_in_v8": {
|
||||
"unresolved_asset_cluster_projection": "asset_cluster 계열이 Part 3 v.8 에서 소멸(P2·P3·LES 스키마·컴파일러 0회)",
|
||||
"unresolved_structure_role_projection": "registry structure_types 73/73 이 module·role_projection 전건 선언(결손 0)"
|
||||
},
|
||||
"unreachable_disposition": "pack 에 실리면 PART4_UNREACHABLE_EXCEPTION_TYPE 경성 실패"
|
||||
"unreachable_disposition": "pack 에 실리면 PART4_UNREACHABLE_EXCEPTION_TYPE 경성 실패",
|
||||
"conflict_note": "값이 다른 금액 정본이 함께 있다. BO 금액이 있으면 그것이 금액 본체이고 확정된 값이 아니다. selected_value_id 는 계산 근거 판정이며 금액을 바꾸지 않는다. 별개 사실일 수 있으므로 소장 금액은 변호사가 확인한다.",
|
||||
"related_values_note": "related_values 는 이 BO 와 연결된 값 표시이고 BO 금액이 아니다. BO 금액이 있으면 그것이 금액 본체이고 related_values 는 월세처럼 per 가 있는 별도 금액이다. BO 금액이 없으면 이율 같은 비금액과 요건사실에 언급만 된 금액도 들어 있을 수 있다. 소장 금액은 변호사가 확인한다."
|
||||
},
|
||||
"adjudication": {
|
||||
"accepted_status": [
|
||||
@@ -299,12 +301,9 @@
|
||||
"READY_NO_EXCEPTIONS",
|
||||
"READY_WITH_BLOCKS"
|
||||
],
|
||||
"allowed_patch_fields": [
|
||||
"amount"
|
||||
],
|
||||
"note": "허용 필드 밖 수정은 PART4_PATCH_REJECTED. F1 의 유일 생존 부류가 계산 근거 다중성 판정이므로 패치 가능 필드는 amount 하나다."
|
||||
"note": "F1 은 행 금액을 바꾸지 않는다. 계산 근거 판정은 amount JSON 의 conflict.selected_value_id 에만 남는다. Part 2 R1 과 같은 원칙이다 — 값이 다른 정본은 별개 사실일 수 있다. LLM 출력 이상은 멈추지 않고 UNRESOLVED 표시와 CALCULATION_BASIS_CONFLICT_REVIEW 로 내린다."
|
||||
},
|
||||
"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": [
|
||||
"UNREGISTERED_EFFECT_TYPE_REVIEW",
|
||||
"PART3_REGISTRY_SIDECAR_MISMATCH"
|
||||
@@ -349,10 +348,13 @@
|
||||
"EVIDENCE_REF_NOT_IN_EVIDENCE_UNIVERSE",
|
||||
"EMPTY_DERIVED_FACT",
|
||||
"NO_EVIDENCE_REFS",
|
||||
"NO_LINKED_LEGAL_EFFECT_STRUCTURE"
|
||||
"NO_LINKED_LEGAL_EFFECT_STRUCTURE",
|
||||
"CALCULATION_REQUEST_UNATTACHED_REVIEW",
|
||||
"CALCULATION_PACK_OVERSIZE_REVIEW"
|
||||
],
|
||||
"hard_failure_codes": [
|
||||
"PART4_ASSET_DEPLOYMENT_INCOMPLETE",
|
||||
"PART4_RUNTIME_MANIFEST_INVALID",
|
||||
"MODULE_MIRROR_UNREGISTERED",
|
||||
"MODULE_MIRROR_HASH_MISMATCH",
|
||||
"PART4_POLICY_INVALID",
|
||||
@@ -366,11 +368,8 @@
|
||||
"PART4_EFFECT_CONSERVATION_BROKEN",
|
||||
"PART4_CALC_CONSERVATION_BROKEN",
|
||||
"PART4_CALC_SOURCE_CONSERVATION_BROKEN",
|
||||
"PART4_COVERAGE_BROKEN",
|
||||
"PART4_PATCH_REJECTED",
|
||||
"PART4_BO_CONSERVATION_BROKEN",
|
||||
"PART4_FACT_ID_SEQUENCE_BROKEN",
|
||||
"PART4_ADJUDICATION_MISSING",
|
||||
"PART4_DOMAIN_EFFECT_NOT_ACTIVE",
|
||||
"PART4_LEDGER_SCHEMA_INVALID",
|
||||
"PART4_UNREACHABLE_EXCEPTION_TYPE",
|
||||
@@ -397,5 +396,10 @@
|
||||
"commercial_successor_effect": "commercial_successor",
|
||||
"actio_fields": "actio",
|
||||
"note": "구 4필드 별칭이 참조하는 module 어휘. 코드에 리터럴을 두지 않는다(정적 검사 11) — registry structure_types[].module 이 원천이고 이 선언은 그중 별칭 파생이 쓰는 세 값을 고정한다."
|
||||
}
|
||||
},
|
||||
"review_codes_hard_warning": [
|
||||
"CALCULATION_BASIS_CONFLICT_REVIEW",
|
||||
"GATE_FIRED_REVIEW"
|
||||
],
|
||||
"review_codes_note": "GATE_FIRED_REVIEW 는 blocks_final_drafting 게이트만 HARD_WARNING, 나머지는 SOFT_WARNING 이다."
|
||||
}
|
||||
|
||||
+16
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"schema_version": "stage1_seed_admission_policy.v1",
|
||||
"status": "ACTIVE",
|
||||
"purpose": "R0 가 이미 수행하는 전체 스키마 검증(worker_output_validator -> schema_subset_validator)의 결과를 등급으로 나누어 처리하는 규칙을 코드 밖에 선언한다. 구조 위반은 막고, 어휘·형태 위반은 정본으로 정규화하거나 정당한 자유 공간으로 수확한 뒤 검토로 남긴다. 값을 지어내지 않는다 — 표에 없는 낱말과 대조 불가능한 참조는 복구하지 않고 격리한다.",
|
||||
"purpose": "R0 가 이미 수행하는 전체 스키마 검증(worker_output_validator -> schema_subset_validator)의 결과를 등급으로 나누어 처리하는 규칙을 코드 밖에 선언한다. 구조 위반은 막고, 어휘·형태 위반은 정본으로 정규화하거나 정당한 자유 공간으로 수확한 뒤 검토로 남긴다. 값을 지어내지 않는다 — 표에 없는 낱말과 대조 불가능한 참조는 복구하지 않고 격리한다. 예외는 enum_unmapped_fallback 에 선언한 슬롯 status 하나다.",
|
||||
"authority": {
|
||||
"seed_contract": "task_c_bo_stage_b_domain_bo_seed.v3",
|
||||
"validator": "Default_Agent/stage1_runtime/worker_output_validator.txt",
|
||||
@@ -45,6 +45,7 @@
|
||||
"CALCULATION_REVIEW_MISSING": "review",
|
||||
"CALCULATION_DOMAIN_NOT_DECLARED": "review",
|
||||
"EVIDENCE_SLOT_NOT_DECLARED": "review",
|
||||
"STRUCTURE_TYPE_NOT_DECLARED": "review",
|
||||
"UNKNOWN_VALUE_REVIEW_MISSING": "review",
|
||||
"WORKER_BO_TYPE_UNREGISTERED": "review",
|
||||
"WORKER_DEPENDENCY_UNREGISTERED": "review",
|
||||
@@ -88,6 +89,10 @@
|
||||
"empty": "NO_SUPPORT"
|
||||
},
|
||||
"bo_seed_candidates[].evidence_slot_status[].status": {
|
||||
"filled": "filled",
|
||||
"partial": "partial",
|
||||
"missing": "missing",
|
||||
"conflicted": "conflicted",
|
||||
"supported": "filled",
|
||||
"proven": "filled",
|
||||
"sufficient": "filled",
|
||||
@@ -179,6 +184,12 @@
|
||||
},
|
||||
"enum_case_fold": true,
|
||||
"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": {
|
||||
"bo_seed_candidates[].element_fact_candidates[].source_id": {
|
||||
"rule": "first_universe_member_of_sibling_array",
|
||||
@@ -314,6 +325,10 @@
|
||||
"rule": "from_context",
|
||||
"key": "r0_membership_key"
|
||||
},
|
||||
"bo_seed_candidates[].evidence_slot_status[].status": {
|
||||
"rule": "constant",
|
||||
"value": "missing"
|
||||
},
|
||||
"bo_seed_candidates[].evidence_slot_status[].slot_id": {
|
||||
"rule": "rename_sibling",
|
||||
"sibling_candidates": [
|
||||
|
||||
+28
-6
@@ -29,6 +29,7 @@ REVIEW_CROSS_DOMAIN = "PART3_EFFECT_TYPE_CROSS_DOMAIN"
|
||||
REVIEW_CALC_DANGLING = "PART3_CALCULATION_REF_DANGLING"
|
||||
REVIEW_BO_UNATTACHED = "PART3_BO_UNATTACHED"
|
||||
REVIEW_BO_UNRESOLVED = "PART3_BO_DOMAIN_UNRESOLVED"
|
||||
REVIEW_ROUTE_NO_BO = "PART3_ROUTE_CANDIDATE_NOT_IN_BO"
|
||||
|
||||
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)
|
||||
if isinstance(row.get("domain_id"), str)}
|
||||
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]] = []
|
||||
audit: dict[str, Any] = {"sidecar_dialects": {}, "input_gaps": [],
|
||||
@@ -309,9 +311,6 @@ def compile_structure_seeds(activation_manifest: Any,
|
||||
record["registered_declared"] = item["registered"]
|
||||
if domain_id == e13_domain and 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
|
||||
|
||||
# ---------------- L0-2b · 슬라이스 투영 정합 ----------------
|
||||
@@ -395,6 +394,14 @@ def compile_structure_seeds(activation_manifest: Any,
|
||||
"type_id": type_id, "signal_id": route.get("signal_id"),
|
||||
"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")
|
||||
if isinstance(declared_flag, bool) and isinstance(registered, bool) \
|
||||
and declared_flag != registered:
|
||||
@@ -467,9 +474,21 @@ def compile_structure_seeds(activation_manifest: Any,
|
||||
continue
|
||||
keywords = _strings(bo.get("Legal_Keywords"))
|
||||
attached_here = False
|
||||
for domain_id in resolved:
|
||||
for type_id in keywords:
|
||||
record = records.get((domain_id, type_id))
|
||||
# 도메인을 건너 병합된 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")))
|
||||
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"]:
|
||||
@@ -497,6 +516,9 @@ def compile_structure_seeds(activation_manifest: Any,
|
||||
record["review_codes"].sort()
|
||||
if record["review_codes"]:
|
||||
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"
|
||||
bundle = {
|
||||
|
||||
+28
-6
@@ -29,6 +29,7 @@ REVIEW_CROSS_DOMAIN = "PART3_EFFECT_TYPE_CROSS_DOMAIN"
|
||||
REVIEW_CALC_DANGLING = "PART3_CALCULATION_REF_DANGLING"
|
||||
REVIEW_BO_UNATTACHED = "PART3_BO_UNATTACHED"
|
||||
REVIEW_BO_UNRESOLVED = "PART3_BO_DOMAIN_UNRESOLVED"
|
||||
REVIEW_ROUTE_NO_BO = "PART3_ROUTE_CANDIDATE_NOT_IN_BO"
|
||||
|
||||
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)
|
||||
if isinstance(row.get("domain_id"), str)}
|
||||
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]] = []
|
||||
audit: dict[str, Any] = {"sidecar_dialects": {}, "input_gaps": [],
|
||||
@@ -309,9 +311,6 @@ def compile_structure_seeds(activation_manifest: Any,
|
||||
record["registered_declared"] = item["registered"]
|
||||
if domain_id == e13_domain and 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
|
||||
|
||||
# ---------------- L0-2b · 슬라이스 투영 정합 ----------------
|
||||
@@ -395,6 +394,14 @@ def compile_structure_seeds(activation_manifest: Any,
|
||||
"type_id": type_id, "signal_id": route.get("signal_id"),
|
||||
"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")
|
||||
if isinstance(declared_flag, bool) and isinstance(registered, bool) \
|
||||
and declared_flag != registered:
|
||||
@@ -467,9 +474,21 @@ def compile_structure_seeds(activation_manifest: Any,
|
||||
continue
|
||||
keywords = _strings(bo.get("Legal_Keywords"))
|
||||
attached_here = False
|
||||
for domain_id in resolved:
|
||||
for type_id in keywords:
|
||||
record = records.get((domain_id, type_id))
|
||||
# 도메인을 건너 병합된 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")))
|
||||
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"]:
|
||||
@@ -497,6 +516,9 @@ def compile_structure_seeds(activation_manifest: Any,
|
||||
record["review_codes"].sort()
|
||||
if record["review_codes"]:
|
||||
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"
|
||||
bundle = {
|
||||
|
||||
+8
-4
@@ -39,12 +39,12 @@
|
||||
},
|
||||
"bo_attachment": {
|
||||
"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 검토로 싣는다.",
|
||||
"purpose": "원본 review_code 와 마찬가지로 — BO 연결을 잃지 않기 위해서다. SG 층의 source_bo_ids 가 비어 있어도 이 조인이 BO↔구조 연결을 세운다."
|
||||
},
|
||||
"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",
|
||||
"unlinked_rule": "봉투 참조에 연결되지 않은 SG-11 레코드는 구조에 싣지 않되 영수증에 미연결 계수로 형식화 기록한다.",
|
||||
"dangling_rule": "봉투에 있는데 SG-11 에 없는 참조는 PART3_CALCULATION_REF_DANGLING 검토."
|
||||
@@ -75,9 +75,13 @@
|
||||
"PART3_EFFECT_TYPE_CROSS_DOMAIN",
|
||||
"PART3_CALCULATION_REF_DANGLING",
|
||||
"PART3_BO_UNATTACHED",
|
||||
"PART3_BO_DOMAIN_UNRESOLVED"
|
||||
"PART3_BO_DOMAIN_UNRESOLVED",
|
||||
"PART3_ROUTE_CANDIDATE_NOT_IN_BO",
|
||||
"PART3_SIGNAL_MANIFEST_BLOCKED"
|
||||
],
|
||||
"hard_error_codes": [
|
||||
"PART3_READ_SET_MISMATCH",
|
||||
"PART3_SG01_COPY_MISMATCH",
|
||||
"PART3_ASSET_DEPLOYMENT_INCOMPLETE",
|
||||
"PART3_POLICY_INVALID",
|
||||
"PART3_STRUCTURE_SCHEMA_STALE",
|
||||
@@ -93,6 +97,6 @@
|
||||
"PART3_EXPECTED_RUNNABLE_EMPTY",
|
||||
"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 하나)의 사이드카 부재는 정상 — 스킵하고 영수증에 기록한다. 선언이 있는 도메인의 부재·미등재는 경성 실패다."
|
||||
}
|
||||
|
||||
+14
@@ -259,6 +259,7 @@ def validate_worker_output(
|
||||
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("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 = declared_candidates if isinstance(declared_candidates, list) else []
|
||||
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),
|
||||
"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")
|
||||
for order, slot in enumerate(slots if isinstance(slots, list) else []):
|
||||
slot_id = slot.get("slot_id") if isinstance(slot, dict) else None
|
||||
|
||||
+14
@@ -259,6 +259,7 @@ def validate_worker_output(
|
||||
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("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 = declared_candidates if isinstance(declared_candidates, list) else []
|
||||
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),
|
||||
"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")
|
||||
for order, slot in enumerate(slots if isinstance(slots, list) else []):
|
||||
slot_id = slot.get("slot_id") if isinstance(slot, dict) else None
|
||||
|
||||
+9
@@ -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 줄 출력 금지.
|
||||
+77
@@ -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)
|
||||
+1059
File diff suppressed because it is too large
Load Diff
+1059
File diff suppressed because it is too large
Load Diff
+265
@@ -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
|
||||
+90
@@ -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
|
||||
+164
@@ -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)
|
||||
+129
@@ -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)
|
||||
+85
@@ -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)
|
||||
+80
@@ -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)
|
||||
+69
@@ -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]
|
||||
+33
@@ -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)
|
||||
+13
@@ -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))])
|
||||
+24
@@ -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")})
|
||||
+21
@@ -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)
|
||||
+36
@@ -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])
|
||||
+45
@@ -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()
|
||||
+190
@@ -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"}]
|
||||
+45
@@ -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"))
|
||||
+48
@@ -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))
|
||||
+56
@@ -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")))
|
||||
+42
@@ -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"]])
|
||||
+20
@@ -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)])
|
||||
+42
@@ -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)
|
||||
+7
@@ -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}
|
||||
+8
@@ -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}
|
||||
+8
@@ -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}
|
||||
+8
@@ -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}
|
||||
+36
@@ -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")
|
||||
+17
@@ -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)
|
||||
+20
@@ -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
|
||||
+6
@@ -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
|
||||
+18
@@ -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
|
||||
+17
@@ -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()])]})
|
||||
+42
@@ -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()))
|
||||
+10
@@ -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)
|
||||
+24
@@ -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))
|
||||
+5
@@ -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])
|
||||
+19
@@ -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"})
|
||||
+35
@@ -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]})
|
||||
+9
@@ -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})
|
||||
+125
@@ -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])
|
||||
+32
@@ -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()
|
||||
+6
@@ -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)
|
||||
+5
@@ -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))
|
||||
+24
@@ -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)
|
||||
+39
@@ -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)
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
exec(open('r2base.py').read())
|
||||
SD=pathlib.Path("../seal/DA").resolve()
|
||||
D0=D; D=SD
|
||||
class SealFs(Fs):
|
||||
def __init__(self,mode,docs): self.docs=dict(docs); self.ov={}
|
||||
def get(self,p):
|
||||
if p in self.docs: return self.docs[p]
|
||||
if p.startswith("Default_Agent/"):
|
||||
f=SD/p[len("Default_Agent/"):]
|
||||
if f.exists(): return f.read_bytes().decode("utf-8")
|
||||
return None
|
||||
OLD=Fs
|
||||
Fs=SealFs
|
||||
ps=open("p2_seal.yml",encoding="utf-8").read().split("\n")
|
||||
R0SRC=code("Task_C_BO_R0_seed_reducer_and_exception_planner",ps);F0SRC=code("Task_C_BO_F0_final_bo_compiler_gate_writer",ps);S0SRC=code("Task_C_BO_S0_signal_bundle_writer",ps)
|
||||
def block_with(lines,needle):
|
||||
a=next(i for i,l in enumerate(lines) if needle in l); st=a
|
||||
while "code: |" not in lines[st]: st-=1
|
||||
ind=len(lines[st+1])-len(lines[st+1].lstrip()); b=[]
|
||||
for l in lines[st+1:]:
|
||||
if l.strip() and (len(l)-len(l.lstrip()))<ind: break
|
||||
b.append(l[ind:] if l.strip() else "")
|
||||
return "\n".join(b)
|
||||
A0=block_with(ps,"def assert_deployment")
|
||||
def gate(src,fsx,tag):
|
||||
purge(); s=src.replace(" _init()\n RESULT = main()\n"," RESULT = None\n").replace('if __name__ == "__main__":',"if False:")
|
||||
g=load(s,fsx,tag); g["_call"]=lambda n,a,m=None: fsx.call(n,a)
|
||||
return g["assert_deployment"]()
|
||||
fs=SealFs("V2",{})
|
||||
def t(lab,src,f):
|
||||
cnt[0]+=1
|
||||
try:
|
||||
r=gate(src,f,"sl%d"%cnt[0]); print(lab,"PASS",(len(r.get("entries",[])) if isinstance(r,dict) else r))
|
||||
except BaseException as e: print(lab,"멈춤",type(e).__name__,str(e)[:210])
|
||||
t("A0 새상수+새자산",A0,fs)
|
||||
t("A0 옛상수+새자산",A0.replace(re.search(r'EXPECTED_RUNTIME_MANIFEST_SHA256 = "([0-9a-f]{64})"',A0).group(1),"0cacaef800f1b3c1d75a1c84c42dc0bb312ab7aafe2262e3e15f32313b728d44"),fs)
|
||||
p3n=open("p3_new.yml",encoding="utf-8").read().split("\n"); p3r=open("p3_red.yml",encoding="utf-8").read().split("\n")
|
||||
t("P3 L0 게이트",block_with(p3n,"def assert_deployment"),fs); t("P3red L0 게이트",block_with(p3r,"def assert_deployment"),fs); t("P4 게이트",block_with(p4,"def assert_deployment"),fs)
|
||||
class Partial(SealFs):
|
||||
bad=None
|
||||
def get(self,p):
|
||||
if p==self.bad: return (D0/p[len("Default_Agent/"):]).read_bytes().decode("utf-8")
|
||||
return SealFs.get(self,p)
|
||||
for rel in ("signals/adapters/s3_domain_seed_adapter.txt","stage1_runtime/structure_index_compiler.txt","stage1_runtime/fact_ledger_compiler.txt","stage1_runtime/structure_index_policy.v1.json"):
|
||||
f=Partial("V2",{}); f.bad="Default_Agent/"+rel
|
||||
t("부분배포 %s: A0"%rel.split("/")[-1],A0,f); t(" P3",block_with(p3n,"def assert_deployment"),f); t(" P4",block_with(p4,"def assert_deployment"),f)
|
||||
# 봉인 트리 전 구간
|
||||
L2_=L2
|
||||
T2,T3="money_claim","commercial_successor"
|
||||
o=scen({"E-02":[dseed(1,T2,"같은행위",calculation_requests=[{"calculation_domain":"CE-01","completeness":"ready","source_refs":["EV-1"]}])],"E-03":[dseed(1,[T3,T2],"같은행위",legal_effect_candidates=[L(type_id=T3,q=1),L(type_id=T2)],calculation_requests=[{"calculation_domain":"CE-01","completeness":"partial","source_refs":["EV-2"]}])]})
|
||||
print(S(o),o.get("codes")); print(recs(o)); print(rj(o["_fs"],"validation_assets/routing/part3_receipt.json")["deployment_gate"]["runtime_manifest_sha256"][:12], rj(o["_fs"],"validation_assets/routing/part4_receipt.json")["deployment_gate"]["runtime_manifest_sha256"][:12])
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
exec(open('r2base.py').read())
|
||||
def strict(fs):
|
||||
bad=[]
|
||||
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") if "load_json_strict" in S2 else v)
|
||||
except BaseException as e: bad.append((k,type(e).__name__,str(e)[:70]))
|
||||
return bad
|
||||
def wxs(fs):
|
||||
out=[]
|
||||
for f in ("legal_effect_routes","legal_relation_lifecycle_signals","defense_exception_signals","calculation_requirements"):
|
||||
for r in sigs(fs,f):
|
||||
if "worker_extra" in r["details"]: out.append((f,r["signal_id"],str(r["details"]["worker_extra"])[:80],len(str(r["details"]["worker_extra"]))))
|
||||
return out
|
||||
print("load_json_strict" in S2)
|
||||
CALC={"calculation_domain":"CE-01","completeness":"ready","source_refs":["EV-1"]}
|
||||
CASES={
|
||||
"effect worker_extra self":lambda:dseed(1,None,legal_effect_candidates=[L(worker_extra={"a":1})]),
|
||||
"effect NaN":lambda:dseed(1,None,legal_effect_candidates=[L(z=float("nan"))]),
|
||||
"effect Inf":lambda:dseed(1,None,legal_effect_candidates=[L(z=float("inf"))]),
|
||||
"element NaN":lambda:dseed(1,"money_claim",element_fact_candidates=[ev(z=float("nan"))]),
|
||||
"defense NaN":lambda:dseed(1,"money_claim",defense_candidates=[ev(z=float("nan"))]),
|
||||
"calc NaN":lambda:dseed(1,"money_claim",calculation_requests=[dict(CALC,z=float("nan"))]),
|
||||
"payload NaN":lambda:dseed(1,"money_claim",element_fact_candidates=[ev(payload={"z":float("nan")})]),
|
||||
"effect surrogate":lambda:dseed(1,None,legal_effect_candidates=[L(z="\ud800")]),
|
||||
"element surrogate":lambda:dseed(1,"money_claim",element_fact_candidates=[ev(z="\ud800")]),
|
||||
"excerpt surrogate(스키마칸)":lambda:dseed(1,"money_claim",element_fact_candidates=[ev(excerpt="\ud800")]),
|
||||
}
|
||||
for nm,mk in CASES.items():
|
||||
for m in ("CUR","V2"):
|
||||
o=scen({"E-02":[dseed(2,"money_claim"),mk()]},mode=m); fs=o["_fs"]
|
||||
st={k:str(v)[:130] for k,v in S(o).items() if k in("S0","man","F2") or "EXC" in str(v) or "Error" in str(v)}
|
||||
print("##",nm,m,st, "strict",strict(fs) if str(o.get("S0")).startswith("READY") else "-", "wx",wxs(fs)[:1] if str(o.get("S0")).startswith("READY") else "-")
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
src=open('t_wx.py').read().replace("exec(open('r2base.py').read())","exec(open('r2base.py').read()); exec(open('r2fix.py').read()); use_fix(True)").replace('for m in ("CUR","V2"):','for m in ("V2",):')
|
||||
exec(src)
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
# r_p7 실행법
|
||||
임시 폴더 X/w 에서 (harness/README.md 와 part_3_v.2 §7 5단계 구성 + 아래):
|
||||
python3 patch_final.py <Default_Agent>; cp p2_new.yml p2_addendum.yml
|
||||
python3 patch_p3.py; python3 mk_red.py; mv p3_red.yml p3_red_keep.yml; python3 patch_p3_v2.py; cp p3_v2.yml p3_new.yml
|
||||
python3 patch_p7.py; cp p2_new.yml p2_p7.yml
|
||||
# p2_fix.yml 이 있으면 rig.py 가 FIX 로 적재한다(q5_fix.py, q5_rev.py)
|
||||
시험: q1_repro q1_effect(§2.4) / q2_apply_doc(문서만으로 적용) / q3_direct q3_nested q3_oracle(공격·변성 오라클) /
|
||||
q4_fuzz q4_budget q4_replay q4_class(차등 퍼저·회귀) / q5_count q5_fix q5_rev(주장 확인)
|
||||
주의: out/q4n_* 는 NODOT 필터 교체 전에 시작되어 점 든 키가 포함된 일반 퍼저 결과다. tmp* 폴더가 수 GB 쌓이니 라운드마다 지운다.
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
rounds 150 seed 909
|
||||
(CURo,V2o,V2) ok -> {(False, False, True): 88, (False, False, False): 20, (True, True, True): 35, (False, True, True): 7}
|
||||
stops CURo {('L0', 'PART3_FINAL_SCHEMA_VALIDATION_FAILED'): 95, ('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 11, ('F0', 'SystemExit:1'): 9}
|
||||
stops V2o {('L0', 'PART3_FINAL_SCHEMA_VALIDATION_FAILED'): 88, ('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 11, ('F0', 'SystemExit:1'): 9}
|
||||
stops V2 {('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 11, ('F0', 'SystemExit:1'): 9}
|
||||
bad {}
|
||||
m2 fired {False: 120, True: 10}
|
||||
s2 {'review_ok': 130, ('LES_BO_JOIN', 'PASS'): 130, ('LES_REVERSE_INDEX', 'PASS'): 130}
|
||||
gap
|
||||
empty:OTHER 1
|
||||
empty:OTHER|reg_bad 1
|
||||
empty:bo_absent 5
|
||||
empty:bo_absent+cross 2
|
||||
empty:bo_absent+cross|bo_absent+reg_bad+cross 1
|
||||
empty:bo_absent+cross|cross 1
|
||||
empty:bo_absent+cross|cross|reg_bad+cross 1
|
||||
empty:bo_absent+reg_bad 8
|
||||
empty:bo_absent+reg_bad+cross 7
|
||||
empty:bo_absent+reg_bad+cross|reg_bad+cross 1
|
||||
empty:bo_absent+reg_bad|cross|reg_bad+cross 1
|
||||
empty:bo_absent+reg_bad|reg_bad+cross 2
|
||||
empty:bo_absent|bo_absent+cross|bo_absent+reg_bad|bo_absent+reg_bad+cross 1
|
||||
empty:bo_absent|bo_absent+reg_bad+cross|cross 1
|
||||
empty:bo_absent|bo_absent+reg_bad|bo_absent+reg_bad+cross 1
|
||||
empty:bo_absent|bo_absent+reg_bad|cross 1
|
||||
empty:bo_absent|reg_bad+cross 3
|
||||
empty:cross 2
|
||||
empty:reg_bad 4
|
||||
empty:reg_bad+cross 2
|
||||
('kw', 'reg_bad', 'other', 'single', 'bo_none', 'CROSS+UNATT+M2') 4
|
||||
('kw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+UNATT+M2') 1
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_none', 'CROSS+M2') 1
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_none', 'CROSS+UNATT+M2') 6
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_there', 'CROSS+UNATT') 161
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_there', 'CROSS+UNATT+M2') 35
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_none', 'CROSS+M2') 3
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_none', 'CROSS+UNATT+M2') 6
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS') 1
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+M2') 1
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+UNATT') 19
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+UNATT+M2') 8
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_none', 'M2') 1
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_none', 'UNATT+M2') 4
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_there', 'M2') 1
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_there', 'SILENT') 4
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_there', 'UNATT') 19
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_there', 'UNATT+M2') 13
|
||||
('nokw', 'reg_ok', 'other', 'single', 'bo_none', 'CROSS+UNATT+M2') 3
|
||||
('nokw', 'reg_ok', 'other', 'single', 'bo_there', 'CROSS+UNATT') 1
|
||||
('nokw', 'reg_ok', 'own', 'single', 'bo_none', 'UNATT+M2') 2
|
||||
third2 [[128, "LES-E-03-money_claim", "E-03:001", "bh1", [], null, ["E-03:001"], {"candidate_ref": "E-03:001", "registered": false, "review_code": 7, "source_refs": ["EV-1"], "source_seed_id": "s4", "type_id": "money_claim"}, "s4", null, [{"type_id": {"x": 1}, "registered": "yes", "source_refs": "EV-1", "bo_absent": "true", "worker_extra": {"z": 1}, "review_code": "X_Y", "candidate_ref": "E-99:001"}, {"type_id": "money_claim", "registered": false, "source_refs": ["EV-1"], "review_code": 7}, {"type_id": null, "registered": false, "source_refs": ["EV-1"], "candidate_ref": {"x": 1}, "bo_absent": 1}, {"type_id": {"status": "BLOCKED", "blocked": true}, "registered": true, "source_refs": ["EV-1"], "review_code": null, "raw_type_id": {"a": 1}, "worker_extra": "q"}], []], [139, "LES-E-02-money_claim", "E-02:003", "bh2", [], null, ["E-02:003"], {"candidate_ref": "E-02:003", "registered": false, "source_refs": null, "source_seed_id": "s1", "type_id": "money_claim"}, "s1", null, [{"type_id": "money_claim", "registered": {}, "source_refs": ["EV-2", "EV-3"]}, {"type_id": "fraudulent_transfer", "registered": 0, "source_refs": ["EV-1"]}, {"type_id": "money_claim", "registered": false, "source_refs": null}], [{"decision": "MERGE", "input_candidate_refs": ["E-02:001", "E-03:001"], "merge_target_ref": "E-03:001"}]]]
|
||||
third [["LES-E-03-money_claim", "E-03:001", "bh1", [], {"source_event_candidate_ids": [], "source_meeting_clause_ids": [], "source_domain": "E-03"}, {"candidate_ref": "E-03:001", "registered": false, "review_code": 7, "source_refs": ["EV-1"], "source_seed_id": "s4", "type_id": "money_claim"}], ["LES-E-02-money_claim", "E-02:003", "bh2", [], {"source_event_candidate_ids": [], "source_meeting_clause_ids": [], "source_domain": "E-02"}, {"candidate_ref": "E-02:003", "registered": false, "source_refs": null, "source_seed_id": "s1", "type_id": "money_claim"}]]
|
||||
silent ex [["LES-E-03-general_legal_effect", "sg13-ee4ecfb6507a66d7", "bh2", ["money_claim"], 1], ["LES-E-02-general_legal_effect", "sg13-cf2469e81a0dd0e5", "bh6", ["money_claim"], "true"], ["LES-E-02-general_legal_effect", "sg13-fd4bf67562df8e5f", "bh6", ["money_claim"], 1], ["LES-E-02-general_legal_effect", "sg13-c6fee94574ece6b9", "bh5", ["money_claim", "매매"], null]]
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
rounds 150 seed 909
|
||||
(CURo,V2o,V2) ok -> {(False, False, True): 88, (False, False, False): 20, (True, True, True): 35, (False, True, True): 7}
|
||||
stops CURo {('L0', 'PART3_FINAL_SCHEMA_VALIDATION_FAILED'): 95, ('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 11, ('F0', 'SystemExit:1'): 9}
|
||||
stops V2o {('L0', 'PART3_FINAL_SCHEMA_VALIDATION_FAILED'): 88, ('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 11, ('F0', 'SystemExit:1'): 9}
|
||||
stops V2 {('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 11, ('F0', 'SystemExit:1'): 9}
|
||||
bad {}
|
||||
m2 fired {False: 122, True: 8}
|
||||
s2 {'review_ok': 130, ('LES_BO_JOIN', 'PASS'): 130, ('LES_REVERSE_INDEX', 'PASS'): 130}
|
||||
gap
|
||||
empty:bo_absent 5
|
||||
empty:bo_absent+cross 2
|
||||
empty:bo_absent+cross|bo_absent+reg_bad+cross 1
|
||||
empty:bo_absent+cross|cross 1
|
||||
empty:bo_absent+cross|cross|reg_bad+cross 1
|
||||
empty:bo_absent+reg_bad 8
|
||||
empty:bo_absent+reg_bad+cross 7
|
||||
empty:bo_absent+reg_bad+cross|reg_bad+cross 1
|
||||
empty:bo_absent+reg_bad|cross|reg_bad+cross 1
|
||||
empty:bo_absent+reg_bad|reg_bad+cross 2
|
||||
empty:bo_absent|bo_absent+cross|bo_absent+reg_bad|bo_absent+reg_bad+cross 1
|
||||
empty:bo_absent|bo_absent+reg_bad+cross|cross 1
|
||||
empty:bo_absent|bo_absent+reg_bad|bo_absent+reg_bad+cross 1
|
||||
empty:bo_absent|bo_absent+reg_bad|cross 1
|
||||
empty:bo_absent|reg_bad+cross 3
|
||||
empty:cross 2
|
||||
empty:reg_bad 4
|
||||
empty:reg_bad+cross 2
|
||||
('kw', 'reg_bad', 'other', 'single', 'bo_none', 'CROSS+UNATT+M2') 4
|
||||
('kw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+UNATT+M2') 1
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_none', 'CROSS+M2') 1
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_none', 'CROSS+UNATT+M2') 9
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_there', 'CROSS+UNATT') 162
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_there', 'CROSS+UNATT+M2') 35
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_none', 'CROSS+M2') 3
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_none', 'CROSS+UNATT+M2') 6
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS') 1
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+M2') 1
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+UNATT') 19
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+UNATT+M2') 8
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_none', 'M2') 1
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_none', 'UNATT+M2') 3
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_there', 'M2') 1
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_there', 'SILENT') 4
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_there', 'UNATT') 19
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_there', 'UNATT+M2') 10
|
||||
third2 []
|
||||
third []
|
||||
silent ex [["LES-E-03-general_legal_effect", "sg13-ee4ecfb6507a66d7", "bh2", ["money_claim"], 1], ["LES-E-02-general_legal_effect", "sg13-cf2469e81a0dd0e5", "bh6", ["money_claim"], "true"], ["LES-E-02-general_legal_effect", "sg13-fd4bf67562df8e5f", "bh6", ["money_claim"], 1], ["LES-E-02-general_legal_effect", "sg13-c6fee94574ece6b9", "bh5", ["money_claim", "매매"], null]]
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
rounds 400 seed 910
|
||||
(CURo,V2o,V2) ok -> {(True, True, True): 79, (False, False, True): 210, (False, False, False): 80, (False, True, True): 31}
|
||||
stops CURo {('L0', 'PART3_FINAL_SCHEMA_VALIDATION_FAILED'): 240, ('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 27, ('F0', 'SystemExit:1'): 53, ('F2', 'PART4_CALC_CONSERVATION_BROKEN'): 1}
|
||||
stops V2o {('L0', 'PART3_FINAL_SCHEMA_VALIDATION_FAILED'): 210, ('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 27, ('F0', 'SystemExit:1'): 53}
|
||||
stops V2 {('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 27, ('F0', 'SystemExit:1'): 53}
|
||||
bad {}
|
||||
m2 fired {False: 292, True: 28}
|
||||
s2 {'review_ok': 320, ('LES_BO_JOIN', 'PASS'): 320, ('LES_REVERSE_INDEX', 'PASS'): 320}
|
||||
gap
|
||||
empty:bo_absent 7
|
||||
empty:bo_absent+cross 10
|
||||
empty:bo_absent+cross|bo_absent+reg_bad 2
|
||||
empty:bo_absent+cross|bo_absent+reg_bad+cross 5
|
||||
empty:bo_absent+cross|bo_absent+reg_bad+cross|reg_bad+cross 2
|
||||
empty:bo_absent+cross|bo_absent+reg_bad|bo_absent+reg_bad+cross 1
|
||||
empty:bo_absent+cross|bo_absent+reg_bad|bo_absent+reg_bad+cross|reg_bad+cross 1
|
||||
empty:bo_absent+cross|cross 1
|
||||
empty:bo_absent+cross|reg_bad 2
|
||||
empty:bo_absent+cross|reg_bad+cross 1
|
||||
empty:bo_absent+reg_bad 13
|
||||
empty:bo_absent+reg_bad+cross 15
|
||||
empty:bo_absent+reg_bad+cross|cross|reg_bad+cross 3
|
||||
empty:bo_absent+reg_bad+cross|reg_bad 2
|
||||
empty:bo_absent+reg_bad+cross|reg_bad+cross 2
|
||||
empty:bo_absent+reg_bad|bo_absent+reg_bad+cross 2
|
||||
empty:bo_absent+reg_bad|bo_absent+reg_bad+cross|cross 1
|
||||
empty:bo_absent+reg_bad|bo_absent+reg_bad+cross|cross|reg_bad+cross 1
|
||||
empty:bo_absent+reg_bad|bo_absent+reg_bad+cross|reg_bad 1
|
||||
empty:bo_absent+reg_bad|cross 1
|
||||
empty:bo_absent+reg_bad|reg_bad+cross 2
|
||||
empty:bo_absent|bo_absent+cross|bo_absent+reg_bad 1
|
||||
empty:bo_absent|bo_absent+cross|bo_absent+reg_bad|bo_absent+reg_bad+cross|reg_bad+cross 1
|
||||
empty:bo_absent|bo_absent+cross|bo_absent+reg_bad|reg_bad+cross 1
|
||||
empty:bo_absent|bo_absent+reg_bad 2
|
||||
empty:bo_absent|bo_absent+reg_bad+cross 3
|
||||
empty:bo_absent|bo_absent+reg_bad+cross|cross|reg_bad+cross 1
|
||||
empty:bo_absent|bo_absent+reg_bad|bo_absent+reg_bad+cross 1
|
||||
empty:bo_absent|bo_absent+reg_bad|bo_absent+reg_bad+cross|cross|reg_bad+cross 1
|
||||
empty:bo_absent|bo_absent+reg_bad|reg_bad 1
|
||||
empty:bo_absent|reg_bad 1
|
||||
empty:cross 5
|
||||
empty:cross|reg_bad+cross 6
|
||||
empty:reg_bad 7
|
||||
empty:reg_bad+cross 16
|
||||
empty:reg_bad|reg_bad+cross 1
|
||||
('kw', 'reg_bad', 'other', 'single', 'bo_none', 'CROSS+M2') 1
|
||||
('kw', 'reg_bad', 'other', 'single', 'bo_none', 'CROSS+UNATT+M2') 13
|
||||
('kw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+M2') 2
|
||||
('kw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+UNATT') 2
|
||||
('kw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+UNATT+M2') 3
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_none', 'CROSS+M2') 5
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_none', 'CROSS+UNATT+M2') 26
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_there', 'CROSS+UNATT') 366
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_there', 'CROSS+UNATT+M2') 161
|
||||
('nokw', 'reg_bad', 'other', 'merged', 'bo_none', 'CROSS+M2') 3
|
||||
('nokw', 'reg_bad', 'other', 'merged', 'bo_there', 'CROSS') 2
|
||||
('nokw', 'reg_bad', 'other', 'merged', 'bo_there', 'CROSS+UNATT') 1
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_none', 'CROSS+M2') 5
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_none', 'CROSS+UNATT+M2') 35
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS') 7
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+M2') 3
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+UNATT') 40
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+UNATT+M2') 17
|
||||
('nokw', 'reg_bad', 'own', 'merged', 'bo_there', 'UNATT') 1
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_none', 'M2') 2
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_none', 'UNATT+M2') 21
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_there', 'SILENT') 7
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_there', 'UNATT') 32
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_there', 'UNATT+M2') 11
|
||||
third2 []
|
||||
third []
|
||||
silent ex [["LES-E-03-general_legal_effect", "sg13-0f8ac8521cc33019", "bh9", ["money_claim"], null], ["LES-E-03-general_legal_effect", "sg13-416f9ee9f998d3de", "bh9", ["money_claim"], null], ["LES-E-03-general_legal_effect", "sg13-249a0c537c30d6af", "bh11", ["money_claim"], 1], ["LES-E-03-general_legal_effect", "sg13-6502dbb749016b2e", "bh11", ["money_claim"], 1]]
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
rounds 400 seed 911
|
||||
(CURo,V2o,V2) ok -> {(True, True, True): 73, (False, False, True): 211, (False, False, False): 91, (False, True, True): 25}
|
||||
stops CURo {('L0', 'PART3_FINAL_SCHEMA_VALIDATION_FAILED'): 235, ('F0', 'SystemExit:1'): 47, ('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 43, ('F2', 'PART4_CALC_CONSERVATION_BROKEN'): 2}
|
||||
stops V2o {('L0', 'PART3_FINAL_SCHEMA_VALIDATION_FAILED'): 211, ('F0', 'SystemExit:1'): 47, ('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 44}
|
||||
stops V2 {('F0', 'SystemExit:1'): 47, ('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 44}
|
||||
bad {}
|
||||
m2 fired {False: 283, True: 26}
|
||||
s2 {'review_ok': 309, ('LES_BO_JOIN', 'PASS'): 309, ('LES_REVERSE_INDEX', 'PASS'): 309}
|
||||
gap
|
||||
empty:bo_absent 4
|
||||
empty:bo_absent+cross 10
|
||||
empty:bo_absent+cross|bo_absent+reg_bad 1
|
||||
empty:bo_absent+cross|bo_absent+reg_bad+cross 5
|
||||
empty:bo_absent+cross|bo_absent+reg_bad|bo_absent+reg_bad+cross 1
|
||||
empty:bo_absent+cross|bo_absent+reg_bad|bo_absent+reg_bad+cross|cross|reg_bad+cross 1
|
||||
empty:bo_absent+reg_bad 18
|
||||
empty:bo_absent+reg_bad+cross 18
|
||||
empty:bo_absent+reg_bad+cross|cross 1
|
||||
empty:bo_absent+reg_bad|bo_absent+reg_bad+cross 3
|
||||
empty:bo_absent+reg_bad|bo_absent+reg_bad+cross|cross 1
|
||||
empty:bo_absent+reg_bad|cross 1
|
||||
empty:bo_absent+reg_bad|cross|reg_bad+cross 1
|
||||
empty:bo_absent+reg_bad|reg_bad+cross 1
|
||||
empty:bo_absent|bo_absent+cross|bo_absent+reg_bad+cross|reg_bad|reg_bad+cross 1
|
||||
empty:bo_absent|bo_absent+cross|bo_absent+reg_bad|bo_absent+reg_bad+cross 1
|
||||
empty:bo_absent|bo_absent+reg_bad 4
|
||||
empty:bo_absent|bo_absent+reg_bad+cross|reg_bad+cross 1
|
||||
empty:bo_absent|bo_absent+reg_bad|bo_absent+reg_bad+cross 1
|
||||
empty:cross 4
|
||||
empty:cross|reg_bad+cross 2
|
||||
empty:cross|reg_bad|reg_bad+cross 1
|
||||
empty:reg_bad 13
|
||||
empty:reg_bad+cross 9
|
||||
empty:reg_bad|reg_bad+cross 1
|
||||
('kw', 'reg_bad', 'other', 'single', 'bo_none', 'CROSS+UNATT+M2') 6
|
||||
('kw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+UNATT') 4
|
||||
('kw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+UNATT+M2') 1
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_none', 'CROSS+UNATT+M2') 15
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_there', 'CROSS') 1
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_there', 'CROSS+M2') 2
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_there', 'CROSS+UNATT') 373
|
||||
('kw', 'reg_ok', 'other', 'single', 'bo_there', 'CROSS+UNATT+M2') 148
|
||||
('nokw', 'reg_bad', 'other', 'merged', 'bo_none', 'CROSS+UNATT+M2') 2
|
||||
('nokw', 'reg_bad', 'other', 'merged', 'bo_there', 'CROSS+UNATT') 1
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_none', 'CROSS+M2') 1
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_none', 'CROSS+UNATT+M2') 15
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS') 1
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+M2') 3
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+UNATT') 32
|
||||
('nokw', 'reg_bad', 'other', 'single', 'bo_there', 'CROSS+UNATT+M2') 18
|
||||
('nokw', 'reg_bad', 'own', 'merged', 'bo_there', 'SILENT') 6
|
||||
('nokw', 'reg_bad', 'own', 'merged', 'bo_there', 'UNATT') 1
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_none', 'M2') 4
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_none', 'UNATT+M2') 14
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_there', 'M2') 1
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_there', 'SILENT') 1
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_there', 'UNATT') 31
|
||||
('nokw', 'reg_bad', 'own', 'single', 'bo_there', 'UNATT+M2') 6
|
||||
third2 []
|
||||
third []
|
||||
silent ex [["LES-E-00-general_legal_effect", "sg13-3ca2c3e5b5f3ccbc", "bh5", ["commercial_successor", "money_claim"], "true"], ["LES-E-00-general_legal_effect", "sg13-34aa22f4b7c13fd1", "bh5", ["money_claim"], null], ["LES-E-00-general_legal_effect", "sg13-5c3a4ecebb72edc6", "bh5", ["money_claim"], "yes"], ["LES-E-00-general_legal_effect", "sg13-e676cd41d7b4f75c", "bh5", ["money_claim"], null]]
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
REG 177 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 4, "seen": 9, "ratio": 0.4444, "max_ratio": 0.34} {"E-03": [{"seed_id": "s1", "bo_type": "event", "source_refs": ["EV-2"], "element_fact_candidates": [{"source_id": "EV-2", "source_kind": "evidence", "excerpt": "본문1", "payload": {}}], "opposing_fact_candidates": [5], "defense_candidates": [{"source_id": "EV-2", "source_kind": "evidence", "payload": {}}], "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": "다른행위", "action_type": "법률행위(legal acts)
|
||||
REG 196 F0 SystemExit:1 {"E-02": [{"seed_id": "s4", "bo_type": "event", "source_refs": ["EV-1"], "element_fact_candidates": [{"source_id": "EV-1", "source_kind": "evidence", "excerpt": "e6", "payload": {}}], "opposing_fact_candidates": [{"source_id": "EVT-1", "source_kind": "evidence", "excerpt": "e81", "payload": {}}, {"source_id": "MC-1", "source_kind": "evidence", "excerpt": "e15", "payload": {}}, {"source_id": "한글 값", "source_kind": "evidence", "excerpt": null, "payload": {}}, {"source_id": "EV-1", "source_kind": "evidence", "excerpt": "e80", "payload": {}}, {"source_id": "EV-1", "payload": {}}], "defense_candida
|
||||
REG 325 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 2, "seen": 3, "ratio": 0.6667, "max_ratio": 0.34} {"E-13": [{"seed_id": "s4", "bo_type": "event", "source_refs": ["EV-1"], "element_fact_candidates": [{"source_id": "EV-1", "source_kind": "X", "excerpt": "X", "payload": {}, "content": "CE-02"}], "opposing_fact_candidates": [], "defense_candidates": [], "evidence_slot_status": [], "calculation_requests": [{}, {"calculation_domain": "CE-01", "completeness": "ready", "source_refs": ["EV-999"]}, {"calculation_domain": "CE-01", "completeness": "partial", "source_refs": ["EV-2", "EV-3"], "review_code": "XX_YY"}, {"calculation_domain": 1, "completeness": "partial", "source_refs": "X", "review_code":
|
||||
rounds 1500 seed 11 (ADDok,P7ok) {(True, True): 1070, (False, False): 424, (True, False): 5, (False, True): 1}
|
||||
stops ADD {('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 345, ('F0', 'SystemExit:1'): 80}
|
||||
stops P7 {('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 347, ('F0', 'SystemExit:1'): 82}
|
||||
reg Counter({('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 3, ('F0', 'SystemExit:1'): 2})
|
||||
rel Counter({('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 1})
|
||||
identical 42
|
||||
diff docs [('stage1_part2_review_handoff.json', 1028), ('postb_seed_ledger.json', 955), ('part4_receipt.json', 731), ('E-13.json', 603), ('E-02.json', 591), ('E-03.json', 583), ('part3_receipt.json', 246), ('fact_ledger_candidate_bundle.json', 224), ('structure_seed_bundle.json', 209), ('legal_effect_structures.json', 209), ('signal_manifest.json', 147), ('BO.json', 145), ('domain_signals', 131), ('fact_ledger_writer_report.json', 115), ('Fact_Ledger_base.json', 115), ('stage1_part4_review_handoff.json', 103), ('stage1_part3_review_handoff.json', 96), ('postb_compiled_bundle_compact.json', 66), ('legal_effect_routes.json', 25), ('calculation_requirements.json', 17)]
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
REG 624 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 3, "seen": 7, "ratio": 0.4286, "max_ratio": 0.34} {"E-02": [{"seed_id": "s1", "bo_type": "event", "source_refs": ["EV-2"], "element_fact_candidates": [{"source_id": "EV-2", "source_kind": "evidence", "excerpt": "본문1", "payload": {}}], "opposing_fact_candidates": [], "defense_candidates": [], "evidence_slot_status": [{"slot_id": "e.el09", "status": "filled", "source_refs": [], "review_code": "XX_YY"}, {"status": "partial", "source_refs": ["EVT-1"], "review_code": "XX_YY", "x.y": null}], "calculation_requests": [{"calculation_domain": "CE-01", "completeness": "partial", "source_refs": ["EV-1"], "review_code": "XX_YY"}, "x"], "dependency_refs":
|
||||
REG 688 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 2, "seen": 5, "ratio": 0.4, "max_ratio": 0.34} {"E-02": [{"seed_id": "s2", "bo_type": "event", "source_refs": ["EV-3"], "element_fact_candidates": [{"source_id": "EV-3", "source_kind": "evidence", "excerpt": "본문2", "payload": {}}], "opposing_fact_candidates": [{"source_id": "MC-1", "source_kind": "evidence", "excerpt": "e60", "payload": {}}, {"source_id": "EVT-1", "source_kind": "complete", "excerpt": "e59", "payload": {}, "content": "CE-02", "value": ["EV-2"]}, {"source_id": "EV-1", "source_kind": "complete", "excerpt": "e75", "payload": {}}, {"source_id": "MC-1", "source_kind": "evidence", "excerpt": "e37", "payload": {}, "a[1]": {"excer
|
||||
REG 750 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 3, "seen": 7, "ratio": 0.4286, "max_ratio": 0.34} {"E-02": [{"seed_id": "s4", "bo_type": "event", "source_refs": ["EV-1"], "element_fact_candidates": [{"excerpt": "e36", "payload": null}, {"source_id": "EV-2", "source_kind": "evidence", "excerpt": "e62", "payload": {}}], "opposing_fact_candidates": [{"source_id": null, "source_kind": "evidence", "payload": {}}, {"source_id": "MC-1", "source_kind": "evidence", "excerpt": "e22", "payload": {}}, {"source_id": "EV-2", "source_kind": 7, "excerpt": "e68", "payload": {}}, {"source_id": "MC-1", "source_kind": "evidence", "excerpt": "e71", "payload": {}}, {"source_id": "EVT-1", "source_kind": "evidenc
|
||||
rounds 1500 seed 22 (ADDok,P7ok) {(True, True): 1049, (False, False): 440, (False, True): 3, (True, False): 8}
|
||||
stops ADD {('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 354, ('F0', 'SystemExit:1'): 89}
|
||||
stops P7 {('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 357, ('F0', 'SystemExit:1'): 91}
|
||||
reg Counter({('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 7, ('F0', 'SystemExit:1'): 1})
|
||||
rel Counter({('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 3})
|
||||
identical 49
|
||||
diff docs [('stage1_part2_review_handoff.json', 1000), ('postb_seed_ledger.json', 916), ('part4_receipt.json', 710), ('E-02.json', 575), ('E-03.json', 575), ('E-13.json', 560), ('part3_receipt.json', 223), ('fact_ledger_candidate_bundle.json', 193), ('structure_seed_bundle.json', 179), ('legal_effect_structures.json', 179), ('BO.json', 133), ('signal_manifest.json', 123), ('domain_signals', 113), ('Fact_Ledger_base.json', 100), ('fact_ledger_writer_report.json', 100), ('stage1_part4_review_handoff.json', 84), ('stage1_part3_review_handoff.json', 78), ('postb_compiled_bundle_compact.json', 67), ('legal_effect_routes.json', 20), ('calculation_requirements.json', 12)]
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
REG 56 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 3, "seen": 7, "ratio": 0.4286, "max_ratio": 0.34} {"E-02": [{"seed_id": "s2", "bo_type": "event", "source_refs": ["EV-3"], "element_fact_candidates": [{"source_id": "EV-1", "source_kind": "SUPPORTED", "excerpt": "e26", "payload": {}}], "opposing_fact_candidates": [{"source_id": "EV-2", "source_kind": "evidence", "excerpt": "e11", "payload": {}}, {"source_id": "EV-1", "source_kind": "evidence", "excerpt": "e55", "payload": {}}, {"source_id": "EV-1", "source_kind": "evidence", "excerpt": "e90", "payload": {}}], "defense_candidates": [], "evidence_slot_status": [{"status": "filled", "source_refs": ["EVT-1"], "component_id": "e.el05"}], "calculat
|
||||
REG 124 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 4, "seen": 9, "ratio": 0.4444, "max_ratio": 0.34} {"E-13": [{"seed_id": "s3", "bo_type": "event", "source_refs": ["EV-4"], "element_fact_candidates": [{"source_id": "EV-4", "source_kind": "evidence", "excerpt": "본문3", "payload": {}}], "opposing_fact_candidates": [{"source_kind": "evidence", "excerpt": 1, "payload": {}}, {"source_id": "MC-1", "source_kind": null, "excerpt": "e0", "payload": {}}, {"source_id": "", "source_kind": "evidence", "excerpt": "e27", "source_ref": "e.el05"}], "defense_candidates": [], "evidence_slot_status": [], "calculation_requests": [], "dependency_refs": [], "legal_effect_candidates": [{"type_id": "commercial_succes
|
||||
REG 199 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 3, "seen": 6, "ratio": 0.5, "max_ratio": 0.34} {"E-03": [{"seed_id": "s1", "bo_type": "event", "source_refs": ["EV-2"], "element_fact_candidates": [{"source_id": "EV-2", "source_kind": "evidence", "excerpt": "본문1", "payload": {}}], "opposing_fact_candidates": [], "defense_candidates": [{"source_id": "EVT-1", "source_kind": "evidence", "excerpt": "e52", "payload": {}}], "evidence_slot_status": [], "calculation_requests": [], "dependency_refs": [], "legal_effect_candidates": [{"type_id": "money_claim", "registered": true, "source_refs": ["EV-1"]}, {"type_id": "fraudulent_transfer", "registered": true, "source_refs": ["EV-1"]}], "review_items
|
||||
rounds 1500 seed 33 (ADDok,P7ok) {(False, False): 433, (True, True): 1052, (True, False): 14, (False, True): 1}
|
||||
stops ADD {('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 347, ('F0', 'SystemExit:1'): 87}
|
||||
stops P7 {('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 359, ('F0', 'SystemExit:1'): 88}
|
||||
reg Counter({('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 13, ('F0', 'SystemExit:1'): 1})
|
||||
rel Counter({('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 1})
|
||||
identical 35
|
||||
diff docs [('stage1_part2_review_handoff.json', 1017), ('postb_seed_ledger.json', 932), ('part4_receipt.json', 727), ('E-03.json', 578), ('E-02.json', 574), ('E-13.json', 569), ('part3_receipt.json', 238), ('fact_ledger_candidate_bundle.json', 214), ('legal_effect_structures.json', 202), ('structure_seed_bundle.json', 202), ('signal_manifest.json', 138), ('BO.json', 137), ('domain_signals', 120), ('Fact_Ledger_base.json', 113), ('fact_ledger_writer_report.json', 113), ('stage1_part4_review_handoff.json', 94), ('stage1_part3_review_handoff.json', 82), ('postb_compiled_bundle_compact.json', 64), ('legal_effect_routes.json', 25), ('calculation_requirements.json', 17)]
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
REG 400 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 3, "seen": 7, "ratio": 0.4286, "max_ratio": 0.34} {"E-13": [{"seed_id": "s4", "bo_type": "event", "source_refs": ["EV-1"], "element_fact_candidates": [{"source_id": "EVT-1", "source_kind": "evidence", "excerpt": "e14", "payload": {}, "refs": "e.el05"}, {"source_id": "EVT-1", "source_kind": "evidence", "excerpt": "e4", "payload": {}}, {"source_id": null, "source_kind": "SUPPORTED", "excerpt": "e52", "payload": {}}], "opposing_fact_candidates": [{"source_id": "", "source_kind": "evidence", "excerpt": "e69", "payload": {}}, {"source_id": "MC-1", "source_kind": "evidence", "excerpt": "e35", "payload": {}}, {"source_id": "MC-1", "source_kind": "ev
|
||||
REG 528 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 2, "seen": 5, "ratio": 0.4, "max_ratio": 0.34} {"E-03": [{"seed_id": "s4", "bo_type": "event", "source_refs": ["EV-1"], "element_fact_candidates": [{"source_id": "MC-1", "source_kind": "evidence", "excerpt": "e36", "payload": {}, "extra": {"excerpt": "본문"}}], "opposing_fact_candidates": [], "defense_candidates": [], "evidence_slot_status": [], "calculation_requests": [{"calculation_domain": "CE-01", "completeness": "ready", "source_refs": "한글 값", "review_code": "XX_YY"}, {"calculation_domain": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
REG 646 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 2, "seen": 4, "ratio": 0.5, "max_ratio": 0.34} {"E-02": [{"seed_id": "s3", "bo_type": "event", "source_refs": ["EV-4"], "element_fact_candidates": [{"source_id": "MC-1", "source_kind": "evidence", "payload": {}}, {"source_id": true, "source_kind": "evidence", "excerpt": "e75", "payload": {}}, {"source_id": "MC-1", "source_kind": "evidence", "excerpt": "e23", "payload": {}}, {"source_kind": 7, "payload": {}}, {"source_id": "EV-2", "source_kind": "evidence", "excerpt": "e57", "payload": {}}], "opposing_fact_candidates": [{"source_id": "EV-2", "source_kind": "evidence", "excerpt": "e38", "payload": {}}, 5], "defense_candidates": [{"source_id"
|
||||
rounds 1500 seed 44 (ADDok,P7ok) {(False, False): 440, (True, True): 1051, (True, False): 7, (False, True): 2}
|
||||
stops ADD {('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 338, ('F0', 'SystemExit:1'): 104}
|
||||
stops P7 {('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 343, ('F0', 'SystemExit:1'): 104}
|
||||
reg Counter({('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 6, ('F0', 'SystemExit:1'): 1})
|
||||
rel Counter({('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 2})
|
||||
identical 48
|
||||
diff docs [('stage1_part2_review_handoff.json', 1003), ('postb_seed_ledger.json', 925), ('part4_receipt.json', 721), ('E-02.json', 590), ('E-13.json', 579), ('E-03.json', 566), ('part3_receipt.json', 236), ('fact_ledger_candidate_bundle.json', 219), ('legal_effect_structures.json', 196), ('structure_seed_bundle.json', 196), ('signal_manifest.json', 137), ('BO.json', 132), ('domain_signals', 130), ('fact_ledger_writer_report.json', 106), ('Fact_Ledger_base.json', 106), ('stage1_part4_review_handoff.json', 87), ('stage1_part3_review_handoff.json', 77), ('postb_compiled_bundle_compact.json', 49), ('legal_effect_routes.json', 15), ('calculation_requirements.json', 8)]
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
REG 59 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 2, "seen": 4, "ratio": 0.5, "max_ratio": 0.34} {"E-03": [{"seed_id": "s1", "bo_type": "event", "source_refs": ["EV-2"], "element_fact_candidates": [{"source_id": "EV-1", "source_kind": "evidence", "excerpt": "e3", "payload": {}}, {"source_id": "EV-1", "source_kind": "evidence", "payload": {}}, {"source_id": "EV-2", "source_kind": "evidence", "excerpt": "e42", "payload": {"a": 1}, "extra": "v"}, {"source_id": "EVT-1", "source_kind": "evidence", "excerpt": "e74", "payload": {}, "content": "본문"}], "opposing_fact_candidates": [], "defense_candidates": [], "evidence_slot_status": [], "calculation_requests": [{"calculation_domain": "CE-01", "com
|
||||
REG 152 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 2, "seen": 5, "ratio": 0.4, "max_ratio": 0.34} {"E-13": [{"seed_id": "s3", "bo_type": "event", "source_refs": ["EV-4"], "element_fact_candidates": [{"source_id": "MC-1", "source_kind": "evidence", "excerpt": "e52", "payload": {}}, {"source_id": "MC-1", "source_kind": "evidence", "excerpt": "e43", "payload": {}}], "opposing_fact_candidates": [], "defense_candidates": [{"source_id": "EV-1", "source_kind": "evidence", "payload": {}}, "x"], "evidence_slot_status": [], "calculation_requests": [{"calculation_domain": "CE-01", "completeness": null, "source_refs": ["EV-1"], "review_code": "XX_YY", "ce_id": "e.el05"}, {"calculation_domain": "CE-01"
|
||||
REG 397 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 2, "seen": 3, "ratio": 0.6667, "max_ratio": 0.34} {"E-13": [{"seed_id": "s1", "bo_type": "event", "source_refs": ["EV-2"], "element_fact_candidates": [{"source_id": "EV-2", "source_kind": "evidence", "excerpt": "본문1", "payload": {}}], "opposing_fact_candidates": [], "defense_candidates": [{"source_id": "EV-1", "source_kind": "evidence", "excerpt": "e24", "payload": {}}, {"source_id": "EVT-1", "source_kind": "evidence", "excerpt": "e81", "extra": 1}, {"source_id": "", "source_kind": "evidence", "excerpt": "e97", "payload": {}, "foo": 1}, {"source_id": "MC-1", "source_kind": "evidence", "excerpt": "e87", "payload": {}}], "evidence_slot_status":
|
||||
rounds 1500 seed 55 (ADDok,P7ok) {(True, True): 1061, (False, False): 427, (False, True): 4, (True, False): 8}
|
||||
stops ADD {('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 340, ('F0', 'SystemExit:1'): 91}
|
||||
stops P7 {('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 343, ('F0', 'SystemExit:1'): 92}
|
||||
reg Counter({('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 7, ('F0', 'SystemExit:1'): 1})
|
||||
rel Counter({('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 4})
|
||||
identical 48
|
||||
diff docs [('stage1_part2_review_handoff.json', 1013), ('postb_seed_ledger.json', 943), ('part4_receipt.json', 733), ('E-02.json', 590), ('E-13.json', 584), ('E-03.json', 579), ('part3_receipt.json', 255), ('fact_ledger_candidate_bundle.json', 222), ('structure_seed_bundle.json', 201), ('legal_effect_structures.json', 201), ('BO.json', 144), ('signal_manifest.json', 143), ('domain_signals', 136), ('Fact_Ledger_base.json', 108), ('fact_ledger_writer_report.json', 108), ('stage1_part4_review_handoff.json', 84), ('stage1_part3_review_handoff.json', 82), ('postb_compiled_bundle_compact.json', 65), ('legal_effect_routes.json', 19), ('calculation_requirements.json', 7)]
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
REG 197 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 2, "seen": 4, "ratio": 0.5, "max_ratio": 0.34} {"E-13": [{"seed_id": "s2", "bo_type": "event", "source_refs": ["EV-3"], "element_fact_candidates": [{"source_id": "EV-3", "source_kind": "evidence", "excerpt": "본문2", "payload": {}}], "opposing_fact_candidates": [], "defense_candidates": [{"source_id": "EV-1", "source_kind": "evidence", "excerpt": "e50", "payload": {}, "fact": "e.el05"}, {"source_id": "EV-2", "source_kind": "evidence", "excerpt": "e49", "payload": {}}, {"source_id": "MC-1", "source_kind": "evidence", "excerpt": "e80", "payload": {}, "source_ref": "CE-02"}], "evidence_slot_status": [{"slot_id": "e.el09", "status": "filled", "s
|
||||
REG 891 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 2, "seen": 5, "ratio": 0.4, "max_ratio": 0.34} {"E-02": [{"seed_id": "s2", "bo_type": "event", "source_refs": ["EV-3"], "element_fact_candidates": [{"source_id": "EV-2", "source_kind": "complete", "payload": {}}, [1], {"source_kind": "evidence", "excerpt": "e84", "payload": {}}, {"source_id": "MC-1", "source_kind": "evidence", "excerpt": "e71", "payload": {}}, "x"], "opposing_fact_candidates": [{"source_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
REG 1253 R0 RuntimeError:{"reason_code": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "message": "격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.", "quarantined": 2, "seen": 4, "ratio": 0.5, "max_ratio": 0.34} {"E-03": [{"seed_id": "s2", "bo_type": "event", "source_refs": ["EV-3"], "element_fact_candidates": [{"source_id": "EV-3", "source_kind": "evidence", "excerpt": "본문2", "payload": {}}], "opposing_fact_candidates": [{"source_id": "EVT-1", "source_kind": "SUPPORTED", "excerpt": "e25", "payload": {}}, {"source_id": "EVT-1", "source_kind": "evidence", "excerpt": "e30", "payload": {}}], "defense_candidates": [{"source_id": "EVT-1", "source_kind": "evidence", "excerpt": "e91", "payload": {}}], "evidence_slot_status": [], "calculation_requests": [], "dependency_refs": [], "legal_effect_candidates": [{
|
||||
rounds 1500 seed 66 (ADDok,P7ok) {(True, True): 1054, (False, False): 437, (True, False): 4, (False, True): 5}
|
||||
stops ADD {('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 354, ('F0', 'SystemExit:1'): 88}
|
||||
stops P7 {('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 353, ('F0', 'SystemExit:1'): 88}
|
||||
reg Counter({('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 4})
|
||||
rel Counter({('R0', 'PART2_SEED_ADMISSION_BUDGET_EXCEEDED'): 5})
|
||||
identical 43
|
||||
diff docs [('stage1_part2_review_handoff.json', 1011), ('postb_seed_ledger.json', 954), ('part4_receipt.json', 749), ('E-13.json', 585), ('E-03.json', 575), ('E-02.json', 556), ('part3_receipt.json', 224), ('fact_ledger_candidate_bundle.json', 205), ('structure_seed_bundle.json', 188), ('legal_effect_structures.json', 188), ('signal_manifest.json', 135), ('domain_signals', 129), ('BO.json', 120), ('fact_ledger_writer_report.json', 97), ('Fact_Ledger_base.json', 97), ('stage1_part4_review_handoff.json', 88), ('stage1_part3_review_handoff.json', 77), ('postb_compiled_bundle_compact.json', 63), ('legal_effect_routes.json', 20), ('calculation_requirements.json', 8)]
|
||||
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
{"roots": {"E-03": [{"seed_id": "s1", "bo_type": "event", "source_refs": ["EV-2"], "element_fact_candidates": [{"source_id": "EV-2", "source_kind": "evidence", "excerpt": "본문1", "payload": {}}], "opposing_fact_candidates": [{"source_id": null, "source_kind": "evidence", "excerpt": "e48", "payload": {}, "refs": "CE-02"}, {"source_id": "EV-1", "source_kind": "evidence", "payload": {"a": 1}}], "defense_candidates": [{"source_id": "EV-2", "source_kind": null, "excerpt": "e87", "payload": {}}, {"source_id": "EV-2", "source_kind": "complete", "excerpt": "e65", "payload": {}}, {"source_id": "EV-2", "source_kind": "error", "excerpt": "e43", "payload": {}, "evidence_refs": "CE-02"}, {"source_id": "MC-1", "source_kind": "evidence", "excerpt": "e64", "payload": {}}, {"source_id": "EV-1", "source_kind": "evidence", "excerpt": "e74", "payload": {}, "x.y": 1}], "evidence_slot_status": [], "calculation_requests": [{"calculation_domain": "CE-01", "source_refs": ["EV-1"], "review_code": "XX_YY"}], "dependency_refs": [], "legal_effect_candidates": [{"type_id": "commercial_successor", "registered": true}, {"type_id": "commercial_successor", "registered": true, "source_refs": ["EV-2", "EV-3"], "component_id": "EV-1"}], "review_items": [{"review_code": "XX_YY", "severity": "review", "reason": "r92", "source_refs": 7}, {"review_code": "XX_YY", "severity": null, "reason": "r3"}, {"review_code": "XX_YY", "severity": "Filled", "reason": "r61", "component_id": "e.el05"}, {"review_code": "XX_YY", "reason": "r88", "source_refs": ["MC-1"]}], "extensions": {"domain_payload": {"action_summary": "다른행위", "action_type": "법률행위(legal acts)"}}, "amount_facts": [{"amount_type": "a_8", "decimal_value": null, "currency": null, "source_refs": ["EV-2", "EV-3"]}]}, {"seed_id": "s5", "bo_type": "event", "source_refs": ["EV-2"], "element_fact_candidates": [{"source_id": "EV-2", "source_kind": "evidence", "excerpt": "본문5", "payload": {}}], "opposing_fact_candidates": [], "defense_candidates": [], "evidence_slot_status": [], "calculation_requests": [], "dependency_refs": [], "legal_effect_candidates": [{"type_id": "general_legal_effect", "registered": true, "source_refs": ["EV-1"]}], "review_items": [], "extensions": {"domain_payload": {"action_summary": "채움E-030", "action_type": "법률행위(legal acts)"}}}]}, "canon": [], "stage": "R0", "why": "PART2_SEED_ADMISSION_BUDGET_EXCEEDED", "err": "RuntimeError:{\"reason_code\": \"PART2_SEED_ADMISSION_BUDGET_EXCEEDED\", \"message\": \"격리 비율이 한계를 넘었다. 모델 잡음이 아니라 계약 파손으로 본다.\", \"quarantined\": 1, \"seen\": 2, \"ratio\": 0.5, \"max_ratio\": 0.34}", "stdout": ""}
|
||||
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user