diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/domains/_common/common_worker_contract.md b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/domains/_common/common_worker_contract.md index 9a9ad8ee..4df887bf 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/domains/_common/common_worker_contract.md +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/domains/_common/common_worker_contract.md @@ -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 diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/runtime_manifest.json b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/runtime_manifest.json index 2925d252..f65fdf87 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/runtime_manifest.json +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/runtime_manifest.json @@ -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", diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/adapters/s3_domain_seed_adapter.py b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/adapters/s3_domain_seed_adapter.py index c3ce632a..5b5808e4 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/adapters/s3_domain_seed_adapter.py +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/adapters/s3_domain_seed_adapter.py @@ -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, diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/adapters/s3_domain_seed_adapter.txt b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/adapters/s3_domain_seed_adapter.txt index c3ce632a..5b5808e4 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/adapters/s3_domain_seed_adapter.txt +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/adapters/s3_domain_seed_adapter.txt @@ -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, diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.py b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.py index 019179ad..8f289b2d 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.py +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.py @@ -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 diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.txt b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.txt index 019179ad..8f289b2d 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.txt +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/compiler/signal_compiler.txt @@ -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 diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/emitters/emitter_runtime.py b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/emitters/emitter_runtime.py index ee1b06a9..561797d9 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/emitters/emitter_runtime.py +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/emitters/emitter_runtime.py @@ -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", diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/emitters/emitter_runtime.txt b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/emitters/emitter_runtime.txt index ee1b06a9..561797d9 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/emitters/emitter_runtime.txt +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/signals/emitters/emitter_runtime.txt @@ -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", diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/bo_surface_projection_policy.v1.json b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/bo_surface_projection_policy.v1.json index 57cfc53b..581a7a38 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/bo_surface_projection_policy.v1.json +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/bo_surface_projection_policy.v1.json @@ -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 은 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 는 사전순 최소를 골라 ':' 로 만든다. 마지막 출처는 ':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", diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.py b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.py index 641e4871..84112c74 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.py +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.py @@ -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,46 +545,47 @@ 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")): - route_refs.append(ref) - sg = sg11_by_signal_id.get(ref) - if sg is None: - calculation_requests.append({"calculation_id": None, - "request_id": ref, - "provenance": {"signal_id": ref, - "dangling": True}}) - reviews.append({"review_code": "CALCULATION_REF_DANGLING_REVIEW", - "severity": "SOFT_WARNING", "fact_id": fact_id, - "detail": ref}) - continue - used_sg11.add(ref) - details = _dict(sg.get("details")) - calc_id = details.get("calculation_id") - if not isinstance(calc_id, str) or not calc_id: - calc_id = ref - reviews.append({"review_code": "CALCULATION_ID_SUBSTITUTED_REVIEW", - "severity": "SOFT_WARNING", "fact_id": fact_id, - "detail": ref}) - law_refs = sorted(set( - _strings(sg.get("law_version_refs")) - + _strings(details.get("law_version_refs")) - + [ref2 for d in _strings(sg.get("domain_ids")) - for ref2 in sg04_by_domain.get(d, [])])) - calculation_requests.append({ - "calculation_id": calc_id, - "request_id": ref, - "operand_state": (sg.get("operand_state") - or details.get("operand_state")), - "missing_operands": _strings(details.get("missing_operands")), - "law_version_refs": law_refs, - "provenance": {"signal_id": ref, - "structure_ids": sorted( - s for s in structure_ids - if ref in _strings( - _dict(record_by_id.get(s)).get( - "calculation_request_refs")))}, - }) + # 계산 조인은 도메인 단위라 한 도메인의 레코드마다 같은 ref 가 있다. 행에는 한 번만 싣는다. + for ref in sorted({ref for record in attached + for ref in _strings(record.get("calculation_request_refs"))}): + route_refs.append(ref) + sg = sg11_by_signal_id.get(ref) + if sg is None: + calculation_requests.append({"calculation_id": None, + "request_id": ref, + "provenance": {"signal_id": ref, + "dangling": True}}) + reviews.append({"review_code": "CALCULATION_REF_DANGLING_REVIEW", + "severity": "SOFT_WARNING", "fact_id": fact_id, + "detail": ref}) + continue + used_sg11.add(ref) + details = _dict(sg.get("details")) + calc_id = details.get("calculation_id") + if not isinstance(calc_id, str) or not calc_id: + calc_id = ref + reviews.append({"review_code": "CALCULATION_ID_SUBSTITUTED_REVIEW", + "severity": "SOFT_WARNING", "fact_id": fact_id, + "detail": ref}) + law_refs = sorted(set( + _strings(sg.get("law_version_refs")) + + _strings(details.get("law_version_refs")) + + [ref2 for d in _strings(sg.get("domain_ids")) + for ref2 in sg04_by_domain.get(d, [])])) + calculation_requests.append({ + "calculation_id": calc_id, + "request_id": ref, + "operand_state": (sg.get("operand_state") + or details.get("operand_state")), + "missing_operands": _strings(details.get("missing_operands")), + "law_version_refs": law_refs, + "provenance": {"signal_id": ref, + "structure_ids": sorted( + s for s in structure_ids + if ref in _strings( + _dict(record_by_id.get(s)).get( + "calculation_request_refs")))}, + }) # (다) 증거력 credibility, proof_strength, slack = score_evidence( evidence_refs, authority, policy, reviews, fact_id) @@ -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), diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.txt b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.txt index 641e4871..84112c74 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.txt +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_compiler.txt @@ -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,46 +545,47 @@ 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")): - route_refs.append(ref) - sg = sg11_by_signal_id.get(ref) - if sg is None: - calculation_requests.append({"calculation_id": None, - "request_id": ref, - "provenance": {"signal_id": ref, - "dangling": True}}) - reviews.append({"review_code": "CALCULATION_REF_DANGLING_REVIEW", - "severity": "SOFT_WARNING", "fact_id": fact_id, - "detail": ref}) - continue - used_sg11.add(ref) - details = _dict(sg.get("details")) - calc_id = details.get("calculation_id") - if not isinstance(calc_id, str) or not calc_id: - calc_id = ref - reviews.append({"review_code": "CALCULATION_ID_SUBSTITUTED_REVIEW", - "severity": "SOFT_WARNING", "fact_id": fact_id, - "detail": ref}) - law_refs = sorted(set( - _strings(sg.get("law_version_refs")) - + _strings(details.get("law_version_refs")) - + [ref2 for d in _strings(sg.get("domain_ids")) - for ref2 in sg04_by_domain.get(d, [])])) - calculation_requests.append({ - "calculation_id": calc_id, - "request_id": ref, - "operand_state": (sg.get("operand_state") - or details.get("operand_state")), - "missing_operands": _strings(details.get("missing_operands")), - "law_version_refs": law_refs, - "provenance": {"signal_id": ref, - "structure_ids": sorted( - s for s in structure_ids - if ref in _strings( - _dict(record_by_id.get(s)).get( - "calculation_request_refs")))}, - }) + # 계산 조인은 도메인 단위라 한 도메인의 레코드마다 같은 ref 가 있다. 행에는 한 번만 싣는다. + for ref in sorted({ref for record in attached + for ref in _strings(record.get("calculation_request_refs"))}): + route_refs.append(ref) + sg = sg11_by_signal_id.get(ref) + if sg is None: + calculation_requests.append({"calculation_id": None, + "request_id": ref, + "provenance": {"signal_id": ref, + "dangling": True}}) + reviews.append({"review_code": "CALCULATION_REF_DANGLING_REVIEW", + "severity": "SOFT_WARNING", "fact_id": fact_id, + "detail": ref}) + continue + used_sg11.add(ref) + details = _dict(sg.get("details")) + calc_id = details.get("calculation_id") + if not isinstance(calc_id, str) or not calc_id: + calc_id = ref + reviews.append({"review_code": "CALCULATION_ID_SUBSTITUTED_REVIEW", + "severity": "SOFT_WARNING", "fact_id": fact_id, + "detail": ref}) + law_refs = sorted(set( + _strings(sg.get("law_version_refs")) + + _strings(details.get("law_version_refs")) + + [ref2 for d in _strings(sg.get("domain_ids")) + for ref2 in sg04_by_domain.get(d, [])])) + calculation_requests.append({ + "calculation_id": calc_id, + "request_id": ref, + "operand_state": (sg.get("operand_state") + or details.get("operand_state")), + "missing_operands": _strings(details.get("missing_operands")), + "law_version_refs": law_refs, + "provenance": {"signal_id": ref, + "structure_ids": sorted( + s for s in structure_ids + if ref in _strings( + _dict(record_by_id.get(s)).get( + "calculation_request_refs")))}, + }) # (다) 증거력 credibility, proof_strength, slack = score_evidence( evidence_refs, authority, policy, reviews, fact_id) @@ -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), diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_policy.v1.json b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_policy.v1.json index 8d428c5e..bfd5aedb 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_policy.v1.json +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/fact_ledger_policy.v1.json @@ -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 이다." } diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/seed_admission_policy.v1.json b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/seed_admission_policy.v1.json index faea9c32..c95f44e1 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/seed_admission_policy.v1.json +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/seed_admission_policy.v1.json @@ -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": [ diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/structure_index_compiler.py b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/structure_index_compiler.py index 3ee69f54..fb07abef 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/structure_index_compiler.py +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/structure_index_compiler.py @@ -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,14 +474,26 @@ 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)) - 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() + # 도메인을 건너 병합된 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"]: + record["source_bo_ids"].append(bo_id) + record["source_bo_ids"].sort() if attached_here: bo_attached.append(bo_id if isinstance(bo_id, str) else "") else: @@ -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 = { diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/structure_index_compiler.txt b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/structure_index_compiler.txt index 3ee69f54..fb07abef 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/structure_index_compiler.txt +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/structure_index_compiler.txt @@ -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,14 +474,26 @@ 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)) - 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() + # 도메인을 건너 병합된 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"]: + record["source_bo_ids"].append(bo_id) + record["source_bo_ids"].sort() if attached_here: bo_attached.append(bo_id if isinstance(bo_id, str) else "") else: @@ -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 = { diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/structure_index_policy.v1.json b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/structure_index_policy.v1.json index a96ac883..ecd8021e 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/structure_index_policy.v1.json +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/structure_index_policy.v1.json @@ -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 가 : 로 만든 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 하나)의 사이드카 부재는 정상 — 스킵하고 영수증에 기록한다. 선언이 있는 도메인의 부재·미등재는 경성 실패다." } diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/worker_output_validator.py b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/worker_output_validator.py index 6c9fd244..acd4a2a9 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/worker_output_validator.py +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/worker_output_validator.py @@ -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 diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/worker_output_validator.txt b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/worker_output_validator.txt index 6c9fd244..acd4a2a9 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/worker_output_validator.txt +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.7/extension_research/Default_Agent/stage1_runtime/worker_output_validator.txt @@ -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 diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_1_v.8.yml b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_1_v.8.yml index 886ec259..36cdc93d 100644 --- a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_1_v.8.yml +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_1_v.8.yml @@ -8,7 +8,7 @@ # 설계 판정 : P1-T2_to_T9_선결작업수행결과/01_설계판정/P0_설계판정_결정문서.md # 계측 재정의 : 같은 폴더 02_계측재정의/P2_계측통로_재정의.md # -# 구성 — task 13종 (v3 대비 +4 신설 · 4 개정 · 5 무변경) +# 구성 — task 18종 (v3 대비 +9 신설 · 4 개정 · 5 무변경). 2026-10-30 V 사슬 5종 신설, 기존 13종 코드 무변경. # [신설] Task_A0_domain_screener_01 / 02 / 03 ver_8 후보본 # [개정] Task_A_client_goal Task_A_client_goal_v4.yml # [무변경] Task_Evidence_shard_planner v3 622-945 @@ -19,7 +19,12 @@ # [무변경] Task_B12_gate_llm_adjudicator v3 3520-3679 # [무변경] Task_B12_gate_audit_finalizer v3 3680-4041 # [신설] Task_D0_domain_activation_gate ver_8 후보본 (정정본) -# [개정] Task_B2_SHA256_soft_gate_handoff_writer T9_..._v4.yml +# [개정] Task_B2_SHA256_soft_gate_handoff_writer T9_..._v4.yml (2026-10-30: nexts 에 V3 만 추가, 코드 무변경) +# [신설] Task_V0_value_facts_input_planner 가액금액_포함_작업구조도개정_계획서.md §2 +# [신설] Task_V1_value_facts_* 가액금액_정보추출_프롬프트.md [SYSTEM] (full 모드) +# [신설] Task_V1c_value_facts_capture_* S2_10 capture 패턴 +# [신설] Task_V2_value_facts_gate_merger assets_for_stage_1/value_facts/v4 gate_check.run_gate +# [신설] Task_V3_value_facts_party_linker T9 norm_name 복사 # # 개정 요지 # T0 3종 스크리너 사슬 신설. 02 가 01 의 초안을 봉인하고 03 이 후보 어휘를 압축한다. @@ -46,6 +51,20 @@ # precheck·audit checks[candidate_id_collision].id_normalizations 기록, severity HARD_WARNING; 치환 후 중복만 hard). # 실패분석_stage_1_part_2_v.8.md §4 F-1. mapper 프롬프트·CANDIDATE_ID_RE·최종 파일 스키마·보존 불변식 불변. # +# V(2026-10-30) 금액의 출처를 하나로 모은다. 정본은 gate 를 통과한 value_facts.json 이다(원문에 있다는 것까지만 보증). +# 산출: value_facts_inputs/ · value_facts_input_plan.json · value_facts_parts/ · value_facts.json · +# quality_gates/value_facts_gate.json(출처 지문) · value_facts_party_links.json. 기존 B1·B2 금액 칸은 대조용으로 남긴다. +# T9 봉인 7 키·handoff 바이트 불변(value_facts 실패가 사건 handoff 를 막지 않는다). 하류 대조는 +# gate.source_fingerprint.evidence_indexed_sha256 == handoff digest_guard.evidence_indexed_sha256 으로 한다. +# V 자산은 Default_Agent/value_facts/v4/MANIFEST.json 의 sha256 으로 대조한다(runtime_manifest 아님). +# party_ref 는 client_goal 성명이다(당사자 id 없음). 어휘 party_refs 설명("당사자 정본 ID") 문구 수정은 다음 자산 개정으로 미룬다. +# Stage 2 수용 조건: gate.status ∈ {READY, READY_WITH_REVIEW} · gate.run_id == value_facts.run_id · +# gate.value_facts_sha256 == sha256(value_facts.json) · 위 evidence_indexed_sha256 일치. 하나라도 어긋나면 쓰지 않는다. +# OUT 은 T9 와 V3 를 함께 기다린다. V 사슬이 멈춰 run 이 끝나지 않아도 T9 가 쓴 handoff 는 유효하다. +# 실주행 확인 필요(probe): (1) V1 인스턴스 1건 실패·시간 초과 시 all V1c_* 대기와 OUT 도달 여부 — 멈추면 OUT.wait 에서 V3 를 뺀다, +# (2) B1/B2 와 V1/V1c 두 fan-out 이 동시에 돌 때 {same_ordinal} 짝과 all V1c_* 집계, (3) T9 실패 시 V3 미기동 후 종료 상태, +# (4) V1 MODEL_INCOMPLETE 빈도(나오면 llm_reasoning 을 medium 으로). +# # 모듈 반입 규약 (localdocs 가 .py 를 서빙하지 않아 도입한 우회책) # 모든 .py 에는 같은 디렉터리에 바이트 동일한 .txt 형제 미러가 배포된다. # 빌더 규칙이며 예외는 build_default_agent_stage1.py 하나다. 미러는 정본 옆에 놓이므로 @@ -58,6 +77,8 @@ # Default_Agent/routing/activation_cue_digest.md # Default_Agent/routing/evidence_component_union.md # Default_Agent/platform/contracts/determinism_scope_contract.json +# Default_Agent/value_facts/v4/{MANIFEST.json, value_facts_vocab_block.v4.full.txt, +# value_facts_gate_rules.v4.json, value_normalize_lexicon.json, gate_check.txt} (V 사슬, 2026-10-30 신규 배포) # # 이 파일은 스테이지 하나다. 스테이지 선언 1벌 · task_procedure 1벌 · tasks 1벌. # 조각 후보본들이 각자 갖고 있던 Agent/Stages 머리와 자기 task_procedure 는 전부 걷어냈다. @@ -6854,6 +6875,1121 @@ Agent: if __name__ == "__main__": main() + # ---- V 사슬 (가액금액 추출) — 가액금액_포함_작업구조도개정_계획서.md §2 ---------------- + - task_name: Task_V0_value_facts_input_planner + description: V 산출 자리표시 초기화, 자산 해시 대조, 문서별 입력 렌더링, V1 fan-out 계획 + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 240 + code: | + #!/usr/bin/env python3 + # Task_V0_value_facts_input_planner + # 1) 이전 실행의 V 계획·산출 4종을 BLOCKED 자리표시로 덮는다(옛 결과가 남지 않게). + # 2) 자산 반입·해시 대조 -> 3) 문서마다 본문 렌더링(gate 와 같은 함수, D6) + # 4) value_facts_inputs/E-NNN.txt 와 계획을 쓰고 dynamic_fanout 을 낸다. + # 어떤 경우에도 raise 하지 않는다. 막히면 빈 fan-out 과 BLOCKED 를 낸다(사건 사슬을 막지 않는다). + TASK_NAME = "Task_V0_value_facts_input_planner" + import copy + import hashlib + import itertools + import json + import re + import secrets + from datetime import datetime, timezone + + import httpx + + # -------------------------------------------------------------------------- + # localdocs 보일러플레이트 (SKILL.md 5장 / 5.2장) + # clientInfo 에 {{__user_hash__}} / {{__workspace_hash__}} 를 반드시 넣는다. + # Task_D0_domain_activation_gate 의 검증 완료본을 그대로 복사했다. + # -------------------------------------------------------------------------- + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=120) + MSG_ID_COUNTER = itertools.count(10) + + + def next_msg_id(): + return next(MSG_ID_COUNTER) + + + def _init(): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": TASK_NAME, "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}"}} + }, headers=MCP_HEADERS) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post(LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS).raise_for_status() + + + def _parse_mcp(text): + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + return None + try: + return json.loads(text) + except Exception: + return None + + + def _call(name, args, mid): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": mid, "method": "tools/call", + "params": {"name": name, "arguments": args} + }, headers=MCP_HEADERS) + r.raise_for_status() + p = _parse_mcp(r.text) + if not p or "result" not in p: + raise RuntimeError("MCP_CALL_FAILED:%s" % name) + return p + + + def read_raw(name): + # 원문 그대로 돌려준다. sha256 은 이 문자열의 utf-8 바이트로 계산한다(재직렬화 금지). + p = _call("read_docs", {"doc_names": [name]}, next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("EMPTY_RESPONSE:%s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("EMPTY_CONTENT:%s" % name) + return inner + raise RuntimeError("UNEXPECTED_READ_DOCS_ENVELOPE:%s" % name) + + + def write_doc(path, content): + _call("write_file", {"path": path, "content": content, "overwrite": True}, + next_msg_id()) + + + def sha_text(text): + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + + def now_utc(): + return datetime.now(timezone.utc).isoformat() + + + def dumps(obj): + return json.dumps(obj, ensure_ascii=False, indent=2) + + # -------------------------------------------------------------------------- + # value_facts v4 자산 반입 — Default_Agent/value_facts/v4/MANIFEST.json 의 sha256 과 대조한다. + # gate_check 는 localdocs 가 .py 를 서빙하지 않으므로 바이트 동일한 .txt 미러로 읽는다. + # 미러의 기대 해시는 MANIFEST.tools["gate_check.py"] 다. + # -------------------------------------------------------------------------- + ASSET_DIR = "Default_Agent/value_facts/v4/" + ASSET_MANIFEST = ASSET_DIR + "MANIFEST.json" + ASSETS = { + "vocab_block": ("value_facts_vocab_block.v4.full.txt", "files", "value_facts_vocab_block.v4.full.txt"), + "gate_rules": ("value_facts_gate_rules.v4.json", "files", "value_facts_gate_rules.v4.json"), + "lexicon": ("value_normalize_lexicon.json", "files", "value_normalize_lexicon.json"), + "gate_check": ("gate_check.txt", "tools", "gate_check.py"), + } + + + def load_assets(keys): + # 요청한 자산만 읽는다. 하나라도 없거나 해시가 다르면 예외. 호출자가 BLOCKED 로 기록한다. + manifest = json.loads(read_raw(ASSET_MANIFEST)) + bodies, hashes = {}, {} + for key in keys: + name, section, entry = ASSETS[key] + want = (manifest.get(section) or {}).get(entry) + if not want: + raise RuntimeError("ASSET_UNREGISTERED:%s" % entry) + body = read_raw(ASSET_DIR + name) + got = sha_text(body) + if got != want: + raise RuntimeError("ASSET_HASH_MISMATCH:%s" % name) + bodies[key] = body + hashes[name] = got + scope = {"__name__": "value_facts_gate_check"} + exec(compile(bodies["gate_check"], "gate_check.py", "exec"), scope) + out = {"gate": scope, "sha256": hashes} + for key in ("gate_rules", "lexicon"): + if key in bodies: + out[key] = json.loads(bodies[key]) + return out + + PLAN_PATH = "value_facts_input_plan.json" + SHARD_PLAN_PATH = "evidence_shard_plan.json" + INPUT_DIR = "value_facts_inputs" + PART_DIR = "value_facts_parts" + OUTPUTS = { + PLAN_PATH: "value_facts_input_plan.v1", + "value_facts.json": "stage1_value_facts.v1", + "quality_gates/value_facts_gate.json": "stage1_value_facts_gate.v1", + "value_facts_party_links.json": "stage1_value_facts_party_links.v1", + } + + + def reset_outputs(run_id, started_at): + for path, schema in OUTPUTS.items(): + write_doc(path, dumps({"schema_version": schema, "run_id": run_id, "status": "BLOCKED", + "reason": "NOT_YET_GENERATED_THIS_RUN", "run_started_at": started_at})) + + + def doc_type_of(doc): + # 문서 종류 = source_file 에서 확장자만 뗀 이름(인명 포함). R6 이 문서 종류로 value_basis 를 고른다. + name = str(doc.get("source_file") or "").split("/")[-1] + return re.sub(r"\.[A-Za-z0-9]+$", "", name) or "UNKNOWN" + + + def render_input(evidence_index, doc_type, text): + return ("## [DOCUMENT]\n\n" + "- evidence_index: %s\n- 문서 종류: %s\n- provenance: EVIDENCE\n\n" + "\n%s\n\n\n" + "위 문서에서 `value_facts`를 [SYSTEM] 규칙대로 추출해 JSON 하나로 출력하라.\n" + % (evidence_index, doc_type, text)) + + + def main(run_id, started_at, issues): + plan = {"schema_version": "value_facts_input_plan.v1", "planner_task": TASK_NAME, + "run_id": run_id, "created_at_utc": started_at, "status": "BLOCKED", + "asset_sha256": {}, "items": [], "skipped": [], "issues": issues} + try: + assets = load_assets(["vocab_block", "gate_check"]) + plan["asset_sha256"] = assets["sha256"] + shard_plan_raw = read_raw(SHARD_PLAN_PATH) + plan["evidence_shard_plan_sha256"] = sha_text(shard_plan_raw) + shard_plan = json.loads(shard_plan_raw) + if shard_plan.get("planner_status") != "READY": + raise RuntimeError("SHARD_PLANNER_NOT_READY:%s" % shard_plan.get("planner_status")) + render = assets["gate"]["doc_text_from_evidence"] + for shard in shard_plan.get("shards") or []: + evidence_index = shard.get("evidence_index_candidate") + label = shard.get("ordinal_label") + try: + doc = json.loads(read_raw(shard["shard_doc_path"])) + text = render(doc) + doc_type = doc_type_of(doc) + input_path = "%s/%s.txt" % (INPUT_DIR, evidence_index) + write_doc(input_path, render_input(evidence_index, doc_type, text)) + plan["items"].append({ + "ordinal_label": label, "evidence_index": evidence_index, "doc_type": doc_type, + "shard_doc_path": shard["shard_doc_path"], "input_path": input_path, + "part_path": "%s/%s.raw.json" % (PART_DIR, evidence_index), + "document_text_sha256": sha_text(text), "document_chars": len(text)}) + except Exception as exc: + plan["skipped"].append({"evidence_index": evidence_index, "code": "RENDER_FAILED", + "message": str(exc)[:300]}) + plan["status"] = "READY" if plan["items"] else "BLOCKED" + if not plan["items"]: + issues.append({"code": "NO_RENDERABLE_DOCUMENT", "message": "fan-out 대상 문서가 없다"}) + except Exception as exc: + issues.append({"code": str(exc).split(":")[0] or type(exc).__name__, "message": str(exc)[:300]}) + plan["status"] = "BLOCKED" + plan["items"] = [] + write_doc(PLAN_PATH, dumps(plan)) + return plan + + + RUN_ID = "vf-" + datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "-" + secrets.token_hex(4) + STARTED_AT = now_utc() + ISSUES = [] + PLAN = None + try: + _init() + reset_outputs(RUN_ID, STARTED_AT) + PLAN = main(RUN_ID, STARTED_AT, ISSUES) + except Exception as exc: + ISSUES.append({"code": "V0_FAILED", "message": str(exc)[:300]}) + + ITEMS = (PLAN or {}).get("items") or [] + # 백엔드 wildcard fan-out 은 stdout 의 dynamic_fanout 을 읽는다. item 은 경로만 싣는다(본문은 파일로). + print(json.dumps({ + "dynamic_fanout": [{"run_id": RUN_ID, "evidence_index": x["evidence_index"], + "input_path": x["input_path"], "part_path": x["part_path"]} for x in ITEMS], + "status": (PLAN or {}).get("status", "BLOCKED"), + "run_id": RUN_ID, + "item_count": len(ITEMS), + "skipped": [s["evidence_index"] for s in (PLAN or {}).get("skipped") or []], + "issues": ISSUES, + }, ensure_ascii=False)) + + - task_name: Task_V1_value_facts_* + description: 증거문서 1건의 가액·금액·수치 사실을 value_facts 레코드로 옮겨 적는다(가액금액_정보추출_프롬프트.md, full 모드) + # B1_*(12)와 동시에 돈다. Gemini 속도 제한을 고려해 8로 둔다. + max_concurrency: 8 + max_iterations: 1 + llm_provider: google + llm_model: gemini-3.5-flash-lite + llm_reasoning: high + llm_token_limit: 32000 + cache_control: + mode: auto + ttl: 20m + use_tools: + - localdocs + # 도구는 preflight 읽기에만 쓴다. LLM 에는 노출하지 않고, 응답은 봉투로 V1c 에 넘긴다. + expose_tools: false + preflight: true + # 정적 VOCAB 은 캐시 앞부분에, 문서별 입력은 그 뒤에 간다(SKILL.md §3.1). 프롬프트에는 item 변수가 없다. + preflight_files: + - Default_Agent/value_facts/v4/value_facts_vocab_block.v4.full.txt + - "{{item.input_path}}" + llm_result_envelope: true + prompts: + - role: user + content: |- + + ## [SYSTEM] + + 너는 대한민국 민사소송 증거문서에서 **가액·금액·수치 사실**을 옮겨 적는 기록원이다. 판단하지 않고, 계산하지 않고, 문서가 적은 것을 문서가 부른 이름으로 기록한다. 법적 의미(피보전채권인지, 공제 대상인지, 소가에 들어가는지)는 다음 단계가 정한다. + + ### 1. 무엇을 레코드로 만드는가 + + - 문서에 적힌 **값 하나 = 레코드 하나**다. 금액, 이율·비율, 지분, 면적·길이, 수량·주식 수·의결권 수, 기간 수치, 단가, 환율·지수가 대상이다. + - 다음은 만들지 않는다: 페이지 번호, 조항 번호, 지번·동호수의 숫자, 계좌·전화·사건·등기 접수 번호, 날짜 그 자체. 이것들은 해당 값의 `object_label_text`·`obligation_ref`·`dates`·`source_ref` 안에 넣는다. + - 같은 값이 같은 문서에 여러 번 나오면, 명칭이나 맥락(날짜·당사자·목적물)이 다를 때만 따로 만든다. + - 표는 칸마다 레코드를 만든다. 반복 회차(월별 관리비, 할부)에는 같은 `recurrence.series_label`을 붙인다. 합계 행은 `SUM_TOTAL`로 만든다. + - 문서가 "없음·해당 없음"이라고 **명시**한 값은 `absence_stated: true`로 만든다. 언급이 없는 값은 만들지 않는다. + - 등기부의 말소사항(취소선 `~~`로 표시된 행)의 값도 레코드로 만들고, `dates`에 REGISTRATION_CANCELLED(말소 등기 접수일)를 붙인다. 말소 문구는 `condition_text`에 인용한다. + + ### 2. 칸을 채우는 규칙 + + **필수 칸(항상 쓴다):** `local_id, value_kind, item_label, value_type, amount_text, value_basis, stated_by, dates, parties, provenance, source_ref`. `dates`와 `parties`는 해당이 없어도 `[]`로 둔다. + + **선택 칸:** 원문에 그 칸을 뒷받침하는 단어가 있을 때만 쓴다. 없으면 키 자체를 생략한다(null이나 빈 문자열을 쓰지 않는다). + + **옮겨 적기:** + - R1. `amount_text`와 `item_label`은 원문 문자열을 그대로 쓴다("금 오천만 원정", "△1,200", "월 2푼", "중도금 2차"). 숫자를 정규화·환산·약분·합산하지 않는다. 표 머리의 "단위: 천원"은 `unit_multiplier_text`에만 적는다. + - R2. `source_ref.quote`(80자 이내)는 원문을 그대로 인용하고, 그 안에 `amount_text`가 반드시 들어 있어야 한다. 가능하면 `item_label`도 들어가게 인용 범위를 잡는다. + - R3. 판독이 어려운 숫자는 추측해 채우지 않는다. 보이는 대로 쓰고 `legibility: PARTIAL` 또는 `ILLEGIBLE`을 붙인다. + + **어휘 고르기([VOCAB]의 닫힌 목록에서만):** + - R4. `value_kind`는 **문서가 그 값을 부르는 이름**으로 고른다. 손해·위자료·일실·피담보채권·평균임금·통상임금·증여가액 같은 법률 개념 kind는 원문에 그 단어가 있을 때만 쓴다. 맞는 항목이 없거나 두 항목 사이에서 망설이면 `OTHER`를 쓴다. 틀린 kind보다 OTHER가 낫다. + - R5. `value_type`은 [VOCAB] §3.7 허용표와 맞아야 한다. RATE는 기간당 비율이며, 원문에 분모(연·월·일)가 있으면 `per`를 쓰고 없으면 생략한다("이자는 3%로 한다", 원천징수 3.3%). RATIO는 기간 없는 비율, SHARE는 소유·권리 비율, UNIT_PRICE는 단위당 금액이며 `per`가 필수다(감정평가서의 ㎡당 감정 단가는 APPRAISAL_VALUE + UNIT_PRICE). 차임·지료·사용료·보험료처럼 기간마다 반복되는 금액(MONEY)도 원문에 분모("월", "㎡당 월")가 있으면 `per`를 쓴다. + - R6. `value_basis`는 **이 값을 만든 행위와 문서 종류**로 고른다. 계약서는 AGREED, 영수증·이체내역은 PAID, 등기부는 REGISTERED, 감정서는 APPRAISED(감정서에 인용된 공시지가도 APPRAISED), 판결·지급명령·배당표는 COURT_DECISION을 쓴다. 재산세 고지서의 시가표준액·주택가격·과세표준은 TAX_BASE(과세표준의 kind는 TAXATION_STANDARD, 주택의 시가표준액·개별주택가격·공동주택가격의 kind는 PUBLIC_HOUSING_PRICE), 세액은 IMPOSED를 쓴다. 효력이나 집행력은 판단하지 않는다. + - R7. `tax_base_scope`는 TAX_BASE_VALUE·PUBLIC_HOUSING_PRICE에는 반드시 쓰고, 공시지가 kind(PUBLIC_LAND_PRICE_*)에는 쓴다면 LAND만 쓴다. 문서의 표제·항목명으로만 고른다. 개별공시지가는 LAND, 건축물 시가표준액은 BUILDING_ONLY, 개별·공동주택가격(재산세 고지서의 주택 시가표준액 포함)은 HOUSING_INCL_LAND, 차량·선박·회원권 등은 OTHER, 그 밖에는 UNSTATED를 쓴다. 토지가 포함됐는지 추론하지 않는다. 다른 kind에는 쓰지 않으며, 특히 TAXATION_STANDARD(과세표준)에는 쓰지 않는다. + - R8. `parties[].role`은 문서가 그 사람에게 붙인 호칭을 §3.4 매핑표로 옮긴 것이다. 호칭 원문은 `role_text`에 둔다. 갑·을은 계약서가 정의한 지위로 쓰고, 호칭이 없으면 OTHER를 쓴다. + - R9. `rate_form`은 이율 문구에 기준금리·변동·가산·%p·상한·하한·단계·구간이 있을 때만 쓴다. `vat`·`withholding`은 "부가세 포함/별도", "세전/세후" 같은 표지가 있을 때만 쓴다. + + **날짜·기간·당사자 비율:** + - R10. `dates[]`에는 값에 직접 붙은 날짜만 역할과 함께 넣는다. 문서 작성일을 값마다 반복하지 않는다. `date_value`는 원문이 연·월·일을 모두 적었을 때만 YYYY-MM-DD로 쓴다. + - R11. "~부터 ~까지"는 `dates`가 아니라 `period`에 쓴다. 끝이 "다 갚는 날까지"처럼 열려 있으면 `end.event_text`에 그 문구를 쓰고 `open_ended: true`로 둔다. + - R12. 지분·귀속비율·부분 면적은 별도의 SHARE·AREA 레코드로 만들고 `share_local_id`·`area_local_id`로 가리킨다. 분수로 적혀 있으면 `fraction`에 분자·분모를 원문 그대로 둔다. + + **관계(가장 틀리기 쉬움):** + - R13. `relations[]`는 같은 문서 안의 두 값이 **원문 접속어로 직접 연결된 경우에만** 쓴다(공제·차감·포함·합계·~에 대하여 연 ~%·~의 배액·한도·범위 내·~에 갈음하여·~로 환산). 그 접속어 구절을 `connective_quote`에 인용한다. 숫자를 맞춰 보며 관계를 찾지 않는다. 예외: 같은 증서에 원금이 하나이고 그 증서에 "이자는 …", "이 자 : …", 표의 "이자" 행으로 이율이 적혀 있으면, 그 이자 문구를 `connective_quote`로 하여 그 원금에 ACCRUES_ON을 붙인다(원금이 둘 이상이면 붙이지 않는다). + - R14. 주어는 이 레코드, 목적어는 `target_local_ids`다. 예를 들어 "선이자 50만 원 공제"에서 선이자 레코드는 원금을 향해 DEDUCTED_FROM이다. 이율 레코드는 원금을 향해 ACCRUES_ON이고, 합계 레코드는 구성 항목을 향해 INCLUDES다. 목적어가 값으로 적혀 있지 않으면 `target_text`에 원문을 쓴다. 역방향 관계는 쓰지 않는다. + - R15. 한 값에 붙은 "한도·이하·미만·이상·초과"는 `relations`가 아니라 `bound`에 쓴다. 다른 값의 한도이면 `relations`의 LIMIT_OF로 쓴다. + + **쓰지 않는 것:** + - R16. 다음 칸은 코드와 다음 단계 전용이므로 출력하지 않는다: `value_id, amount_value, party_refs, object_refs, conflict_group, fill_status, lookup`, `right_refs`의 `registry_ref·fraction_ref`. + - R17. 법정이율, 인지규칙 비율, 소액사건 기준액처럼 문서에 적히지 않은 법정 상수는 쓰지 않는다. 문서에 없는 시가·공시가격·환율을 보충하지 않는다. 다른 문서와 비교하지 않는다. + - R18. `provenance`는 입력으로 받은 `provenance` 값을 그대로 쓴다. + + **담보 설정 약정:** + - R19. 원문에 담보를 설정·제공하기로 하는 약정("근저당권을 설정하기로 함", "담보로 제공한다", "보증인을 세운다")이 있으면, **피담보채권 값**(원금·대금 등)의 레코드에 `security_terms: [{right_kind, term_quote}]`를 붙인다. 지분·면적 값에는 붙이지 않고, 피담보채권 값이 없으면 채권최고액 값에 붙인다. `right_kind`는 §3.6에서 고르고(근저당 ROOT_MORTGAGE, 저당 MORTGAGE, 질권 PLEDGE, 전세권 JEONSE, 소유권이전 가등기·양도담보 OWNERSHIP, 보증인 세우기처럼 맞는 것이 없으면 OTHER), `term_quote`는 설정·제공 동사를 포함한 약정 문구를 200자 이내로 원문 그대로 이어서 인용한다(생략부호 금지). 약정에 적힌 채권최고액은 MAX_SECURED_AMOUNT + value_basis AGREED 레코드로 따로 만든다. 담보가 여럿이면 항목을 여러 개 둔다. 등기되지 않은 약정은 `right_refs`에 쓰지 않는다. + + ### 3. 출력 + + - JSON 객체 하나만 출력한다. 설명, 마크다운, 주석을 붙이지 않는다. + - 형식: `{"evidence_index": "...", "value_facts": [ ... ]}` + - `local_id`는 문서에 나오는 순서대로 v1, v2, …로 붙인다. `relations`, `share_local_id`, `area_local_id`는 이 번호로만 가리킨다. + - 값이 하나도 없으면 `"value_facts": []`를 출력한다. + + ### 4. 제출 전 점검(속으로 하고 출력하지 않는다) + + 1. 문서의 모든 금액·비율·면적·수량에 레코드가 있는가? 표의 칸과 합계 행, 각주까지 확인했는가? + 2. 모든 레코드에 필수 11칸이 있는가? 각 `quote`에 `amount_text`가 그대로 들어 있는가? + 3. kind와 type이 §3.7 허용표에 맞는가? UNIT_PRICE에 `per`가 있는가? RATE는 원문에 분모가 있을 때 `per`를 썼고, 없으면 생략했는가? + 4. `relations`마다 `connective_quote`가 원문에 있는가? 방향은 맞는가? + 5. 원문에 근거 단어가 없는 선택 칸을 지웠는가? 계산하거나 환산한 값이 섞여 있지 않은가? + 6. 담보 설정 약정이 있으면 피담보채권 값에 `security_terms`를 붙였는가? + + ### 5. 예시 + + 입력 일부: + + ```text + 대여인 甲 / 차용인 乙 + 금 오천만 원정을 2025. 3. 1. 차용하고, 이자는 월 1푼으로 하며 2026. 2. 28.까지 변제한다. 선이자 50만 원 공제 후 4,950만 원 수령 + ``` + + ```json + {"evidence_index":"E-003","value_facts":[ + {"local_id":"v1","value_kind":"LOAN_PRINCIPAL","item_label":"금 오천만 원정","value_type":"MONEY","amount_text":"금 오천만 원정","currency":"KRW","value_basis":"AGREED","stated_by":"차용인 乙","dates":[{"role":"CONTRACT","date_text":"2025. 3. 1.","date_value":"2025-03-01"},{"role":"DUE","date_text":"2026. 2. 28.","date_value":"2026-02-28"}],"parties":[{"party_label":"甲","role":"LENDER","role_text":"대여인"},{"party_label":"乙","role":"BORROWER","role_text":"차용인"}],"provenance":"EVIDENCE","source_ref":{"evidence_index":"E-003","page_or_row":"p1","quote":"금 오천만 원정을 2025. 3. 1. 차용하고"}}, + {"local_id":"v2","value_kind":"INTEREST_RATE","item_label":"이자","value_type":"RATE","amount_text":"월 1푼","per":["월"],"value_basis":"AGREED","stated_by":"차용인 乙","dates":[],"parties":[],"relations":[{"type":"ACCRUES_ON","target_local_ids":["v1"],"connective_quote":"이자는 월 1푼으로 하며"}],"provenance":"EVIDENCE","source_ref":{"evidence_index":"E-003","page_or_row":"p1","quote":"이자는 월 1푼으로 하며"}}, + {"local_id":"v3","value_kind":"INTEREST_AMOUNT","item_label":"선이자","value_type":"MONEY","amount_text":"50만 원","currency":"KRW","value_basis":"AGREED","stated_by":"차용인 乙","dates":[],"parties":[],"relations":[{"type":"DEDUCTED_FROM","target_local_ids":["v1"],"connective_quote":"선이자 50만 원 공제 후"}],"provenance":"EVIDENCE","source_ref":{"evidence_index":"E-003","page_or_row":"p1","quote":"선이자 50만 원 공제 후 4,950만 원 수령"}}, + {"local_id":"v4","value_kind":"AMOUNT_DISBURSED","item_label":"수령","value_type":"MONEY","amount_text":"4,950만 원","currency":"KRW","value_basis":"PAID","stated_by":"차용인 乙","dates":[],"parties":[],"provenance":"EVIDENCE","source_ref":{"evidence_index":"E-003","page_or_row":"p1","quote":"공제 후 4,950만 원 수령"}} + ]} + ``` + + v2의 "월 1푼"은 1%로 바꾸지 않고 그대로 둔다. 실수령액 4,950만 원이 원금인지는 판단하지 않는다. + + 담보 설정 약정 예시(security_terms) 입력 일부: + + ```text + 대여인 한별 귀하 + 차용금액: 금 일억 원정(₩100,000,000) + 변제기: 2025. 6. 30. + 특약: 차용인은 위 채무의 담보로 그 소유 경기 고양시 덕양구 행신동 55 대지에 채권최고액 금 일억삼천만 원의 근저당권을 2025. 1. 31.까지 설정하여 주기로 한다. + 2025. 1. 10. + 차용인 송가람 (인) + ``` + + ```json + {"evidence_index":"E-004","value_facts":[ + {"local_id":"v1","value_kind":"LOAN_PRINCIPAL","item_label":"차용금액","value_type":"MONEY","amount_text":"금 일억 원정","currency":"KRW","value_basis":"AGREED","stated_by":"차용인 송가람","dates":[{"role":"DUE","date_text":"2025. 6. 30.","date_value":"2025-06-30"}],"parties":[{"party_label":"한별","role":"LENDER","role_text":"대여인"},{"party_label":"송가람","role":"BORROWER","role_text":"차용인"}],"security_terms":[{"right_kind":"ROOT_MORTGAGE","term_quote":"차용인은 위 채무의 담보로 그 소유 경기 고양시 덕양구 행신동 55 대지에 채권최고액 금 일억삼천만 원의 근저당권을 2025. 1. 31.까지 설정하여 주기로 한다"}],"provenance":"EVIDENCE","source_ref":{"evidence_index":"E-004","page_or_row":"p1","quote":"차용금액: 금 일억 원정(₩100,000,000)"}}, + {"local_id":"v2","value_kind":"MAX_SECURED_AMOUNT","item_label":"채권최고액","value_type":"MONEY","amount_text":"금 일억삼천만 원","currency":"KRW","value_basis":"AGREED","stated_by":"차용인 송가람","dates":[],"parties":[],"object_label_text":["경기 고양시 덕양구 행신동 55"],"provenance":"EVIDENCE","source_ref":{"evidence_index":"E-004","page_or_row":"p1 특약","quote":"행신동 55 대지에 채권최고액 금 일억삼천만 원의 근저당권을"}} + ]} + ``` + + 약정은 원금 v1에 붙이고, 약정상 채권최고액은 v2(AGREED)로 따로 둔다. 등기되었는지는 판단하지 않는다. + + [VOCAB]의 칸 지시가 [SYSTEM]보다 구체적이면 [VOCAB]를 따른다. + + ## [입력 배치] + + - [VOCAB]은 미리 읽힌 `Default_Agent/value_facts/v4/value_facts_vocab_block.v4.full.txt` 전체다(머리 "# value_facts v4 — 칸 지시와 닫힌 어휘"). + - [DOCUMENT]는 미리 읽힌 `value_facts_inputs/E-NNN.txt` 하나다(`## [DOCUMENT]` 머리, evidence_index·문서 종류·provenance 줄, `` 본문). 출력의 evidence_index·provenance는 그 머리줄 값을 그대로 쓴다. + - 도구를 호출하지 않는다. 파일을 쓰지 않는다. 다른 문서를 읽지 않는다. + + + - task_name: Task_V1c_value_facts_capture_* + description: 같은 ordinal 의 V1 응답 봉투를 value_facts_parts/E-NNN.raw.json 에 그대로 저장 + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 120 + code: | + #!/usr/bin/env python3 + # Task_V1c_value_facts_capture_* + # 같은 ordinal 의 Task_V1_value_facts_ 응답 봉투(llm_result_envelope)를 파싱하지 않고 + # 그대로 value_facts_parts/E-NNN.raw.json 에 쓴다(S2_10 capture 패턴). 검사는 V2 가 한다. + # run_id 를 함께 적어 V2 가 지난 실행의 part 를 걸러 낸다. raise 하지 않는다. + TASK_NAME = "Task_V1c_value_facts_capture" + import copy + import hashlib + import itertools + import json + import re + import secrets + from datetime import datetime, timezone + + import httpx + + # -------------------------------------------------------------------------- + # localdocs 보일러플레이트 (SKILL.md 5장 / 5.2장) + # clientInfo 에 {{__user_hash__}} / {{__workspace_hash__}} 를 반드시 넣는다. + # Task_D0_domain_activation_gate 의 검증 완료본을 그대로 복사했다. + # -------------------------------------------------------------------------- + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=120) + MSG_ID_COUNTER = itertools.count(10) + + + def next_msg_id(): + return next(MSG_ID_COUNTER) + + + def _init(): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": TASK_NAME, "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}"}} + }, headers=MCP_HEADERS) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post(LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS).raise_for_status() + + + def _parse_mcp(text): + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + return None + try: + return json.loads(text) + except Exception: + return None + + + def _call(name, args, mid): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": mid, "method": "tools/call", + "params": {"name": name, "arguments": args} + }, headers=MCP_HEADERS) + r.raise_for_status() + p = _parse_mcp(r.text) + if not p or "result" not in p: + raise RuntimeError("MCP_CALL_FAILED:%s" % name) + return p + + + def read_raw(name): + # 원문 그대로 돌려준다. sha256 은 이 문자열의 utf-8 바이트로 계산한다(재직렬화 금지). + p = _call("read_docs", {"doc_names": [name]}, next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("EMPTY_RESPONSE:%s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("EMPTY_CONTENT:%s" % name) + return inner + raise RuntimeError("UNEXPECTED_READ_DOCS_ENVELOPE:%s" % name) + + + def write_doc(path, content): + _call("write_file", {"path": path, "content": content, "overwrite": True}, + next_msg_id()) + + + def sha_text(text): + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + + def now_utc(): + return datetime.now(timezone.utc).isoformat() + + + def dumps(obj): + return json.dumps(obj, ensure_ascii=False, indent=2) + + ITEM = json.loads(r"""{{item_json}}""") + ORDINAL = int(r"""{{ordinal}}""") + LLM_TASK = "Task_V1_value_facts_%d" % ORDINAL + RESULT = {"status": "FAILED", "evidence_index": ITEM.get("evidence_index"), "part_path": ITEM.get("part_path")} + try: + try: + prev = json.loads(r"""{{prev}}""") + except Exception as exc: + prev = {"_prev_parse_error": str(exc)[:300]} + env = prev.get(LLM_TASK) if isinstance(prev, dict) else None + if isinstance(env, str): + try: + env = json.loads(env) + except Exception: + env = {"content": env, "json_output": None, "status": "UNKNOWN"} + record = {"schema_version": "value_facts_part.v1", "run_id": ITEM.get("run_id"), + "evidence_index": ITEM.get("evidence_index"), "llm_task": LLM_TASK, + "captured_at_utc": now_utc(), "envelope": env if isinstance(env, dict) else None} + if not isinstance(env, dict): + record["error"] = {"code": "MISSING_TASK_OUTPUT", + "detail": prev.get("_prev_parse_error") if isinstance(prev, dict) else None} + _init() + write_doc(ITEM["part_path"], dumps(record)) + RESULT = {"status": "CAPTURED" if isinstance(env, dict) else "CAPTURED_WITHOUT_OUTPUT", + "evidence_index": ITEM.get("evidence_index"), "part_path": ITEM["part_path"], + "llm_status": env.get("status") if isinstance(env, dict) else None} + except Exception as exc: + RESULT["error"] = str(exc)[:300] + print(json.dumps(RESULT, ensure_ascii=False)) + + - task_name: Task_V2_value_facts_gate_merger + description: 문서별 gate(run_gate full) · 별칭 제외 · 병합 · 출처 지문 기록 + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 300 + code: | + #!/usr/bin/env python3 + # Task_V2_value_facts_gate_merger + # V0 계획의 기대 문서만 읽는다. 문서마다 part 를 파싱해 gate_check.run_gate(mode=full)를 돌리고, + # B1 gate 가 중복 별칭으로 뺀 문서의 레코드는 excluded_by_alias 로 옮긴 뒤 records 를 병합한다. + # 출처 지문(evidence_all / evidence_shard_plan / evidence_indexed 의 sha256 + 실행 시각)을 남긴다. + # 하류 대조는 evidence_indexed_sha256 으로 한다(T9 가 같은 값을 봉인한다). + # 어떤 경우에도 raise 하지 않는다. + TASK_NAME = "Task_V2_value_facts_gate_merger" + import copy + import hashlib + import itertools + import json + import re + import secrets + from datetime import datetime, timezone + + import httpx + + # -------------------------------------------------------------------------- + # localdocs 보일러플레이트 (SKILL.md 5장 / 5.2장) + # clientInfo 에 {{__user_hash__}} / {{__workspace_hash__}} 를 반드시 넣는다. + # Task_D0_domain_activation_gate 의 검증 완료본을 그대로 복사했다. + # -------------------------------------------------------------------------- + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=120) + MSG_ID_COUNTER = itertools.count(10) + + + def next_msg_id(): + return next(MSG_ID_COUNTER) + + + def _init(): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": TASK_NAME, "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}"}} + }, headers=MCP_HEADERS) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post(LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS).raise_for_status() + + + def _parse_mcp(text): + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + return None + try: + return json.loads(text) + except Exception: + return None + + + def _call(name, args, mid): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": mid, "method": "tools/call", + "params": {"name": name, "arguments": args} + }, headers=MCP_HEADERS) + r.raise_for_status() + p = _parse_mcp(r.text) + if not p or "result" not in p: + raise RuntimeError("MCP_CALL_FAILED:%s" % name) + return p + + + def read_raw(name): + # 원문 그대로 돌려준다. sha256 은 이 문자열의 utf-8 바이트로 계산한다(재직렬화 금지). + p = _call("read_docs", {"doc_names": [name]}, next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("EMPTY_RESPONSE:%s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("EMPTY_CONTENT:%s" % name) + return inner + raise RuntimeError("UNEXPECTED_READ_DOCS_ENVELOPE:%s" % name) + + + def write_doc(path, content): + _call("write_file", {"path": path, "content": content, "overwrite": True}, + next_msg_id()) + + + def sha_text(text): + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + + def now_utc(): + return datetime.now(timezone.utc).isoformat() + + + def dumps(obj): + return json.dumps(obj, ensure_ascii=False, indent=2) + + # -------------------------------------------------------------------------- + # value_facts v4 자산 반입 — Default_Agent/value_facts/v4/MANIFEST.json 의 sha256 과 대조한다. + # gate_check 는 localdocs 가 .py 를 서빙하지 않으므로 바이트 동일한 .txt 미러로 읽는다. + # 미러의 기대 해시는 MANIFEST.tools["gate_check.py"] 다. + # -------------------------------------------------------------------------- + ASSET_DIR = "Default_Agent/value_facts/v4/" + ASSET_MANIFEST = ASSET_DIR + "MANIFEST.json" + ASSETS = { + "vocab_block": ("value_facts_vocab_block.v4.full.txt", "files", "value_facts_vocab_block.v4.full.txt"), + "gate_rules": ("value_facts_gate_rules.v4.json", "files", "value_facts_gate_rules.v4.json"), + "lexicon": ("value_normalize_lexicon.json", "files", "value_normalize_lexicon.json"), + "gate_check": ("gate_check.txt", "tools", "gate_check.py"), + } + + + def load_assets(keys): + # 요청한 자산만 읽는다. 하나라도 없거나 해시가 다르면 예외. 호출자가 BLOCKED 로 기록한다. + manifest = json.loads(read_raw(ASSET_MANIFEST)) + bodies, hashes = {}, {} + for key in keys: + name, section, entry = ASSETS[key] + want = (manifest.get(section) or {}).get(entry) + if not want: + raise RuntimeError("ASSET_UNREGISTERED:%s" % entry) + body = read_raw(ASSET_DIR + name) + got = sha_text(body) + if got != want: + raise RuntimeError("ASSET_HASH_MISMATCH:%s" % name) + bodies[key] = body + hashes[name] = got + scope = {"__name__": "value_facts_gate_check"} + exec(compile(bodies["gate_check"], "gate_check.py", "exec"), scope) + out = {"gate": scope, "sha256": hashes} + for key in ("gate_rules", "lexicon"): + if key in bodies: + out[key] = json.loads(bodies[key]) + return out + + PLAN_PATH = "value_facts_input_plan.json" + VALUE_FACTS_PATH = "value_facts.json" + GATE_PATH = "quality_gates/value_facts_gate.json" + ALIAS_MANIFEST_PATH = "stage1_tmp/quality_gate/finalized_evidence_id_manifest.json" + FINGERPRINT_SOURCES = {"evidence_all_sha256": "evidence_all.json", + "evidence_shard_plan_sha256": "evidence_shard_plan.json", + "evidence_indexed_sha256": "evidence_indexed.json"} + DOC_TAG_RE = re.compile(r"\n(.*)\n", re.S) + + + class DocError(Exception): + def __init__(self, code, detail=""): + super().__init__("%s:%s" % (code, detail)) + self.code = code + self.detail = detail + + + def parse_model(env): + # S2_10 parse_model 과 같은 규칙. 봉투 status 가 완료가 아니면 본문을 완성본으로 쓰지 않는다. + status = str(env.get("status", env.get("finish_reason", "UNKNOWN"))).lower() + if status not in {"completed", "success", "ok", "stop"}: + raise DocError("MODEL_INCOMPLETE", status) + raw = env.get("json_output") + if raw is None: + raw = env.get("content") if env.get("content") is not None else env.get("output") + if isinstance(raw, dict): + return copy.deepcopy(raw) + if not isinstance(raw, str) or not raw.strip(): + raise DocError("MODEL_OUTPUT_MISSING") + s = raw.strip() + if s.startswith("```"): + m = re.fullmatch(r"```(?:json)?\s*([\s\S]*?)\s*```", s) + if not m: + raise DocError("MODEL_PARSE_FAILED", "unbalanced fences") + s = m.group(1) + try: + return json.loads(s) + except json.JSONDecodeError as exc: + raise DocError("MODEL_PARSE_FAILED", str(exc)[:200]) + + + def fingerprint(): + out = {} + for key, path in FINGERPRINT_SOURCES.items(): + try: + out[key] = sha_text(read_raw(path)) + except Exception: + out[key] = None + out["generated_at_utc"] = now_utc() + return out + + + def dropped_aliases(issues): + try: + manifest = json.loads(read_raw(ALIAS_MANIFEST_PATH)) + except Exception as exc: + issues.append({"code": "ALIAS_MANIFEST_UNREADABLE", "message": str(exc)[:300]}) + return {} + return {str(x["dropped_evidence_index"]): x.get("canonical_evidence_index") + for x in manifest.get("dropped_aliases") or [] + if isinstance(x, dict) and x.get("dropped_evidence_index")} + + + def gate_one(item, run_id, assets): + part = json.loads(read_raw(item["part_path"])) + if part.get("run_id") != run_id: + raise DocError("STALE_PART", str(part.get("run_id"))) + env = part.get("envelope") + if not isinstance(env, dict): + raise DocError("MISSING_TASK_OUTPUT", str((part.get("error") or {}).get("code"))) + output = parse_model(env) + m = DOC_TAG_RE.search(read_raw(item["input_path"])) + if not m: + raise DocError("INPUT_DOCUMENT_MISSING", item["input_path"]) + # gate 는 LLM 이 preflight 로 본 본문(입력 파일의 안)으로 원문 대조한다. + text = m.group(1) + return assets["gate"]["run_gate"](output, text, assets["gate_rules"], assets["lexicon"], + evidence_index=item["evidence_index"], + provenance="EVIDENCE", mode="full") + + + def main(issues): + run_id, status = None, "BLOCKED" + fp = fingerprint() + for key in FINGERPRINT_SOURCES: + if fp[key] is None: + issues.append({"code": "FINGERPRINT_SOURCE_MISSING", "message": FINGERPRINT_SOURCES[key]}) + records, excluded, documents = [], [], [] + asset_sha = {} + try: + plan = json.loads(read_raw(PLAN_PATH)) + run_id = plan.get("run_id") + if plan.get("status") != "READY": + raise RuntimeError("INPUT_PLAN_NOT_READY:%s" % plan.get("status")) + if plan.get("evidence_shard_plan_sha256") != fp["evidence_shard_plan_sha256"]: + issues.append({"code": "SHARD_PLAN_CHANGED_SINCE_V0", "message": "V0 이후 evidence_shard_plan.json 이 바뀌었다"}) + assets = load_assets(["gate_check", "gate_rules", "lexicon"]) + asset_sha = assets["sha256"] + dropped = dropped_aliases(issues) + for item in plan.get("items") or []: + doc = {"evidence_index": item["evidence_index"], "status": "OK", + "record_count": 0, "rejected": [], "issues": []} + if item["evidence_index"] in dropped: + # B1 gate 가 중복 별칭으로 뺀 문서는 gate 하지 않고 제외만 기록한다. + doc["status"] = "EXCLUDED_BY_ALIAS" + excluded.append({"evidence_index": item["evidence_index"], + "canonical_evidence_index": dropped[item["evidence_index"]]}) + documents.append(doc) + continue + try: + rep = gate_one(item, run_id, assets) + doc["rejected"], doc["issues"] = rep["rejected"], rep["issues"] + records.extend(rep["records"]) + doc["record_count"] = len(rep["records"]) + if rep["rejected"] or any(x.get("severity") == "error" for x in rep["issues"]): + doc["status"] = "REVIEW" + except DocError as exc: + doc.update(status="FAILED", error={"code": exc.code, "detail": exc.detail}) + except Exception as exc: + doc.update(status="FAILED", error={"code": "GATE_FAILED", "detail": str(exc)[:300]}) + documents.append(doc) + for s in plan.get("skipped") or []: + documents.append({"evidence_index": s.get("evidence_index"), "status": "FAILED", + "record_count": 0, "rejected": [], "issues": [], + "error": {"code": s.get("code"), "detail": s.get("message")}}) + if not any(d["status"] in {"OK", "REVIEW"} for d in documents): + status = "BLOCKED" + issues.append({"code": "NO_DOCUMENT_GATED", "message": "gate 를 통과한 문서가 없다"}) + elif all(d["status"] in {"OK", "EXCLUDED_BY_ALIAS"} for d in documents) and not issues: + status = "READY" + else: + status = "READY_WITH_REVIEW" + except Exception as exc: + issues.append({"code": str(exc).split(":")[0] or type(exc).__name__, "message": str(exc)[:300]}) + status = "BLOCKED" + if status == "BLOCKED": + records, excluded = [], [] + value_facts = {"schema_version": "stage1_value_facts.v1", "run_id": run_id, "status": status, + "source_fingerprint": fp, "record_count": len(records), + "records": records, "excluded_by_alias": excluded} + body = dumps(value_facts) + write_doc(VALUE_FACTS_PATH, body) + gate = {"schema_version": "stage1_value_facts_gate.v1", "gate_task": TASK_NAME, "run_id": run_id, + "status": status, "source_fingerprint": fp, "value_facts_sha256": sha_text(body), + "asset_sha256": asset_sha, "mode": "full", + "summary": {"documents": len(documents), + "ok": sum(d["status"] == "OK" for d in documents), + "review": sum(d["status"] == "REVIEW" for d in documents), + "failed": sum(d["status"] == "FAILED" for d in documents), + "excluded_by_alias": sum(d["status"] == "EXCLUDED_BY_ALIAS" for d in documents), + "records": len(records), + "rejected": sum(len(d["rejected"]) for d in documents)}, + "documents": documents, "issues": issues} + write_doc(GATE_PATH, dumps(gate)) + return gate + + + ISSUES = [] + GATE = None + try: + _init() + GATE = main(ISSUES) + except Exception as exc: + ISSUES.append({"code": "V2_FAILED", "message": str(exc)[:300]}) + print(json.dumps({"status": (GATE or {}).get("status", "BLOCKED"), + "run_id": (GATE or {}).get("run_id"), + "summary": (GATE or {}).get("summary"), + "value_facts_sha256": (GATE or {}).get("value_facts_sha256"), + "issues": ISSUES}, ensure_ascii=False)) + + - task_name: Task_V3_value_facts_party_linker + description: value_facts 당사자 표기를 routing/party_aliases.json 의 정규 당사자명에 연결 + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 120 + code: | + #!/usr/bin/env python3 + # Task_V3_value_facts_party_linker + # value_facts 레코드의 parties[]·stances[] 의 party_label 을 routing/party_aliases.json(T9 산출)과 맞춰 + # 정규 당사자명(client_goal 성명)을 찾고, 어휘의 코드 기입 칸 party_refs 내용으로 + # value_facts_party_links.json 에 쓴다. value_facts.json 은 고치지 않는다(V2 의 sha256 유지). + # 정규화는 T9 norm_name 을 복사했다. canonical_parties 를 먼저, aliases 를 다음에 본다. + # alias_candidates(미확정)와 stated_by(감정인·관청 등)는 쓰지 않는다. + # gate BLOCKED 이거나 별칭표 error 가 있으면 BLOCKED(연결 비움). raise 하지 않는다. + TASK_NAME = "Task_V3_value_facts_party_linker" + import copy + import hashlib + import itertools + import json + import re + import secrets + from datetime import datetime, timezone + + import httpx + + # -------------------------------------------------------------------------- + # localdocs 보일러플레이트 (SKILL.md 5장 / 5.2장) + # clientInfo 에 {{__user_hash__}} / {{__workspace_hash__}} 를 반드시 넣는다. + # Task_D0_domain_activation_gate 의 검증 완료본을 그대로 복사했다. + # -------------------------------------------------------------------------- + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=120) + MSG_ID_COUNTER = itertools.count(10) + + + def next_msg_id(): + return next(MSG_ID_COUNTER) + + + def _init(): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": TASK_NAME, "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}"}} + }, headers=MCP_HEADERS) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post(LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS).raise_for_status() + + + def _parse_mcp(text): + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + return None + try: + return json.loads(text) + except Exception: + return None + + + def _call(name, args, mid): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": mid, "method": "tools/call", + "params": {"name": name, "arguments": args} + }, headers=MCP_HEADERS) + r.raise_for_status() + p = _parse_mcp(r.text) + if not p or "result" not in p: + raise RuntimeError("MCP_CALL_FAILED:%s" % name) + return p + + + def read_raw(name): + # 원문 그대로 돌려준다. sha256 은 이 문자열의 utf-8 바이트로 계산한다(재직렬화 금지). + p = _call("read_docs", {"doc_names": [name]}, next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("EMPTY_RESPONSE:%s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("EMPTY_CONTENT:%s" % name) + return inner + raise RuntimeError("UNEXPECTED_READ_DOCS_ENVELOPE:%s" % name) + + + def write_doc(path, content): + _call("write_file", {"path": path, "content": content, "overwrite": True}, + next_msg_id()) + + + def sha_text(text): + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + + def now_utc(): + return datetime.now(timezone.utc).isoformat() + + + def dumps(obj): + return json.dumps(obj, ensure_ascii=False, indent=2) + + VALUE_FACTS_PATH = "value_facts.json" + GATE_PATH = "quality_gates/value_facts_gate.json" + PARTY_ALIASES_PATH = "routing/party_aliases.json" + LINKS_PATH = "value_facts_party_links.json" + + + def norm_name(value): + # Task_B2_SHA256_soft_gate_handoff_writer.norm_name 복사본 — 바꾸면 두 곳을 함께 바꾼다. + text = str(value or "") + pattern = r"\s*[((][^()()]*[))]\s*" + while re.search(pattern, text): + text = re.sub(pattern, " ", text) + text = " ".join(text.split()) + if text.startswith("망 "): + text = text[2:] + text = re.sub(r"\s+", "", text) + if text.startswith("주식회사") and len(text) > 4: + text = text[4:] + if text.endswith("주식회사") and len(text) > 4: + text = text[:-4] + return text + + + def build_index(aliases_doc): + index = {} + for name in aliases_doc.get("canonical_parties") or []: + index.setdefault(norm_name(name), set()).add(name) + alias_index = {} + for raw, canonical in (aliases_doc.get("aliases") or {}).items(): + alias_index.setdefault(norm_name(raw), set()).add(canonical) + return index, alias_index + + + def resolve(label, index, alias_index): + key = norm_name(label) + hits = index.get(key) or alias_index.get(key) or set() + if len(hits) == 1: + return next(iter(hits)), "RESOLVED", None + return None, "UNRESOLVED", "AMBIGUOUS" if hits else "NOT_FOUND" + + + def main(): + links, issues, status = [], [], "BLOCKED" + value_facts_raw = read_raw(VALUE_FACTS_PATH) + value_facts = json.loads(value_facts_raw) + gate = json.loads(read_raw(GATE_PATH)) + aliases_raw, aliases_doc = None, None + try: + aliases_raw = read_raw(PARTY_ALIASES_PATH) + aliases_doc = json.loads(aliases_raw) + except Exception as exc: + issues.append({"code": "PARTY_ALIASES_UNREADABLE", "message": str(exc)[:300]}) + if gate.get("status") not in {"READY", "READY_WITH_REVIEW"}: + issues.append({"code": "VALUE_FACTS_GATE_BLOCKED", "message": str(gate.get("status"))}) + elif gate.get("run_id") != value_facts.get("run_id") or gate.get("value_facts_sha256") != sha_text(value_facts_raw): + issues.append({"code": "VALUE_FACTS_GATE_MISMATCH", "message": "gate 와 value_facts.json 이 같은 실행이 아니다"}) + elif aliases_doc is None or aliases_doc.get("error"): + issues.append({"code": "PARTY_ALIASES_ERROR", + "message": str((aliases_doc or {}).get("error") or "unreadable")[:300]}) + else: + index, alias_index = build_index(aliases_doc) + for rec in value_facts.get("records") or []: + for field in ("parties", "stances"): + for i, entry in enumerate(rec.get(field) or []): + label = entry.get("party_label") if isinstance(entry, dict) else None + if not isinstance(label, str) or not label.strip(): + continue + ref, link_status, reason = resolve(label, index, alias_index) + links.append({"value_id": rec.get("value_id"), "path": "%s[%d]" % (field, i), + "party_label": label, "party_ref": ref, + "status": link_status, "reason": reason}) + status = "READY_WITH_REVIEW" if any(x["status"] == "UNRESOLVED" for x in links) else "READY" + doc = {"schema_version": "stage1_value_facts_party_links.v1", "linker_task": TASK_NAME, + "run_id": value_facts.get("run_id"), "status": status, + "party_ref_kind": "client_goal_party_name", + "value_facts_sha256": sha_text(value_facts_raw), + "party_aliases_sha256": sha_text(aliases_raw) if aliases_raw else None, + "generated_at_utc": now_utc(), + "summary": {"links": len(links), + "resolved": sum(x["status"] == "RESOLVED" for x in links), + "unresolved": sum(x["status"] == "UNRESOLVED" for x in links)}, + "links": links if status != "BLOCKED" else [], "issues": issues} + write_doc(LINKS_PATH, dumps(doc)) + return doc + + + DOC = None + ERRORS = [] + try: + _init() + DOC = main() + except Exception as exc: + ERRORS.append({"code": "V3_FAILED", "message": str(exc)[:300]}) + try: + write_doc(LINKS_PATH, dumps({"schema_version": "stage1_value_facts_party_links.v1", + "linker_task": TASK_NAME, "status": "BLOCKED", "links": [], + "issues": ERRORS, "generated_at_utc": now_utc()})) + except Exception: + pass + print(json.dumps({"status": (DOC or {}).get("status", "BLOCKED"), + "summary": (DOC or {}).get("summary"), + "issues": (DOC or {}).get("issues", []) + ERRORS}, ensure_ascii=False)) + task_procedure: # [근거 2] 두 사슬이 IN 에서 병렬 분기한다. # 왼쪽 = 스크리너 사슬, 오른쪽 = 증거 사슬. @@ -6885,7 +8021,7 @@ Agent: # ---- 증거 사슬 (T2 -> T3 -> ... -> T8) -------------------------------- Task_Evidence_shard_planner: - nexts: ["Task_B1_map_doc_*"] + nexts: ["Task_B1_map_doc_*", "Task_V0_value_facts_input_planner"] wait_until: ["IN"] # [근거 5] 아래 T3~T7 다섯 노드는 v3 원문 그대로다. fan-out 토큰 3종 무변경. @@ -6900,7 +8036,7 @@ Agent: wait_until: ["Task_B1_map_doc_{same_ordinal}"] Task_B1_quality_gate_evidence_indexed: - nexts: ["Task_B2_quality_gate_event_candidates"] + nexts: ["Task_B2_quality_gate_event_candidates", "Task_V2_value_facts_gate_merger"] wait_until: ["all Task_B1_map_doc_*"] Task_B2_quality_gate_event_candidates: @@ -6924,12 +8060,38 @@ Agent: wait_until: ["Task_B12_gate_audit_finalizer", "Task_A0_domain_screener_02"] Task_B2_SHA256_soft_gate_handoff_writer: - nexts: ["OUT"] + nexts: ["OUT", "Task_V3_value_facts_party_linker"] wait_until: ["Task_D0_domain_activation_gate", "Task_A_client_goal"] + # ---- V 사슬 (가액금액 추출) ------------------------------------------- + # 사건 사슬은 V 를 기다리지 않는다. V 는 planner 뒤에서 B 사슬과 나란히 돌고 V3 만 T9 를 기다린다. + # V0 -> V2 직결: V0 가 빈 fan-out 을 내도 V2 가 BLOCKED 를 기록하고 끝난다(S2_10 load_fanout 관례). + # when 은 쓰지 않는다(SKIPPED 부모 뒤 all X_* 대기 멈춤 실측). + Task_V0_value_facts_input_planner: + nexts: ["Task_V1_value_facts_*", "Task_V1c_value_facts_capture_*", "Task_V2_value_facts_gate_merger"] + wait_until: ["Task_Evidence_shard_planner"] + + Task_V1_value_facts_*: + nexts: ["Task_V1c_value_facts_capture_{same_ordinal}"] + wait_until: ["Task_V0_value_facts_input_planner"] + + Task_V1c_value_facts_capture_*: + nexts: ["Task_V2_value_facts_gate_merger"] + wait_until: ["Task_V1_value_facts_{same_ordinal}"] + + # B1 gate 를 기다리는 이유: 중복 별칭으로 빠진 문서(finalized_evidence_id_manifest.dropped_aliases)와 + # 출처 지문 evidence_indexed.json 이 B1 gate 에서 확정된다. + Task_V2_value_facts_gate_merger: + nexts: ["Task_V3_value_facts_party_linker"] + wait_until: ["all Task_V1c_value_facts_capture_*", "Task_V0_value_facts_input_planner", "Task_B1_quality_gate_evidence_indexed"] + + Task_V3_value_facts_party_linker: + nexts: ["OUT"] + wait_until: ["Task_V2_value_facts_gate_merger", "Task_B2_SHA256_soft_gate_handoff_writer"] + OUT: nexts: [] - wait_until: ["Task_B2_SHA256_soft_gate_handoff_writer"] + wait_until: ["Task_B2_SHA256_soft_gate_handoff_writer", "Task_V3_value_facts_party_linker"] prevs: [] nexts: [] diff --git a/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_1_v.8_10_30_old.yml b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_1_v.8_10_30_old.yml new file mode 100644 index 00000000..886ec259 --- /dev/null +++ b/Case_02_Comparison_Research/YAML_Prompts/1. Stage_1/v.8/stage_1_part_1_v.8_10_30_old.yml @@ -0,0 +1,6935 @@ +# ============================================================================= +# Liti-agent Stage 1 Part 1 v.8 — 증거 기반 · 목표 · 도메인 확정 (통합 실행본) +# +# 정본 근거 +# 전체 DAG : stage_1_update_strategy.md §1 Part 1 블록 +# 개정 명세 : P1-T2_to_T9_update_strategy.md §1~§4 +# 조립 명세 : stage_1_part_1_완성용_작업명세서.md §3 (16 슬라이스) +# 설계 판정 : P1-T2_to_T9_선결작업수행결과/01_설계판정/P0_설계판정_결정문서.md +# 계측 재정의 : 같은 폴더 02_계측재정의/P2_계측통로_재정의.md +# +# 구성 — task 13종 (v3 대비 +4 신설 · 4 개정 · 5 무변경) +# [신설] Task_A0_domain_screener_01 / 02 / 03 ver_8 후보본 +# [개정] Task_A_client_goal Task_A_client_goal_v4.yml +# [무변경] Task_Evidence_shard_planner v3 622-945 +# [개정] Task_B1_map_doc_* T3_Task_B1_map_doc_v4.yml +# [무변경] Task_B2_map_events_* v3 1540-2204 +# [무변경] Task_B1_quality_gate_evidence_indexed v3 2205-2802 +# [개정] Task_B2_quality_gate_event_candidates v3 2803-3519 + v.8 R5(CHECK 3 정본 id 부여) +# [무변경] Task_B12_gate_llm_adjudicator v3 3520-3679 +# [무변경] Task_B12_gate_audit_finalizer v3 3680-4041 +# [신설] Task_D0_domain_activation_gate ver_8 후보본 (정정본) +# [개정] Task_B2_SHA256_soft_gate_handoff_writer T9_..._v4.yml +# +# 개정 요지 +# T0 3종 스크리너 사슬 신설. 02 가 01 의 초안을 봉인하고 03 이 후보 어휘를 압축한다. +# T1 domain_profiles 를 도메인ID 키 개방형으로. 스키마는 정적 자산으로 분리. +# T3 증거 구성요소 어휘를 registry 합집합 참조로. v3 구조 어휘와 병존(P0 판정 A)하며 +# part 파일에 registry_component_ids 슬롯 1개를 additive 로 더한다(P0 판정 B). +# schema_contract_version 은 evidence_indexed_part.v4 유지 — 순수 additive 다. +# D0 판정 로직을 YAML 에 쓰지 않는다. stage1_runtime/activation_gate.py 를 반입해 호출하고 +# signals/adapters/sg01_activation_adapter.py 로 자기검증한다. 결정 필드는 +# execution_eligible 하나뿐이다(D-3 넓은 정의). +# T9 봉인 사전에 세 해시 추가(screening / activation_manifest / registry_index). +# 원문 sha256 이므로 read_raw 를 쓴다. unwrap_text 재직렬화 금지. +# schema_version 은 stage1_part1_soft_gate_handoff.v1 유지 — 역시 additive 다. +# T9(v.8 alias) client_goal.parties 를 canonical 로 삼아 증거·사건의 당사자 표기 변형을 집계한 +# routing/party_aliases.json 을 handoff 직전에 1회 쓴다(aliases / alias_candidates / +# succession_candidates). digest 7 키·handoff 바이트·client_goal.json 은 불변. T1 -> T9 변 추가. +# 보조 산출물이므로 집계 실패는 error 필드로 남기고 handoff 기록을 막지 않는다. +# T4/T6(v.8 OBLIGEE) 사건 후보에 additive 필드 obligation_direction{obligee_candidates, obligor_candidates} 추가. +# 문서가 채권 자체의 채권자·채무자를 직접 특정할 때만 채운다(stage_1_OBLIGEE_개정방안.md §2~§3). +# T6 CHECK 6 는 비차단(R-SELFWARN 재사용). schema_contract_version·DAG·B12 지침·digest 키 불변. +# T4 r2(2026-10-07) 방향 규칙을 event_kind 매핑 양성 조건으로 교체(채권발생·채권관리·amount 있는 통지만 채움), 빈 상수·예시 4개를 +# 출력 템플릿 옆으로 이동, self-validation invariant 7(누락 시 빈 상수 삽입 보정) 추가, T3·T4 llm_model gemini-3.5-flash-lite. +# T6 R5(2026-10-10) CHECK 3 에서 형식·ordinal 이탈 candidate_id_proposed 를 part 내 순번으로 EVT-{o}-{seq:02d} 정본 부여(제자리 치환, +# precheck·audit checks[candidate_id_collision].id_normalizations 기록, severity HARD_WARNING; 치환 후 중복만 hard). +# 실패분석_stage_1_part_2_v.8.md §4 F-1. mapper 프롬프트·CANDIDATE_ID_RE·최종 파일 스키마·보존 불변식 불변. +# +# 모듈 반입 규약 (localdocs 가 .py 를 서빙하지 않아 도입한 우회책) +# 모든 .py 에는 같은 디렉터리에 바이트 동일한 .txt 형제 미러가 배포된다. +# 빌더 규칙이며 예외는 build_default_agent_stage1.py 하나다. 미러는 정본 옆에 놓이므로 +# sg01_activation_adapter 의 미러는 signals/adapters/ 에 있다(stage1_runtime/ 이 아니다). +# 반입 시 sha256 을 Default_Agent/runtime_manifest.json 과 대조하고, 불일치면 실행하지 않는다. +# +# 정적 자산 선행 조건 (P1-T2_to_T9_update_strategy.md §0.2 — 전부 충족) +# Default_Agent/stage1_runtime/activation_gate.py +# Default_Agent/platform/schemas/client_goal_domain_profiles.schema.json +# Default_Agent/routing/activation_cue_digest.md +# Default_Agent/routing/evidence_component_union.md +# Default_Agent/platform/contracts/determinism_scope_contract.json +# +# 이 파일은 스테이지 하나다. 스테이지 선언 1벌 · task_procedure 1벌 · tasks 1벌. +# 조각 후보본들이 각자 갖고 있던 Agent/Stages 머리와 자기 task_procedure 는 전부 걷어냈다. +# mcpServers 합집합은 {localdocs, code-executor} 이며 v3 머리가 이미 둘 다 선언한다. +# ============================================================================= +Agent: + name: Liti-agent_Civil_Suit_Plaintiff_Stage_1_Part_1 + description: 민사소송 원고 송무 초지능 AI변호사 - Stage 1 Part 1 기초작업 + version: v.2 + + Stages: + - name: stage1_사건개요파악_기초작업 + description: 사건개요 파악, 기초정보 추출 + llm_provider: openai + llm_model: gpt-4o-2024-08-06 + tools: + mcpServers: + localdocs: + type: streamable-http + url: "http://mcp-localdocs:8012/mcp" + description: Get the content of local documents + code-executor: + type: streamable-http + url: https://code-executor.mcp.eroomai.com/mcp + description: Run scripts of programming languages + headers: + Authorization: Bearer rR8OXqWrVZA1gFEo8oWfBkw2XgpWoGrrspw5ObsxTCM= + + tasks: + - task_name: Task_A0_domain_screener_01 + llm_provider: google + llm_model: 'gemini-3.5-flash-lite' + llm_reasoning: high + llm_verbosity: low + cache_control: + mode: auto + ttl: 1h + use_tools: + - localdocs + # preflight: true + preflight_files 화이트리스트. + # 화이트리스트를 명시하면 프롬프트 본문 regex 스캔이 꺼지고 이 두 경로만 + # 미리 읽힌다. 입출력 통제는 유지되면서, 정적 경로인 단어 사전이 캐시 + # 공유 영역에 inline 되어 매 실행 35KB 를 다시 태우지 않는다. + # 도구 오용 방지는 프롬프트의 / 이 맡는다. + preflight: true + preflight_files: + - Default_Agent/routing/activation_cue_digest.md + - client_meeting.md + prompts: + - role: user + content: |- + + + - You are executing one LLM sub-task inside Stage 1 of a Korean civil-litigation complaint-generation pipeline. + - The current task's static block, role overlay, assigned inputs, output schema, and writer boundary control. + - This common prefix cannot expand the current task's input set, output set, legal domain, validation authority, writer authority, or reasoning depth. + - If any common rule appears broader than the current task, apply only the narrower current-task version. + - Stage 1 prepares verified structured artifacts. Do not draft complaint prose or final counsel-level conclusions unless the current task explicitly authorizes a validation or gate conclusion. + + + + - Use only assigned files, provided context inputs, prior outputs, and allowed tools. + - Do not import facts, law, procedural history, parties, dates, amounts, IDs, document contents, or source meanings from memory, outside knowledge, or unassigned files. + - Treat prior outputs as authority only to the extent the current task names them or provides them as context. + - If a value is unsupported, missing, conflicting, stale, or out of scope, use only the current schema's allowed null, empty, unknown, warning, blocked, or needs_review path. + + + + - Preserve exact source identifiers required by the current schema. + - Maintain separation among raw fact, inferred fact, legal signal, evidence support, fact support, validation issue, and final gate decision when the current schema distinguishes them. + - Do not upgrade meeting-only or indirect material into direct proof. + - Do not silently resolve material conflicts. If the current schema has a conflict or uncertainty field, use it; otherwise stay within the task's allowed warning or review path. + + + + - Follow required JSON shape, key names, enum values, ordering, file names, and status strings exactly. + - Do not add arbitrary keys, prose, markdown fences, alternative files, unauthorized repair, or explanatory material outside allowed fields. + - Create, mutate, normalize, merge, or finalize IDs only when the current task explicitly authorizes it. + - Write final files only when the current task is the authorized writer. Validators and guards report issues in their own authorized schema and do not silently repair unless instructed. + + + + - Prefer the current prompt and schema, assigned structured upstream artifacts, compact indexes, ledgers, manifests, bundles, and gates. + - Read raw evidence or meeting text only when the current task requires direct provenance, ambiguity resolution, or a schema-required value missing from structured artifacts. + - For map or projection tasks, process only the assigned item, domain, or batch. Reducers aggregate only the inputs assigned to them. + - Do not restate, summarize, cite, or copy this common prefix in any output. + + + + - Return only the requested structured artifact, concise allowed rationale fields, validation notes, or status object. + - Keep chain-of-thought private. + - Stop when the current schema is complete and safe. + + + + + - Fill only slots that the current extraction, mapping, support, or projection schema asks for. + - Treat legal labels, party assertions, meeting narrative, and upstream candidates as routing signals only, not proof by themselves. + - Preserve the strongest source IDs and locators required by the current schema; do not quote long passages unless asked. + - Separate raw fact, inferred fact, support signal, and review note when the schema distinguishes them. + - If a source conflict is visible, preserve it only through the current schema's allowed uncertainty, warning, or review field. Do not classify full contradiction severity here. + - Do not perform norm search, final legal-effect classification, merits judgment, cross-domain merge, or final writer repair unless the current task explicitly requires it. + - Stop after the assigned item, evidence shard, domain, batch, support file, or fact-support projection is complete. + + + + + Task_A0_domain_screener_01 + + You are an MCP-enabled LLM agent assisting plaintiff-side Korean civil/commercial litigation counsel. + + + `client_meeting.md`와 `Default_Agent/routing/activation_cue_digest.md` 두 개만 읽고 `routing/domain_screening_draft.json`을 생성한다. + 이 task가 답해야 할 질문은 "이 사건이 137종 사건유형 중 무엇인가"가 아니라 "registry의 26개 법리 렌즈 중 어느 것이 켜지는가"이다. + 산출물은 확정이 아니라 가설이다. 확정은 하류의 `Task_D0_domain_activation_gate`가 registry 모듈을 호출하여 결정론적으로 수행한다. + 본 task는 판단 4종(`status`, `candidates`, `unmatched_issue_refs`, `review_items`)과 그 판단을 검증 가능하게 만드는 최소 부속 정보만 생성한다. + 닫힌 스키마 `stage1_domain_screening.v1`의 비판단 6종(`schema_version`, `registry_version`, `registry_index_sha256`, `source_document_refs`, `screening_policy`, `contract_guards`)은 본 task가 만들지 않는다. 후속 task `Task_A0_domain_screener_02`가 registry에서 직접 읽어 붙이고 스키마 검증까지 수행한다. + 본 task의 산출물은 개방형 초안이므로 닫힌 스키마의 필드 집합에 구속되지 않는다. 다만 `candidates` 배열의 각 원소는 닫힌 스키마의 후보 객체와 키 구성이 정확히 같아야 한다. 후속 task가 변형 없이 그대로 복사하기 때문이다. + + + + + - In this task, `provisional_status` and `confidence` are meeting-grounded routing hypotheses, not legal conclusions. + - The EXTRACTION overlay's prohibition on final legal-effect classification does not prohibit the schema-authorized `provisional_status`, `confidence`, or `requested_calculation_domains` fields. + - The overlay's prohibition on norm search remains absolute here. 법령·판례·조문 검색과 인용은 어떤 형태로도 금지한다. + - 본 task는 final writer가 아니다. `FINAL_WRITER_REDUCER` 오버레이는 본 task에 적용되지 않으며, 어떤 최종 산출물도 확정하지 않는다. + + + + + - `client_meeting.md` — 유일한 사실 원천 + - `Default_Agent/routing/activation_cue_digest.md` — 단어 사전(라우팅 어휘). 사실 원천이 아니다. + + + - `routing/domain_screening_draft.json` + + + - `list_docs` : 입력 2종의 존재 확인과 출력 1종의 생성 확인에만 쓴다. + - `write_file` : `routing/domain_screening_draft.json` 한 경로에만 1회 쓴다. + - `read_docs` : 원칙적으로 쓰지 않는다. 두 입력은 preflight로 이미 제공되어 있다. preflight 내용이 제공되지 않은 경우에 한하여 위 두 경로에만 1회 쓴다. + + + - 위 화이트리스트 밖의 어떤 파일도 읽지 않는다. 특히 `Default_Agent/domains/*/domain_config.json` 원본 26개를 직접 읽지 않는다. + - `Default_Agent/validation_assets/routing/case_kind_domain_matrix.v2.json`을 읽지 않는다. 사건유형 이름을 담은 오프라인 회귀 전용 자산이며 런타임 입력이 금지되어 있다. + - `routing/domain_screening.json`을 만들거나 건드리지 않는다. 그 파일은 후속 task의 산출물이다. + - 중간 파일 생성, 산출물 재읽기, `write_file` 2회 이상 호출. + - 사건유형 명칭, 당사자 이름, 사건번호를 라우팅 판단의 근거로 삼기. + - 최종 법률효과 판단, 단일 도메인 확정, 승패 예측, 청구금액 산정, 법령·판례 검색. + - 닫힌 스키마에 없는 필드명 사용: `track_hypothesis`, `domain_hypotheses`, `relief_mode_hints`, `computation_hints`, `matched_cues`, `notes_kr`. + - 비판단 6종(`schema_version`, `registry_version`, `registry_index_sha256`, `source_document_refs`, `screening_policy`, `contract_guards`)을 초안에 넣기. + - 단어 사전에만 있고 상담록에 없는 표현을 사실처럼 근거로 삼기. + + + + + 1. `list_docs`로 `client_meeting.md`와 `Default_Agent/routing/activation_cue_digest.md`의 존재만 확인한다. + 2. preflight로 제공된 두 파일의 내용을 쓴다. 제공되지 않은 경우에 한하여 `read_docs`를 1회 호출한다. + 3. ``에 따라 상담록을 source unit으로 나누고 각 unit에 `MTG.*` 식별자를 부여한다. + 4. ``로 사전을 해석한다. + 5. `` → `` → `` → `` → `` 순서로 판단 4종을 만든다. + 6. ``를 적용하고 ``를 자기점검한다. + 7. 메모리에서 초안 객체를 만들고 `write_file(overwrite=true)`로 `routing/domain_screening_draft.json`에 저장한다. + 8. `list_docs`로 `routing/domain_screening_draft.json` 존재만 확인한다. 절대 읽지 않는다. + 9. 정확히 `"도메인 스크리닝 초안 생성 완료"`만 출력하고 종료한다. + + + + - 필수 입력 누락, 빈 파일, 파싱 불가: 즉시 중단하고 채팅으로만 보고한다. 파일은 쓰지 않는다. + - 단어 사전의 머리말에 `registry_version`이 없거나 `## DOMAINS` 아래 도메인 절이 26개가 아니면 중단하고 `FAILED: activation_cue_digest`만 보고한다. + - tool 오류: 원인 확인 후 1회만 재시도한다. 재실패 시 `FAILED: `만 보고하고 종료한다. + - 판단이 어려운 사안을 억지로 확정하지 않는다. 판단 불가는 실패가 아니라 `review` 상태와 검토 항목으로 표현한다. + + + + - 사실 원천은 `client_meeting.md` 하나뿐이다. + - `Default_Agent/routing/activation_cue_digest.md`는 사실 원천이 아니다. 무엇을 찾을지 알려주는 라우팅 어휘 목록이다. 사전의 `match_value` 문구를 상담록의 대응 서술 없이 근거로 인용하면 그것은 환각이다. + - 상담록의 문장들을 조합해 새로운 사실을 만들지 않는다. 상대방 주장은 주장으로만, 희망사항은 희망으로만 취급한다. + - 상담록에만 있는 내용은 증거가 아니다. 증거 승격은 하류 단계의 권한이며 본 task는 그 판단을 하지 않는다. + - 사건유형 이름을 사실 권위로 쓰지 않는다. 라우팅은 구조화된 단서와 서술로만 한다. + + + + - 사전은 머리말, `## LEGEND`, `## GLOBAL_DEFAULTS`, `## USAGE`, `## DOMAINS` 다섯 부분이다. 판단에 쓰는 것은 `GLOBAL_DEFAULTS`와 `DOMAINS`이다. + - 도메인 절 머리 형식: `### | | kind= | ao=<0|1> | dep= | calc=` + - 단서 줄 형식: + `P|||||||` + `N|||||||` + `C|||` + `OVR|=|...` + - `` 코드는 두 개뿐이다. `DR`=confidence_downrank_only, `MR`=monitor_review. + - `` 코드 `SP`/`SU`는 하류 단계의 조회 위치 표시다. 본 task는 상담록만 보므로 `src` 값을 이유로 단서를 배제하지 않는다. + - `OVR` 줄이 있으면 그 도메인에 한하여 `GLOBAL_DEFAULTS`를 덮어쓴다. 값 `absent`는 원본에 그 키가 없다는 뜻이므로 그 임계값 판정을 적용하지 않는다. + - 모든 충돌 단서의 효과는 `hard_review`이며 그래서 `C` 줄에서 생략되어 있다. + - 사전에 없는 도메인 ID, 단서 ID, 검토 코드, 계산 ID는 만들지 않는다. + + + + - 상담록을 문단 단위 source unit으로 나누고 각 unit에 다음 형식의 식별자를 부여한다. + `MTG.
.<사건군 2자리>.<항 2자리>` + - `
`은 세 값만 쓴다. 【상담내용】=`FACT`, 【사건관계인의 주장】=`OPP`, 【의뢰인의 희망사항】=`WISH`. + - `<사건군 2자리>`는 그 섹션 안의 `1.`~`9.` 번호를 두 자리로 채운 값이다. 사건군에 속하지 않는 문단은 `00`. + - `<항 2자리>`는 `가.`=`01`, `나.`=`02`, `다.`=`03`, `라.`=`04`, `마.`=`05`, `바.`=`06`, `사.`=`07`, `아.`=`08` 순서다. 항 구분이 없는 문단은 `00`. + - 상담일지 머리표(사무소·연락처·접수번호·상담일자·의뢰인 표)는 문단마다 자르지 않고 `MTG.META.01` 한 단위로 접는다. 상담일자와 의뢰인 값은 그 안에 보존된 것으로 본다. + - 예시: 【상담내용】 `2.` 사건군의 `라.` 문단 → `MTG.FACT.02.04`. 【사건관계인의 주장】 `5.`의 항 구분 없는 문단 → `MTG.OPP.05.00`. 【의뢰인의 희망사항】 `3.` → `MTG.WISH.03.00`. 【상담내용】의 사건군 앞 머리 문단 → `MTG.FACT.00.00`. + - 식별자는 반드시 `^[A-Za-z][A-Za-z0-9_.:/-]{0,255}$`를 만족해야 한다. 한글, 공백, 대괄호, `#`을 쓰지 않는다. + - 어떤 문단도 버리지 않는다. 위 규칙에 맞지 않는 문단은 `MTG.RAW.<3자리 일련번호>`로 부여하고 `review_items`에 `SCREENING_SOURCE_UNIT_FALLBACK`를 남긴다. + - 부여한 전체 목록을 `source_unit_index`에 문서 등장 순서대로 기록한다. 이 목록이 본 task가 살펴본 원천의 전부이며, 후속 task가 같은 규칙으로 독립 재산출하여 대조한다. + - 후속 task가 `source_document_refs`를 만든다. 본 task는 그 필드를 만들지 않는다. + + + + - 각 source unit을 읽고 사전의 긍정 단서 `match_value`에 대응하는 서술이 그 unit에 있는지 판단한다. + - 대응이 인정되면 그 도메인 후보의 `positive_refs`에 해당 unit 식별자를 넣는다. 단서 ID(`E13-P01` 같은 값)는 `positive_refs`에 넣지 않는다. 그 배열은 원천 식별자만 담는다. + - 어떤 단서가 근거였는지는 `reasoning_summary`에 단서 ID로 적는다. + - 단서 하나에만 걸린 상태로 후보를 세우지 않는다(`single_keyword_activation_forbidden`). 서로 다른 단서 두 개 이상 또는 서로 다른 source unit 두 개 이상이 필요하다. + - `cue_type`이 `evidence_component`인 단서는 그 자료의 존재가 상담록에 직접 언급된 경우에만 인정한다. 있을 법하다는 추론으로 인정하지 않는다. + - 한 unit이 여러 도메인에 동시에 걸릴 수 있다. 배타적으로 하나만 고르지 않는다. + - 사건유형 명칭, 당사자 이름, 사건번호는 어떤 경우에도 매칭 근거가 되지 않는다. + + + + - 도메인별로 걸린 긍정 단서의 `weight`를 합산한다. 같은 단서가 여러 unit에서 걸려도 1회만 계산한다. + - 합이 `leaf_activation_threshold` 이상이면 `candidate`, `monitor_threshold` 이상이면 `monitor`로 본다. 기본값은 각각 1.0과 0.5이며 `OVR` 줄이 있으면 그 값을 쓴다. + - 임계값은 registry가 정한 참고값이며 판정 권한이 없다. 임계값에 못 미쳐도 강한 서술이 있으면 `monitor` 또는 `review`로 보존한다. 임계값을 넘었다는 사실만으로 `candidate`를 확정하지도 않는다. + - 네 상태의 뜻은 다음과 같다. + `candidate` — 이 도메인이 독자 쟁점으로 켜질 만한 서술이 있다. + `supporting` — 독자 쟁점은 아니나 다른 도메인의 요건을 뒷받침한다. 다른 도메인의 `dep=`에 등장하는 선행 도메인이 주로 여기에 온다. + `monitor` — 가능성은 있으나 서술이 얇다. 삭제하지 않고 감시한다. + `review` — 판단이 갈리거나 충돌 단서가 걸렸다. + - `confidence`는 `high|medium|low` 세 값이다. 강한 단서 두 개 이상이면 `high`, 강한 단서 하나이거나 보조 단서 위주이면 `medium`, 부정 단서로 낮춰졌거나 서술이 얇으면 `low`로 본다. + - `ao=1`인 도메인(E-00, X1, X2, X3)은 상시 활성 대상이다. 단서가 걸리지 않아도 후보 목록에서 누락시키지 않으며, 대응 서술이 없으면 `monitor`와 `low`로 남긴다. + - `reasoning_summary`는 1자 이상 1200자 이하다. 어떤 단서 ID가 어느 unit에서 걸렸는지와 상태를 그렇게 정한 이유만 적는다. 법률 결론, 승패 전망, 조문 인용을 적지 않는다. + - `final_determination_forbidden`은 모든 후보에서 `true`이다. + + + + - 부정 단서가 걸리면 해당 unit 식별자를 `negative_refs`에 넣는다. + - `DR`은 `confidence`만 한 단계 낮춘다. `high`→`medium`, `medium`→`low`, `low`는 그대로 둔다. + - `MR`은 `provisional_status`를 `monitor`로 옮긴다. + - 어느 경우에도 후보를 목록에서 삭제하지 않고, `provisional_status`를 `candidate`에서 두 단계 넘게 내리지 않는다(`candidate_downgrade_forbidden`). + - 충돌 단서가 걸리면 해당 unit 식별자를 `conflict_refs`에 넣고, 그 `C` 줄의 `review_code`를 그대로 써서 `review_items`에 항목을 추가한다. 검토 코드를 새로 만들지 않는다. + - 충돌 단서가 걸린 후보의 `provisional_status`는 `review`로 하고 `confidence`는 `low`를 넘지 않는다. + - 충돌을 조용히 해소하지 않는다. 어느 쪽이 맞는지 고르지 않고 양쪽 근거를 모두 남긴다. + + + + - `source_unit_index`의 unit 중 어떤 후보의 `positive_refs`·`negative_refs`·`conflict_refs`에도 들어가지 않은 것을 모두 `unmatched_issue_refs`에 넣는다. 하나도 버리지 않는다. + - `unmatched_issue_refs`가 비어 있지 않으면 `review_items`에 `UNROUTED_ISSUE_REVIEW` 항목을 하나 만들고 그 unit들을 `source_refs`에 담는다. `severity`는 `review`, `domain_ids`는 `["E-00"]`로 한다. + - `review_items` 각 항목의 필수 키는 `review_code`, `severity`, `reason`, `source_refs` 넷이다. 선택 키는 `domain_ids`, `unresolved_type`, `blocks_final_drafting` 셋이다. 다른 키를 만들지 않는다. + - `review_code`는 `^[A-Z][A-Z0-9_]{2,127}$`를 만족해야 하고, 사전의 `C` 줄에 적힌 코드이거나 `UNROUTED_ISSUE_REVIEW` 또는 `SCREENING_SOURCE_UNIT_FALLBACK` 중 하나여야 한다. + - `severity`는 `info|review|hard_warning|block` 네 값이다. 본 task는 `block`을 쓰지 않는다. 실행을 막는 판정은 하류 게이트의 권한이다. + - `status`는 다음 순서로 정한다. + 입력 자체가 판정 불가이면 `BLOCKED`. + 하드 실패가 있으면 `FAILED`. + `review_items`가 하나라도 있으면 `READY_WITH_REVIEW`. + 그 외에는 `READY`. + - 본 task는 `status`를 제안할 뿐이다. 후속 task는 이 값을 올릴 수 있어도 내릴 수 없다. + + + + - 금액 계산이 필요해 보이는 서술이 있으면 그 후보의 `requested_calculation_domains`에 계산 ID를 넣는다. + - 넣을 수 있는 값은 사전의 그 도메인 머리에 적힌 `calc=` 목록 안에 있는 것뿐이다. 목록 밖 값은 넣지 않는다. + - 계산 ID 형식은 `^CE-[A-Z0-9][A-Z0-9-]{0,15}$`이다. + - 본 task는 어떤 금액도 계산하지 않고 이율·기산일·기간·원금을 정하지 않는다. 계산이 필요하다는 표시만 남긴다. + - 필요 없으면 빈 배열로 둔다. + + + + - 인코딩은 UTF-8, 줄바꿈은 LF, 문자열은 NFC로 정규화한다. + - 모든 참조 배열은 중복 없이 문자열 오름차순으로 정렬한다. + - `candidates`는 `domain_id` 문자열 오름차순으로 정렬한다. + - `source_unit_index`는 문서 등장 순서를 유지한다. + - 숫자를 문자열로 감싸지 않고 불리언은 `true`/`false`로 쓴다. + - 값이 없으면 빈 배열을 쓰고 `null`이나 빈 문자열을 쓰지 않는다. + - 출력은 순수 JSON 하나다. 마크다운 코드펜스, 머리말, 꼬리 설명을 붙이지 않는다. + + + + 최상위 키는 `domain_screening_draft` 하나다. 아래 키 구성을 정확히 지킨다. + + { + "domain_screening_draft": { + "draft_schema_version": "stage1_domain_screening_draft.v1", + "produced_by": "Task_A0_domain_screener_01", + "source_document_code": "MTG", + "source_document_name": "client_meeting.md", + "unit_numbering_rule": "MTG.
..", + "source_unit_index": [ + { "unit_id": "MTG.FACT.01.01", "gist": "60자 이내 요지. 판단이 아니라 그 문단이 무엇을 다루는지만 적는다." } + ], + "status": "READY | READY_WITH_REVIEW | BLOCKED | FAILED 중 하나", + "candidates": [ + { + "domain_id": "E-13", + "provisional_status": "candidate | supporting | monitor | review 중 하나", + "positive_refs": ["MTG.FACT.03.01"], + "negative_refs": [], + "conflict_refs": [], + "confidence": "high | medium | low 중 하나", + "reasoning_summary": "E13-P01은 MTG.FACT.03.01에서, E13-P02는 MTG.FACT.03.03에서 대응 서술을 확인함. 합 2.0으로 활성 임계값을 넘어 candidate로 둠.", + "final_determination_forbidden": true, + "requested_calculation_domains": ["CE-03"] + } + ], + "unmatched_issue_refs": ["MTG.WISH.05.00"], + "review_items": [ + { + "review_code": "UNROUTED_ISSUE_REVIEW", + "severity": "review", + "reason": "어느 도메인 단서에도 걸리지 않은 상담록 단위를 잔여로 보존함.", + "source_refs": ["MTG.WISH.05.00"], + "domain_ids": ["E-00"], + "unresolved_type": "unrouted_meeting_unit", + "blocks_final_drafting": true + } + ] + } + } + + 고정값 규칙: + - `draft_schema_version`, `produced_by`, `source_document_code`, `source_document_name`, `unit_numbering_rule` 다섯 값은 위에 적힌 문자열을 글자 그대로 쓴다. + - `candidates`의 각 원소는 위 아홉 개 키만 쓴다. `requested_calculation_domains`가 빈 배열이어도 키는 남긴다. + - `review_items`가 없으면 빈 배열로 둔다. + + + + - `source_unit_index`의 모든 `unit_id`가 `^[A-Za-z][A-Za-z0-9_.:/-]{0,255}$`를 만족하고 중복이 없는지 점검한다. + - 상담록의 모든 문단이 `source_unit_index`에 하나씩 대응하는지, 빠뜨린 문단이 없는지 점검한다. + - 모든 `positive_refs`·`negative_refs`·`conflict_refs`·`review_items[].source_refs`·`unmatched_issue_refs`의 원소가 전부 `source_unit_index`의 `unit_id` 집합 안에 있는지 점검한다. 목록 밖 식별자가 하나라도 있으면 고친다. + - `source_unit_index`의 개수가 (어느 후보엔가 인용된 unit 수) + (`unmatched_issue_refs` 수)와 같은지 점검한다. 어긋나면 인용 관계를 다시 본다. + - 모든 `domain_id`가 사전 `## DOMAINS`에 실제로 있는 값이고 `^(?:(?:EC|E)-[A-Z0-9]{2,8}|X[A-Z0-9]{1,8})$`를 만족하는지 점검한다. + - 같은 `domain_id`가 `candidates`에 두 번 등장하지 않는지 점검한다. + - 모든 후보에 `final_determination_forbidden: true`가 있는지 점검한다. + - 부정 단서가 걸린 후보가 목록에서 사라지지 않았는지, `candidate`에서 두 단계 넘게 내려가지 않았는지 점검한다. + - 충돌 단서가 걸린 후보의 `provisional_status`가 `review`이고 `confidence`가 `low`인지 점검한다. + - 모든 `review_code`가 사전의 `C` 줄에 있는 값이거나 `UNROUTED_ISSUE_REVIEW` 또는 `SCREENING_SOURCE_UNIT_FALLBACK`인지 점검한다. + - 각 후보의 `requested_calculation_domains`가 그 도메인 머리의 `calc=` 목록의 부분집합인지 점검한다. + - `ao=1`인 E-00, X1, X2, X3 네 도메인이 `candidates`에 모두 있는지 점검한다. + - 금지 필드명 여섯 개와 비판단 6종이 초안에 하나도 없는지 점검한다. + - `reasoning_summary`에 사건유형 명칭, 당사자 이름, 사건번호가 판단 근거로 쓰이지 않았는지 점검한다. + - `reasoning_summary`가 1200자를 넘지 않는지 점검한다. + - 출력 파일 경로와 성공 메시지가 정확한지 점검한다. + + + + + + [ ] 1) `list_docs`로 `client_meeting.md`와 `Default_Agent/routing/activation_cue_digest.md` 존재 확인(내용은 preflight로 이미 제공됨) + [ ] 2) source unit 채번 → 단서 매칭 → 판단 4종 생성 + [ ] 3) `` 자기점검 + [ ] 4) `write_file` 사용해서 `routing/domain_screening_draft.json` 생성 + [ ] 5) `list_docs` 사용해서 `routing/domain_screening_draft.json` 존재만 확인(절대 읽기 금지) + [ ] 6) `"도메인 스크리닝 초안 생성 완료"` 출력하고 작업을 끝낸다(terminate) + + + + + - `client_meeting.md` + - `Default_Agent/routing/activation_cue_digest.md` + + + - `routing/domain_screening_draft.json` + + + + + - 이 산출물은 가설이다. 어떤 도메인도 확정하지 않는다. + - `routing/domain_screening.json`은 후속 task의 산출물이다. 만들지 않는다. + - 비판단 6종은 초안에 넣지 않는다. + - 초안을 재읽지 않는다. + - 성공 시 마지막 채팅 출력은 정확히 `"도메인 스크리닝 초안 생성 완료"` 한 줄만 쓴다. + + + - task_name: Task_A0_domain_screener_02 + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + timeout: 180 + code: | + #!/usr/bin/env python3 + # Task_A0_domain_screener_02 + # domain_screening_draft.json (LLM 판단 4종) 를 받아 + # 비판단 6종을 registry 에서 직접 읽어 붙이고, + # 멤버십과 보존 등식을 검증하여 routing/domain_screening.json 을 기록한다. + # 판단은 하지 않는다. 상태를 올릴 수는 있어도 내리지 않는다. + import hashlib + import itertools + import json + import re + import unicodedata + + import httpx + + # -------------------------------------------------------------------------- + # localdocs 보일러플레이트 (SKILL.md 5장 / 5.2장) + # clientInfo 에 {{__user_hash__}} / {{__workspace_hash__}} 를 반드시 넣는다. + # 빠지면 localdocs 가 루트 경로를 보므로 사용자 파일을 찾지 못한다. + # -------------------------------------------------------------------------- + TASK_NAME = "Task_A0_domain_screener_02" + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=60) + MSG_ID_COUNTER = itertools.count(10) + + + def next_msg_id(): + return next(MSG_ID_COUNTER) + + + def _init(): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": TASK_NAME, "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}"}} + }, headers=MCP_HEADERS) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post(LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS).raise_for_status() + + + def _parse_mcp(text): + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + return None + try: + return json.loads(text) + except Exception: + return None + + + def _call(name, args, mid): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": mid, "method": "tools/call", + "params": {"name": name, "arguments": args} + }, headers=MCP_HEADERS) + r.raise_for_status() + p = _parse_mcp(r.text) + if not p or "result" not in p: + raise RuntimeError("MCP %s failed" % name) + return p + + + def read_raw(name): + # 파일 내용을 재직렬화 없이 원문 그대로 돌려준다. + # registry_index_sha256 은 원문 바이트의 해시여야 하므로 재직렬화를 절대 허용하지 않는다. + p = _call("read_docs", {"doc_names": [name]}, next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("Empty response: %s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("Empty content: %s" % name) + return inner + raise RuntimeError("Unexpected read_docs envelope: %s" % name) + + + def read_json(name): + raw = read_raw(name) + s = raw.strip() + if s.startswith("```"): + for part in s.split("```"): + part = part.strip() + if part.startswith("json"): + part = part[4:].strip() + if part.startswith("{") or part.startswith("["): + s = part + break + try: + return json.loads(s) + except json.JSONDecodeError: + obj, _ = json.JSONDecoder().raw_decode(s) + return obj + + + def write_doc(path, content): + _call("write_file", {"path": path, "content": content, "overwrite": True}, + next_msg_id()) + + + # -------------------------------------------------------------------------- + # 경로와 상수 + # -------------------------------------------------------------------------- + DRAFT_PATH = "routing/domain_screening_draft.json" + MEETING_PATH = "client_meeting.md" + REGISTRY_INDEX_PATH = "Default_Agent/domains/_registry_index.json" + DIGEST_PATH = "Default_Agent/routing/activation_cue_digest.md" + OUTPUT_PATH = "routing/domain_screening.json" + + SCHEMA_VERSION = "stage1_domain_screening.v1" + + # platform/schemas/domain_screening.schema.json 이 const 로 못박은 값이다. + # 하나라도 다르면 스키마 검증에서 떨어지므로 판단 대상이 아니다. + SCREENING_POLICY = { + "case_name_lookup_forbidden": True, + "single_keyword_activation_forbidden": True, + "negative_cue_downrank_only": True, + "evidence_refinement_required": True, + "unknown_review_code": "UNROUTED_ISSUE_REVIEW", + } + CONTRACT_GUARDS = { + "final_conclusion_forbidden": True, + "unknown_values_require_review": True, + "source_membership_required": True, + "strict_json_output": True, + "meeting_only_evidence_promotion_forbidden": True, + } + + STATUS_RANK = {"READY": 0, "READY_WITH_REVIEW": 1, "BLOCKED": 2, "FAILED": 3} + PROVISIONAL_STATUS = ("candidate", "supporting", "monitor", "review") + CONFIDENCE = ("high", "medium", "low") + SEVERITY = ("info", "review", "hard_warning", "block") + + REF_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_.:/-]{0,255}$") + DOMAIN_RE = re.compile(r"^(?:(?:EC|E)-[A-Z0-9]{2,8}|X[A-Z0-9]{1,8})$") + CALC_RE = re.compile(r"^CE-[A-Z0-9][A-Z0-9-]{0,15}$") + CODE_RE = re.compile(r"^[A-Z][A-Z0-9_]{2,127}$") + REG_VER_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_.-]{2,127}$") + SHA_RE = re.compile(r"^[a-f0-9]{64}$") + + CANDIDATE_REQUIRED = ("domain_id", "provisional_status", "positive_refs", + "negative_refs", "conflict_refs", "confidence", + "reasoning_summary", "final_determination_forbidden") + CANDIDATE_ALLOWED = CANDIDATE_REQUIRED + ("requested_calculation_domains",) + REVIEW_REQUIRED = ("review_code", "severity", "reason", "source_refs") + REVIEW_ALLOWED = REVIEW_REQUIRED + ("domain_ids", "unresolved_type", + "blocks_final_drafting") + SCREENING_REQUIRED = ("schema_version", "status", "registry_version", + "registry_index_sha256", "source_document_refs", + "candidates", "unmatched_issue_refs", "review_items", + "screening_policy", "contract_guards") + + # 01 이 쓰면 안 되는 필드. 하나라도 있으면 초안이 계약을 벗어난 것이다. + FORBIDDEN_DRAFT_FIELDS = ("track_hypothesis", "domain_hypotheses", + "relief_mode_hints", "computation_hints", + "matched_cues", "notes_kr") + NONJUDGMENT_FIELDS = ("schema_version", "registry_version", + "registry_index_sha256", "source_document_refs", + "screening_policy", "contract_guards") + + GANADA = "가나다라마바사아자차카타파하" + SECTION_MARKERS = (("상담내용", "FACT"), + ("사건관계인의주장", "OPP"), + ("의뢰인의희망사항", "WISH")) + + ERRORS = [] + WARNINGS = [] + ADDED_REVIEWS = [] + + + def fail(code, message): + ERRORS.append({"code": code, "message": message}) + + + def warn(code, message): + WARNINGS.append({"code": code, "message": message}) + + + # -------------------------------------------------------------------------- + # 1) source unit 독립 재산출 + # Task_A0_domain_screener_01 의 와 같은 규칙을 + # 코드로 다시 구현한다. LLM 의 채번을 신뢰하지 않고 대조하기 위한 것이다. + # -------------------------------------------------------------------------- + def mint_source_units(meeting_text): + lines = unicodedata.normalize("NFC", meeting_text).split("\n") + section = None + cluster = 0 + units = [] + meta_seen = False + raw_seq = 0 + for line in lines: + t = line.strip() + if not t: + continue + squashed = re.sub(r"\s+", "", t) + if "【" in t and "】" in t: + hit = None + for needle, code in SECTION_MARKERS: + if needle in squashed: + hit = code + break + if hit: + section = hit + cluster = 0 + continue + if section is None: + # 상담일지 머리표는 문단마다 자르지 않고 MTG.META.01 한 단위로 접는다. + if set(t) <= set("| -"): + continue + if not meta_seen: + units.append("MTG.META.01") + meta_seen = True + continue + m = re.match(r"^(\d{1,2})\.\s", t) + if m: + cluster = int(m.group(1)) + continue + m2 = re.match(r"^([" + GANADA + r"])\.\s", t) + if m2: + item = GANADA.index(m2.group(1)) + 1 + else: + item = 0 + unit_id = "MTG.%s.%02d.%02d" % (section, cluster, item) + if unit_id in units: + raw_seq += 1 + unit_id = "MTG.RAW.%03d" % raw_seq + units.append(unit_id) + return units, raw_seq + + + # -------------------------------------------------------------------------- + # 2) 단어 사전 파싱 + # 도메인 화이트리스트, 도메인별 계산 허용목록, 충돌 검토코드, 상시활성 목록, + # 그리고 사전이 어느 registry 스냅숏에서 나왔는지를 뽑는다. + # -------------------------------------------------------------------------- + def parse_digest(md): + text = unicodedata.normalize("NFC", md) + info = {"registry_version": None, "registry_index_sha256": None, + "domains": {}, "always_on": [], "review_codes": set()} + m = re.search(r"^registry_version:\s*`([^`]+)`", text, re.M) + if m: + info["registry_version"] = m.group(1).strip() + m = re.search(r"^registry_index:.*sha256=`([a-f0-9]{64})`", text, re.M) + if m: + info["registry_index_sha256"] = m.group(1) + current = None + for line in text.split("\n"): + t = line.rstrip() + if t.startswith("### "): + parts = [x.strip() for x in t[4:].split("|")] + if len(parts) < 6: + continue + did = parts[0] + kv = {} + for seg in parts[2:]: + if "=" in seg: + k, v = seg.split("=", 1) + kv[k.strip()] = v.strip() + calc = [] if kv.get("calc", "-") == "-" else kv["calc"].split(",") + dep = [] if kv.get("dep", "-") == "-" else kv["dep"].split(",") + info["domains"][did] = {"calc": calc, "dep": dep, + "kind": kv.get("kind"), + "ao": kv.get("ao") == "1"} + if kv.get("ao") == "1": + info["always_on"].append(did) + current = did + elif t.startswith("C|") and current: + fields = t.split("|") + if len(fields) >= 4: + info["review_codes"].add(fields[3].strip()) + return info + + + # -------------------------------------------------------------------------- + # 3) 최종 산출물 자기검증 — 닫힌 스키마의 형태를 코드로 다시 확인한다. + # -------------------------------------------------------------------------- + def self_check(doc): + problems = [] + if list(doc.keys()) != ["domain_screening"]: + problems.append("root key must be exactly domain_screening") + return problems + ds = doc["domain_screening"] + missing = [k for k in SCREENING_REQUIRED if k not in ds] + extra = [k for k in ds if k not in SCREENING_REQUIRED] + if missing: + problems.append("missing required: %s" % ",".join(missing)) + if extra: + problems.append("additionalProperties: %s" % ",".join(extra)) + if ds.get("schema_version") != SCHEMA_VERSION: + problems.append("schema_version const mismatch") + if ds.get("status") not in STATUS_RANK: + problems.append("status enum invalid") + if not REG_VER_RE.match(str(ds.get("registry_version", ""))): + problems.append("registry_version pattern invalid") + if not SHA_RE.match(str(ds.get("registry_index_sha256", ""))): + problems.append("registry_index_sha256 pattern invalid") + for key in ("source_document_refs", "unmatched_issue_refs"): + arr = ds.get(key, []) + if len(set(arr)) != len(arr): + problems.append("%s not unique" % key) + for v in arr: + if not REF_RE.match(v): + problems.append("%s ref pattern invalid: %s" % (key, v)) + for c in ds.get("candidates", []): + for k in CANDIDATE_REQUIRED: + if k not in c: + problems.append("candidate missing %s" % k) + for k in c: + if k not in CANDIDATE_ALLOWED: + problems.append("candidate extra key %s" % k) + if c.get("final_determination_forbidden") is not True: + problems.append("final_determination_forbidden must be true") + for r in ds.get("review_items", []): + for k in REVIEW_REQUIRED: + if k not in r: + problems.append("review_item missing %s" % k) + for k in r: + if k not in REVIEW_ALLOWED: + problems.append("review_item extra key %s" % k) + if r.get("severity") not in SEVERITY: + problems.append("review_item severity invalid") + if not CODE_RE.match(str(r.get("review_code", ""))): + problems.append("review_code pattern invalid") + reason = r.get("reason", "") + if not (1 <= len(reason) <= 1000): + problems.append("review_item reason length invalid") + if ds.get("screening_policy") != SCREENING_POLICY: + problems.append("screening_policy const mismatch") + if ds.get("contract_guards") != CONTRACT_GUARDS: + problems.append("contract_guards const mismatch") + return problems + + + # -------------------------------------------------------------------------- + # main + # -------------------------------------------------------------------------- + def main(): + _init() + + # ---- 입력 4종 ---- + try: + draft_doc = read_json(DRAFT_PATH) + except Exception as exc: + fail("DRAFT_UNREADABLE", "%s: %s" % (DRAFT_PATH, exc)) + return None + try: + meeting_raw = read_raw(MEETING_PATH) + except Exception as exc: + fail("MEETING_UNREADABLE", "%s: %s" % (MEETING_PATH, exc)) + return None + try: + registry_raw = read_raw(REGISTRY_INDEX_PATH) + except Exception as exc: + fail("REGISTRY_INDEX_UNREADABLE", "%s: %s" % (REGISTRY_INDEX_PATH, exc)) + return None + try: + digest_raw = read_raw(DIGEST_PATH) + except Exception as exc: + fail("DIGEST_UNREADABLE", "%s: %s" % (DIGEST_PATH, exc)) + return None + + if not isinstance(draft_doc, dict) or "domain_screening_draft" not in draft_doc: + fail("DRAFT_ROOT_KEY_INVALID", "root key domain_screening_draft not found") + return None + draft = draft_doc["domain_screening_draft"] + + for k in FORBIDDEN_DRAFT_FIELDS: + if k in draft: + fail("FORBIDDEN_FIELD_PRESENT", "draft contains forbidden field %s" % k) + for k in NONJUDGMENT_FIELDS: + if k in draft: + fail("NONJUDGMENT_FIELD_IN_DRAFT", + "draft must not carry non-judgment field %s" % k) + + # ---- registry 원문 해시. 재직렬화하지 않은 원문 바이트로 계산한다. ---- + registry_index_sha256 = hashlib.sha256(registry_raw.encode("utf-8")).hexdigest() + try: + registry_doc = json.loads(registry_raw) + registry = registry_doc["domain_registry_index"] + except Exception as exc: + fail("REGISTRY_INDEX_UNREADABLE", "parse failed: %s" % exc) + return None + registry_version = registry.get("registry_version") + registry_domain_ids = sorted(e["domain_id"] for e in registry.get("entries", [])) + + # ---- 단어 사전 ---- + digest = parse_digest(digest_raw) + if len(digest["domains"]) != len(registry_domain_ids): + fail("DIGEST_MALFORMED", + "digest domains=%d registry entries=%d" + % (len(digest["domains"]), len(registry_domain_ids))) + return None + unknown_in_digest = sorted(set(digest["domains"]) - set(registry_domain_ids)) + if unknown_in_digest: + fail("DIGEST_DOMAIN_SET_MISMATCH", + "digest has domains absent from registry: %s" % ",".join(unknown_in_digest)) + return None + # 사전 머리말은 있으면 낡음 감지에 쓰고, 없으면 경고만 남긴다. + # registry_version 과 registry_index_sha256 의 정본은 _registry_index.json 이지 + # 사전이 아니다. 사전 머리말이 편집되어 사라져도 산출물은 정확해야 한다. + if digest["registry_index_sha256"] is None: + warn("DIGEST_HEADER_ABSENT", + "activation_cue_digest.md has no registry_index sha256 header; " + "staleness cross-check skipped") + elif digest["registry_index_sha256"] != registry_index_sha256: + # 사전이 만들어진 뒤 registry 가 바뀌었거나, 읽는 과정에서 원문이 변형된 것이다. + # 사전이 낡은 단서로 판단한 초안을 봉인하면 안 되므로 여기서 멈춘다. + fail("REGISTRY_INDEX_SHA_MISMATCH", + "digest=%s computed=%s" % (digest["registry_index_sha256"], + registry_index_sha256)) + return None + if digest["registry_version"] is None: + warn("DIGEST_HEADER_ABSENT", + "activation_cue_digest.md has no registry_version header") + elif digest["registry_version"] != registry_version: + fail("REGISTRY_VERSION_MISMATCH", + "digest=%s registry=%s" % (digest["registry_version"], registry_version)) + return None + + # ---- source unit 독립 재산출 ---- + universe, raw_fallback = mint_source_units(meeting_raw) + if raw_fallback: + warn("SCREENING_SOURCE_UNIT_FALLBACK", + "%d unit(s) fell back to MTG.RAW.* numbering" % raw_fallback) + if not universe: + fail("SOURCE_UNIT_SET_EMPTY", "no source unit minted from %s" % MEETING_PATH) + return None + universe_set = set(universe) + if len(universe_set) != len(universe): + fail("SOURCE_UNIT_DUPLICATE", "duplicate unit id after minting") + return None + for u in universe: + if not REF_RE.match(u): + fail("REF_PATTERN_INVALID", "minted unit id invalid: %s" % u) + source_document_refs = sorted(universe_set) + + # 초안이 스스로 적어둔 목록과 대조한다. 어긋나면 재산출본을 정본으로 삼고 검토를 남긴다. + draft_units = [] + for row in draft.get("source_unit_index", []) or []: + if isinstance(row, dict) and row.get("unit_id"): + draft_units.append(row["unit_id"]) + if draft_units and set(draft_units) != universe_set: + only_draft = sorted(set(draft_units) - universe_set) + only_mint = sorted(universe_set - set(draft_units)) + ADDED_REVIEWS.append({ + "review_code": "E00_MEMBERSHIP_CONFLICT_REVIEW", + "severity": "review", + "reason": ("초안의 source_unit_index 와 재산출한 원천 단위 집합이 다르다. " + "재산출본을 정본으로 삼았다. 초안에만 있음=%s, 재산출본에만 있음=%s" + % (",".join(only_draft) or "-", ",".join(only_mint) or "-"))[:1000], + "source_refs": sorted(set(only_mint))[:64], + "domain_ids": ["E-00"], + "unresolved_type": "source_unit_index_divergence", + "blocks_final_drafting": False, + }) + + # ---- 후보 검증 ---- + candidates = draft.get("candidates") + if not isinstance(candidates, list): + fail("DRAFT_FIELD_MISSING", "candidates must be a list") + return None + seen_domains = set() + cited = set() + clean_candidates = [] + for c in candidates: + if not isinstance(c, dict): + fail("CANDIDATE_KEY_INVALID", "candidate is not an object") + continue + did = c.get("domain_id") + for k in CANDIDATE_REQUIRED: + if k not in c: + fail("CANDIDATE_KEY_INVALID", "%s missing %s" % (did, k)) + for k in c: + if k not in CANDIDATE_ALLOWED: + fail("CANDIDATE_KEY_INVALID", "%s extra key %s" % (did, k)) + if not DOMAIN_RE.match(str(did)) or did not in digest["domains"]: + fail("DOMAIN_ID_UNKNOWN", "unknown domain_id: %r" % did) + continue + if did in seen_domains: + fail("DOMAIN_ID_DUPLICATE", "duplicate domain_id: %s" % did) + continue + seen_domains.add(did) + if c.get("provisional_status") not in PROVISIONAL_STATUS: + fail("ENUM_INVALID", "%s provisional_status=%r" % (did, c.get("provisional_status"))) + if c.get("confidence") not in CONFIDENCE: + fail("ENUM_INVALID", "%s confidence=%r" % (did, c.get("confidence"))) + summary = c.get("reasoning_summary", "") + if not isinstance(summary, str) or not (1 <= len(summary) <= 1200): + fail("REASONING_SUMMARY_LENGTH", "%s length=%d" % (did, len(str(summary)))) + if c.get("final_determination_forbidden") is not True: + fail("FINAL_DETERMINATION_FLAG_INVALID", "%s" % did) + for key in ("positive_refs", "negative_refs", "conflict_refs"): + arr = c.get(key) or [] + if not isinstance(arr, list): + fail("CANDIDATE_KEY_INVALID", "%s %s must be a list" % (did, key)) + continue + for ref in arr: + if not REF_RE.match(str(ref)): + fail("REF_PATTERN_INVALID", "%s %s %r" % (did, key, ref)) + elif ref not in universe_set: + # source_membership_required 위반. 조용히 지우지 않고 실패로 처리한다. + fail("REF_NOT_IN_SOURCE_UNIVERSE", "%s %s %s" % (did, key, ref)) + else: + cited.add(ref) + allowed_calc = set(digest["domains"][did]["calc"]) + calc = c.get("requested_calculation_domains") or [] + if not isinstance(calc, list): + fail("CANDIDATE_KEY_INVALID", "%s requested_calculation_domains must be a list" % did) + calc = [] + for cid in calc: + if not CALC_RE.match(str(cid)): + fail("CALC_PATTERN_INVALID", "%s %r" % (did, cid)) + elif cid not in allowed_calc: + fail("CALC_NOT_IN_BINDINGS", "%s requested %s but calc=%s" + % (did, cid, ",".join(sorted(allowed_calc)) or "-")) + out = {} + for k in CANDIDATE_REQUIRED: + out[k] = c.get(k) + for key in ("positive_refs", "negative_refs", "conflict_refs"): + out[key] = sorted(set(out.get(key) or [])) + if "requested_calculation_domains" in c: + out["requested_calculation_domains"] = sorted(set(calc)) + clean_candidates.append(out) + clean_candidates.sort(key=lambda x: str(x.get("domain_id"))) + + # 상시 활성 4종은 D0 게이트의 보장 대상이다. 여기서 후보를 만들어내지 않고 경고만 남긴다. + missing_ao = [d for d in sorted(digest["always_on"]) if d not in seen_domains] + if missing_ao: + warn("ALWAYS_ON_NOT_IN_DRAFT", + "always_on domains absent from draft candidates: %s" % ",".join(missing_ao)) + + # ---- 검토 항목 검증 ---- + allowed_codes = set(digest["review_codes"]) | { + "UNROUTED_ISSUE_REVIEW", "SCREENING_SOURCE_UNIT_FALLBACK", + "E00_MEMBERSHIP_CONFLICT_REVIEW", "E00_FALSE_UNROUTED_REVIEW", + "E00_CONSERVATION_FAILURE"} + clean_reviews = [] + for r in draft.get("review_items") or []: + if not isinstance(r, dict): + fail("REVIEW_ITEM_KEY_INVALID", "review_item is not an object") + continue + for k in REVIEW_REQUIRED: + if k not in r: + fail("REVIEW_ITEM_KEY_INVALID", "missing %s" % k) + for k in r: + if k not in REVIEW_ALLOWED: + fail("REVIEW_ITEM_KEY_INVALID", "extra key %s" % k) + code = str(r.get("review_code", "")) + if not CODE_RE.match(code): + fail("REVIEW_CODE_PATTERN_INVALID", code) + elif code not in allowed_codes: + fail("REVIEW_CODE_UNKNOWN", code) + if r.get("severity") not in SEVERITY: + fail("ENUM_INVALID", "review severity=%r" % r.get("severity")) + for ref in r.get("source_refs") or []: + if ref not in universe_set: + fail("REF_NOT_IN_SOURCE_UNIVERSE", "review_items %s" % ref) + for did in r.get("domain_ids") or []: + if not DOMAIN_RE.match(str(did)): + fail("DOMAIN_ID_UNKNOWN", "review_items %r" % did) + item = {} + for k in REVIEW_ALLOWED: + if k in r: + item[k] = r[k] + item["source_refs"] = sorted(set(item.get("source_refs") or [])) + clean_reviews.append(item) + + # ---- 보존 등식. 초안의 미분류를 신뢰하지 않고 다시 계산한다. ---- + computed_unmatched = sorted(universe_set - cited) + draft_unmatched = sorted(set(draft.get("unmatched_issue_refs") or [])) + if draft_unmatched != computed_unmatched: + only_draft = sorted(set(draft_unmatched) - set(computed_unmatched)) + only_calc = sorted(set(computed_unmatched) - set(draft_unmatched)) + ADDED_REVIEWS.append({ + "review_code": "E00_FALSE_UNROUTED_REVIEW", + "severity": "review", + "reason": ("초안의 unmatched_issue_refs 가 재계산 결과와 다르다. 재계산본으로 대체했다. " + "초안에만 있음=%s, 재계산본에만 있음=%s" + % (",".join(only_draft) or "-", ",".join(only_calc) or "-"))[:1000], + "source_refs": (only_draft + only_calc)[:64], + "domain_ids": ["E-00"], + "unresolved_type": "unmatched_set_divergence", + "blocks_final_drafting": False, + }) + unmatched = computed_unmatched + if computed_unmatched and not any( + r.get("review_code") == "UNROUTED_ISSUE_REVIEW" for r in clean_reviews): + ADDED_REVIEWS.append({ + "review_code": "UNROUTED_ISSUE_REVIEW", + "severity": "review", + "reason": "어느 도메인 단서에도 걸리지 않은 상담록 단위를 잔여로 보존한다.", + "source_refs": computed_unmatched[:64], + "domain_ids": ["E-00"], + "unresolved_type": "unrouted_meeting_unit", + "blocks_final_drafting": True, + }) + clean_reviews.extend(ADDED_REVIEWS) + + if len(universe_set) != len(cited) + len(unmatched): + fail("CONSERVATION_FAILED", + "universe=%d cited=%d unmatched=%d" + % (len(universe_set), len(cited), len(unmatched))) + + # ---- 상태. 올릴 수는 있어도 내리지 않는다. ---- + draft_status = draft.get("status") + if draft_status not in STATUS_RANK: + fail("ENUM_INVALID", "draft status=%r" % draft_status) + draft_status = "READY_WITH_REVIEW" + status = draft_status + if clean_reviews and STATUS_RANK[status] < STATUS_RANK["READY_WITH_REVIEW"]: + status = "READY_WITH_REVIEW" + + if ERRORS: + return None + + # ---- 비판단 6종을 붙여 조립한다. 키 순서는 스키마의 required 순서를 따른다. ---- + screening = { + "schema_version": SCHEMA_VERSION, + "status": status, + "registry_version": registry_version, + "registry_index_sha256": registry_index_sha256, + "source_document_refs": source_document_refs, + "candidates": clean_candidates, + "unmatched_issue_refs": unmatched, + "review_items": clean_reviews, + "screening_policy": dict(SCREENING_POLICY), + "contract_guards": dict(CONTRACT_GUARDS), + } + doc = {"domain_screening": screening} + + problems = self_check(doc) + if problems: + for p in problems: + fail("OUTPUT_SCHEMA_SELF_CHECK_FAILED", p) + return None + + body = json.dumps(doc, ensure_ascii=False, indent=2) + "\n" + write_doc(OUTPUT_PATH, body) + try: + _call("list_docs", {"path": "routing", "pattern": "domain_screening.json"}, + next_msg_id()) + except Exception as exc: + warn("OUTPUT_LIST_CHECK_SKIPPED", str(exc)) + + return { + "screening_sha256": hashlib.sha256(body.encode("utf-8")).hexdigest(), + "status": status, + "source_unit_count": len(universe_set), + "cited_unit_count": len(cited), + "unmatched_unit_count": len(unmatched), + "candidate_count": len(clean_candidates), + "review_item_count": len(clean_reviews), + "review_items_added_by_02": [r["review_code"] for r in ADDED_REVIEWS], + "registry_version": registry_version, + "registry_index_sha256": registry_index_sha256, + } + + + try: + RESULT = main() + except Exception as exc: + fail("UNHANDLED_EXCEPTION", "%s: %s" % (type(exc).__name__, exc)) + RESULT = None + + if RESULT is None: + print(json.dumps({"status": "FAILED", "written": False, + "output_path": OUTPUT_PATH, + "errors": ERRORS, "warnings": WARNINGS}, + ensure_ascii=False)) + else: + payload = {"status": RESULT["status"], "written": True, + "output_path": OUTPUT_PATH, "errors": [], "warnings": WARNINGS} + payload.update(RESULT) + print(json.dumps(payload, ensure_ascii=False)) + - task_name: Task_A0_domain_screener_03 + mcp: code-executor + tool_name: run_code + parameters: + language: python + requirements: "httpx" + network: "agent-network" + # 후보 15개면 도구 호출이 4(고정 읽기)+15(후보 config)+1(쓰기)+1(확인)=21회다. + # 후보가 26개까지 늘어도 여유가 남도록 240초로 둔다. + timeout: 240 + code: | + #!/usr/bin/env python3 + # Task_A0_domain_screener_03 + # routing/domain_screening.json 의 후보 도메인 목록으로 + # Default_Agent/domains/<후보>/domain_config.json 에서 7개 항목만 발췌하여 + # routing/candidate_profile_vocabulary.md 를 기록한다. + # Task_A_client_goal 이 domain_profiles 를 채울 때 쓸 낱말 목록이며, + # 판단은 하지 않는다. registry 원문이 정본이고 이 파일은 파생본이다. + import hashlib + import itertools + import json + import re + import unicodedata + + import httpx + + # -------------------------------------------------------------------------- + # localdocs 보일러플레이트 (SKILL.md 5장 / 5.2장) + # clientInfo 에 {{__user_hash__}} / {{__workspace_hash__}} 를 반드시 넣는다. + # 빠지면 localdocs 가 루트 경로를 보므로 사용자 파일을 찾지 못한다. + # -------------------------------------------------------------------------- + TASK_NAME = "Task_A0_domain_screener_03" + LOCALDOCS_URL = "http://mcp-localdocs:8012/mcp" + MCP_HEADERS = {"Content-Type": "application/json", + "Accept": "application/json, text/event-stream"} + CLIENT = httpx.Client(timeout=60) + MSG_ID_COUNTER = itertools.count(10) + + + def next_msg_id(): + return next(MSG_ID_COUNTER) + + + def _init(): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": TASK_NAME, "version": "1.0", + "user_id": "{{__user_hash__}}", + "workspace_id": "{{__workspace_hash__}}"}} + }, headers=MCP_HEADERS) + r.raise_for_status() + sid = r.headers.get("mcp-session-id") + if sid: + MCP_HEADERS["mcp-session-id"] = sid + CLIENT.post(LOCALDOCS_URL, + json={"jsonrpc": "2.0", "method": "notifications/initialized"}, + headers=MCP_HEADERS).raise_for_status() + + + def _parse_mcp(text): + for line in text.strip().split("\n"): + if line.startswith("data: "): + try: + return json.loads(line[6:]) + except Exception: + return None + try: + return json.loads(text) + except Exception: + return None + + + def _call(name, args, mid): + r = CLIENT.post(LOCALDOCS_URL, json={ + "jsonrpc": "2.0", "id": mid, "method": "tools/call", + "params": {"name": name, "arguments": args} + }, headers=MCP_HEADERS) + r.raise_for_status() + p = _parse_mcp(r.text) + if not p or "result" not in p: + raise RuntimeError("MCP %s failed" % name) + return p + + + def read_raw(name): + # 원문을 재직렬화 없이 그대로 돌려준다. + # domain_config 의 sha256 을 registry 색인과 대조하므로 바이트 보존이 필수다. + p = _call("read_docs", {"doc_names": [name]}, next_msg_id()) + text = (p["result"].get("content") or [{}])[0].get("text", "") + if not text: + raise RuntimeError("Empty response: %s" % name) + try: + outer = json.loads(text) + except Exception: + return text + if isinstance(outer, str): + return outer + if isinstance(outer, dict) and "results" in outer: + r0 = (outer.get("results") or [{}])[0] + inner = r0.get("content") + if inner is None: + inner = r0.get("text") + if not isinstance(inner, str) or not inner: + raise RuntimeError("Empty content: %s" % name) + return inner + raise RuntimeError("Unexpected read_docs envelope: %s" % name) + + + def read_json(name): + raw = read_raw(name) + s = raw.strip() + if s.startswith("```"): + for part in s.split("```"): + part = part.strip() + if part.startswith("json"): + part = part[4:].strip() + if part.startswith("{") or part.startswith("["): + s = part + break + try: + return json.loads(s) + except json.JSONDecodeError: + obj, _ = json.JSONDecoder().raw_decode(s) + return obj + + + def write_doc(path, content): + _call("write_file", {"path": path, "content": content, "overwrite": True}, + next_msg_id()) + + + # -------------------------------------------------------------------------- + # 경로와 상수 + # -------------------------------------------------------------------------- + SCREENING_PATH = "routing/domain_screening.json" + REGISTRY_INDEX_PATH = "Default_Agent/domains/_registry_index.json" + DOMAIN_CATALOG_PATH = "Default_Agent/platform/reference_catalogs/domain_ids.json" + CALC_CATALOG_PATH = "Default_Agent/platform/reference_catalogs/calculation_ids.json" + CONFIG_PATH_FMT = "Default_Agent/domains/%s/domain_config.json" + OUTPUT_PATH = "routing/candidate_profile_vocabulary.md" + + DIGEST_SCHEMA = "candidate_profile_vocabulary.v1" + + # Task_A 프롬프트의 잔여 예산. §2.2 로 고정 4-profile 블록(약 9,000 B)이 + # 삭제되는 것을 반영한 값이다. 초과하면 라벨을 단계적으로 줄인다. + MAX_OUTPUT_BYTES = 28000 + # 라벨 길이 사다리. 앞에서부터 시도하고 예산에 맞는 첫 단계를 쓴다. + LABEL_TIERS = [("full", None), ("60", 60), ("40", 40), ("24", 24), ("none", 0)] + + DOMAIN_RE = re.compile(r"^(?:(?:EC|E)-[A-Z0-9]{2,8}|X[A-Z0-9]{1,8})$") + CALC_RE = re.compile(r"^CE-[A-Z0-9][A-Z0-9-]{0,15}$") + REF_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_.:/-]{0,255}$") + + ERRORS = [] + WARNINGS = [] + + + def fail(code, message): + ERRORS.append({"code": code, "message": message}) + + + def warn(code, message): + WARNINGS.append({"code": code, "message": message}) + + + def cut(text, limit): + # 라벨 축약. 파이프는 구분자이므로 슬래시로 치환한다. + if text is None: + return "-" + t = unicodedata.normalize("NFC", str(text)).replace("\n", " ").replace("|", "/").strip() + if not t: + return "-" + if limit is None: + return t + if limit == 0: + return "" + return t if len(t) <= limit else t[:limit] + + + def render(rows, refs, meta, limit): + # rows: [(domain_id, cfg)] 순서 고정. limit 은 라벨 길이 상한. + L = [] + a = L.append + a("# CANDIDATE_PROFILE_VOCABULARY") + a("") + a("digest_schema: `%s`" % DIGEST_SCHEMA) + a("purpose: `client_goal_domain_profiles.schema.json` 을 채울 때 쓰는 낱말 목록이다. " + "사실 원천이 아니며 registry 원문의 파생본이다.") + a("source: `Default_Agent/domains//domain_config.json` 에서 7개 항목만 발췌 " + "(label_ko·kind, element_slots, opposing_fact_slots, evidence_components, " + "defense_map, calculation_bindings, review_codes)") + a("registry_version: `%s`" % meta["registry_version"]) + a("registry_index_sha256: `%s`" % meta["registry_index_sha256"]) + a("screening_sha256: `%s`" % meta["screening_sha256"]) + a("candidate_count: %d" % len(rows)) + a("label_tier: `%s`" % meta["label_tier"]) + a("") + a("## LEGEND") + a("") + a("도메인 머리: `### ||kind=|calc=`") + a("- `E||||