|
|
@@ -0,0 +1,702 @@
|
|
|
+"""Four-agent, evidence-first ontology construction and publication workflow."""
|
|
|
+from __future__ import annotations
|
|
|
+
|
|
|
+import hashlib
|
|
|
+import json
|
|
|
+import re
|
|
|
+import time
|
|
|
+from typing import Any, Iterable, Optional
|
|
|
+
|
|
|
+from lambdagent import Context, Guard, Term, Tool
|
|
|
+
|
|
|
+from .agents import analyze_controls, discover_assets, infer_semantics, normalize_source, synthesize
|
|
|
+from .db import gen_id, now_utc
|
|
|
+from .decision import collect_project_context, evaluate_retirement_gate
|
|
|
+from .llm import LLMSettings, LongCatSemanticAgent, PROMPT_VERSION, get_llm_settings, resolve_semantic_mode
|
|
|
+from .ontology_catalog import CATALOG_GENERATOR, assemble_catalog
|
|
|
+from .paas import record_agent_run
|
|
|
+from .service import (
|
|
|
+ GovernanceError, create_assertion, create_evidence, graph, require_project,
|
|
|
+ row, rows, upsert_element, upsert_rule, validate_project,
|
|
|
+)
|
|
|
+
|
|
|
+
|
|
|
+BUILD_STATUSES = ("running", "review_required", "published", "failed")
|
|
|
+ALLOWED_BUILD_PREDICATES = {
|
|
|
+ "INSTANCE_OF", "CONTAINS", "REPRESENTS", "BELONGS_TO", "EXPOSES", "OPERATES_ON",
|
|
|
+ "READS", "WRITES", "USES", "MIRRORS_TO", "OWNED_BY", "GOVERNED_BY", "VALIDATES",
|
|
|
+ "REALIZED_BY", "CLASSIFIED_AS", "REQUIRES_APPROVAL_FROM", "EVALUATES",
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+def _dump(value: Any) -> str:
|
|
|
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
|
|
|
+
|
|
|
+
|
|
|
+def _loads(value: Any, default: Any) -> Any:
|
|
|
+ if isinstance(value, (dict, list)):
|
|
|
+ return value
|
|
|
+ try:
|
|
|
+ return json.loads(value) if value not in (None, "") else default
|
|
|
+ except (TypeError, ValueError):
|
|
|
+ return default
|
|
|
+
|
|
|
+
|
|
|
+def _build_row(value: Optional[dict]) -> Optional[dict]:
|
|
|
+ if value is None:
|
|
|
+ return None
|
|
|
+ result = dict(value)
|
|
|
+ for field, default in (
|
|
|
+ ("source_manifest", []), ("evidence_ids", []), ("element_ids", []),
|
|
|
+ ("assertion_ids", []), ("candidate_rules", []), ("diff_json", {}),
|
|
|
+ ("validation_json", {}), ("trace_json", []), ("llm_json", {}), ("paas_runs", []),
|
|
|
+ ):
|
|
|
+ result[field] = _loads(result.get(field), default)
|
|
|
+ return result
|
|
|
+
|
|
|
+
|
|
|
+def _merge_parsed(sources: list[dict]) -> dict:
|
|
|
+ keys = ("tables", "apis", "schemas", "assets", "relationships", "evidence", "rules")
|
|
|
+ return {key: [item for source in sources for item in (source["parsed"].get(key) or [])] for key in keys}
|
|
|
+
|
|
|
+
|
|
|
+def _safe_context_value(value: Any) -> Any:
|
|
|
+ """Bound and redact user-provided context before it can reach a model or PaaS."""
|
|
|
+ if isinstance(value, dict):
|
|
|
+ return {
|
|
|
+ str(key): "[REDACTED]" if any(
|
|
|
+ token in str(key).lower()
|
|
|
+ for token in ("secret", "password", "token", "api_key", "apikey", "authorization", "credential")
|
|
|
+ ) else _safe_context_value(item)
|
|
|
+ for key, item in list(value.items())[:100]
|
|
|
+ }
|
|
|
+ if isinstance(value, list):
|
|
|
+ return [_safe_context_value(item) for item in value[:100]]
|
|
|
+ if isinstance(value, str):
|
|
|
+ text = value[:1200]
|
|
|
+ text = re.sub(r"\bak_[A-Za-z0-9_-]{12,}\b", "[REDACTED_API_KEY]", text)
|
|
|
+ return re.sub(r"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]{12,}", "Bearer [REDACTED]", text)
|
|
|
+ return value
|
|
|
+
|
|
|
+
|
|
|
+def _semantic_project_context(project_context: dict, parsed: dict) -> dict:
|
|
|
+ result = dict(project_context)
|
|
|
+ result["uploaded_evidence"] = [_safe_context_value({
|
|
|
+ "kind": item.get("kind", ""),
|
|
|
+ "title": item.get("title", ""),
|
|
|
+ "source": item.get("source", ""),
|
|
|
+ "content": item.get("content", ""),
|
|
|
+ "metadata": item.get("metadata") or {},
|
|
|
+ }) for item in parsed.get("evidence") or [] if isinstance(item, dict)]
|
|
|
+ result["uploaded_rules"] = [_safe_context_value(item) for item in parsed.get("rules") or [] if isinstance(item, dict)]
|
|
|
+ result["uploaded_relationships"] = [
|
|
|
+ _safe_context_value(item) for item in parsed.get("relationships") or [] if isinstance(item, dict)
|
|
|
+ ]
|
|
|
+ result["uploaded_scope"] = {
|
|
|
+ "evidence": len(result["uploaded_evidence"]),
|
|
|
+ "rules": len(result["uploaded_rules"]),
|
|
|
+ "relationships": len(result["uploaded_relationships"]),
|
|
|
+ }
|
|
|
+ return result
|
|
|
+
|
|
|
+
|
|
|
+def _merge_synthesized(branches: Iterable[dict]) -> dict:
|
|
|
+ """Merge already-synthesized agent results without losing provenance or LLM metadata."""
|
|
|
+ elements: dict[str, dict] = {}
|
|
|
+ assertions: dict[tuple[str, str, str], dict] = {}
|
|
|
+ issues: dict[tuple[str, str], dict] = {}
|
|
|
+ agents: list[str] = []
|
|
|
+ llm: dict = {}
|
|
|
+ for branch in branches:
|
|
|
+ agents.extend(str(item) for item in branch.get("agents") or ([branch["agent"]] if branch.get("agent") else []))
|
|
|
+ elements.update({item["local_id"]: item for item in branch.get("elements") or []})
|
|
|
+ assertions.update({
|
|
|
+ (item["subject"], item["predicate"], item["object"]): item
|
|
|
+ for item in branch.get("assertions") or []
|
|
|
+ })
|
|
|
+ issues.update({
|
|
|
+ (item["code"], item.get("target") or ""): item
|
|
|
+ for item in branch.get("issues") or []
|
|
|
+ })
|
|
|
+ if branch.get("llm"):
|
|
|
+ llm = branch["llm"]
|
|
|
+ return {
|
|
|
+ "agents": list(dict.fromkeys(agents)),
|
|
|
+ "elements": list(elements.values()),
|
|
|
+ "assertions": list(assertions.values()),
|
|
|
+ "issues": list(issues.values()),
|
|
|
+ "summary": {
|
|
|
+ "elements": len(elements),
|
|
|
+ "assertions": len(assertions),
|
|
|
+ "issues": len(issues),
|
|
|
+ },
|
|
|
+ "llm": llm,
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+def _asset_construction(bundle: dict) -> dict:
|
|
|
+ normalized = [normalize_source(source) for source in bundle["sources"]]
|
|
|
+ branches = []
|
|
|
+ for source in normalized:
|
|
|
+ discovered = discover_assets(source)
|
|
|
+ for element in discovered.get("elements") or []:
|
|
|
+ element.setdefault("source", source["source_name"])
|
|
|
+ branches.extend((discovered, analyze_controls(source)))
|
|
|
+ parsed = _merge_parsed(normalized)
|
|
|
+ combined_source = {
|
|
|
+ "source_type": "inventory",
|
|
|
+ "source_name": "+".join(source["source_name"] for source in normalized)[:256],
|
|
|
+ "environment": bundle.get("environment") or "development",
|
|
|
+ "instruction": bundle.get("instruction") or "",
|
|
|
+ "content": "\n".join(source["content"] for source in normalized),
|
|
|
+ "parsed": parsed,
|
|
|
+ "project_context": _semantic_project_context(bundle.get("project_context") or {}, parsed),
|
|
|
+ }
|
|
|
+ return {
|
|
|
+ **bundle,
|
|
|
+ "normalized_sources": normalized,
|
|
|
+ "combined_source": combined_source,
|
|
|
+ "structure": synthesize(tuple(branches)),
|
|
|
+ "candidate_rules": combined_source["parsed"]["rules"],
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+def _identity_assertions(elements: Iterable[dict]) -> list[dict]:
|
|
|
+ table_columns: dict[str, list[str]] = {}
|
|
|
+ schema_fields: dict[str, list[str]] = {}
|
|
|
+ for item in elements:
|
|
|
+ local_id = str(item.get("local_id") or "")
|
|
|
+ if item.get("layer") != "M1" or item.get("kind") != "Column":
|
|
|
+ continue
|
|
|
+ leaf = local_id.rsplit(":", 1)[-1].lower()
|
|
|
+ if local_id.startswith("m1:column:"):
|
|
|
+ table_columns.setdefault(leaf, []).append(local_id)
|
|
|
+ elif local_id.startswith("m1:schema-field:"):
|
|
|
+ schema_fields.setdefault(leaf, []).append(local_id)
|
|
|
+ result = []
|
|
|
+ for leaf in sorted(set(table_columns) & set(schema_fields)):
|
|
|
+ if len(table_columns[leaf]) != 1 or len(schema_fields[leaf]) != 1:
|
|
|
+ continue
|
|
|
+ result.append({
|
|
|
+ "subject": schema_fields[leaf][0], "predicate": "REPRESENTS", "object": table_columns[leaf][0],
|
|
|
+ "assertion_type": "inferred", "confidence": .78, "review_status": "pending",
|
|
|
+ "reason": f"OpenAPI 字段与数据库字段共享规范化名称 {leaf}",
|
|
|
+ "generated_by": "lambdagent:semantic-fusion@identity-v1",
|
|
|
+ })
|
|
|
+ return result
|
|
|
+
|
|
|
+
|
|
|
+class SemanticFusionAgent(Term):
|
|
|
+ def __init__(self, semantic_mode: str, settings: LLMSettings):
|
|
|
+ super().__init__("semantic-fusion-agent")
|
|
|
+ self.semantic_mode = semantic_mode
|
|
|
+ self.settings = settings
|
|
|
+ self.model_agent = LongCatSemanticAgent(settings) if semantic_mode == "llm" else None
|
|
|
+
|
|
|
+ def apply(self, state: dict, ctx: Optional[Context] = None) -> dict:
|
|
|
+ context = ctx or Context()
|
|
|
+ started = time.perf_counter()
|
|
|
+ semantic = (
|
|
|
+ self.model_agent.apply(state["combined_source"], context)
|
|
|
+ if self.model_agent else infer_semantics(state["combined_source"])
|
|
|
+ )
|
|
|
+ identity = {
|
|
|
+ "agent": "identity-resolution",
|
|
|
+ "elements": [],
|
|
|
+ "assertions": _identity_assertions(state["structure"]["elements"]),
|
|
|
+ "issues": [],
|
|
|
+ }
|
|
|
+ state = {**state, "semantic": synthesize((semantic, identity))}
|
|
|
+ context.log(self._name, self._trace_id, {"stage": "semantic-fusion"}, {
|
|
|
+ "elements": len(state["semantic"]["elements"]),
|
|
|
+ "assertions": len(state["semantic"]["assertions"]),
|
|
|
+ }, (time.perf_counter() - started) * 1000, model=self.settings.model if self.model_agent else "")
|
|
|
+ return state
|
|
|
+
|
|
|
+
|
|
|
+def _ontology_validation(state: dict) -> dict:
|
|
|
+ merged = _merge_synthesized((state["structure"], state["semantic"]))
|
|
|
+ catalog_elements, catalog_assertions = assemble_catalog(merged["elements"])
|
|
|
+ merged["elements"].extend(catalog_elements)
|
|
|
+ merged["assertions"].extend(catalog_assertions)
|
|
|
+ merged["summary"] = {
|
|
|
+ "elements": len(merged["elements"]),
|
|
|
+ "assertions": len(merged["assertions"]),
|
|
|
+ "issues": len(merged["issues"]),
|
|
|
+ }
|
|
|
+ ids = {item["local_id"] for item in merged["elements"]}
|
|
|
+ ids.update(
|
|
|
+ item.get("local_id") for item in (state.get("project_context") or {}).get("assets") or []
|
|
|
+ if item.get("local_id")
|
|
|
+ )
|
|
|
+ errors, warnings, valid_assertions = [], [], []
|
|
|
+ seen_uris = set()
|
|
|
+ for item in merged["elements"]:
|
|
|
+ if item["uri"] in seen_uris:
|
|
|
+ errors.append({"code": "DUPLICATE_URI", "message": f"候选本体 URI 重复:{item['uri']}"})
|
|
|
+ seen_uris.add(item["uri"])
|
|
|
+ for item in merged["assertions"]:
|
|
|
+ if item["predicate"] not in ALLOWED_BUILD_PREDICATES:
|
|
|
+ errors.append({"code": "UNSUPPORTED_PREDICATE", "message": f"关系不在白名单:{item['predicate']}"})
|
|
|
+ elif item["subject"] not in ids or item["object"] not in ids:
|
|
|
+ errors.append({"code": "UNRESOLVED_REFERENCE", "message": f"关系端点无法解析:{item['subject']} → {item['object']}"})
|
|
|
+ else:
|
|
|
+ valid_assertions.append(item)
|
|
|
+ if not state["candidate_rules"]:
|
|
|
+ warnings.append({"code": "NO_GOVERNANCE_RULES", "message": "当前文件没有提供治理门禁规则,发布后只能返回证据不足。"})
|
|
|
+
|
|
|
+ existing_uris = set(state.get("existing_uris") or [])
|
|
|
+ element_uris = {item["local_id"]: item["uri"] for item in merged["elements"]}
|
|
|
+ element_uris.update({
|
|
|
+ item["local_id"]: item["uri"]
|
|
|
+ for item in (state.get("project_context") or {}).get("assets") or []
|
|
|
+ if item.get("local_id") and item.get("uri")
|
|
|
+ })
|
|
|
+ existing_relations = {tuple(item) for item in (state.get("existing_relation_uris") or [])}
|
|
|
+ relation_keys = {
|
|
|
+ (element_uris.get(item["subject"], item["subject"]), item["predicate"], element_uris.get(item["object"], item["object"]))
|
|
|
+ for item in valid_assertions
|
|
|
+ }
|
|
|
+ diff = {
|
|
|
+ "new_elements": sum(1 for item in merged["elements"] if item["uri"] not in existing_uris),
|
|
|
+ "matched_elements": sum(1 for item in merged["elements"] if item["uri"] in existing_uris),
|
|
|
+ "new_assertions": sum(1 for key in relation_keys if key not in existing_relations),
|
|
|
+ "matched_assertions": sum(1 for key in relation_keys if key in existing_relations),
|
|
|
+ "candidate_rules": len(state["candidate_rules"]),
|
|
|
+ "preview_elements": [
|
|
|
+ {key: item.get(key) for key in ("local_id", "layer", "profile", "kind", "name", "uri")}
|
|
|
+ for item in merged["elements"][:30]
|
|
|
+ ],
|
|
|
+ "preview_assertions": [
|
|
|
+ {key: item.get(key) for key in ("subject", "predicate", "object", "assertion_type", "confidence", "generated_by")}
|
|
|
+ for item in valid_assertions[:40]
|
|
|
+ ],
|
|
|
+ }
|
|
|
+ merged["assertions"] = valid_assertions
|
|
|
+ return {
|
|
|
+ **state, "result": merged, "diff": diff,
|
|
|
+ "candidate_validation": {"valid": not errors, "errors": errors, "warnings": warnings},
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+def build_ontology_pipeline(semantic_mode: str, settings: LLMSettings):
|
|
|
+ pipeline = (
|
|
|
+ Tool("asset-construction-agent", _asset_construction)
|
|
|
+ >> SemanticFusionAgent(semantic_mode, settings)
|
|
|
+ >> Tool("ontology-validation-agent", _ontology_validation)
|
|
|
+ )
|
|
|
+ def reject_invalid(result: dict) -> dict:
|
|
|
+ validation = result.get("candidate_validation") or {}
|
|
|
+ details = "; ".join(str(item.get("message") or item.get("code")) for item in validation.get("errors") or [])
|
|
|
+ raise GovernanceError(
|
|
|
+ f"候选本体未通过结构校验:{details or '未知校验错误'}",
|
|
|
+ code="INVALID_ONTOLOGY_BUILD",
|
|
|
+ status=422,
|
|
|
+ )
|
|
|
+
|
|
|
+ return Guard(
|
|
|
+ pipeline,
|
|
|
+ validator=lambda result: bool(result.get("candidate_validation", {}).get("valid")),
|
|
|
+ retry=0,
|
|
|
+ on_fail=reject_invalid,
|
|
|
+ )
|
|
|
+
|
|
|
+
|
|
|
+def _source_manifest(sources: list[dict]) -> list[dict]:
|
|
|
+ result = []
|
|
|
+ for source in sources:
|
|
|
+ content = str(source.get("content") or "")
|
|
|
+ result.append({
|
|
|
+ "name": str(source.get("source_name") or "source"),
|
|
|
+ "type": str(source.get("source_type") or ""),
|
|
|
+ "size_bytes": len(content.encode("utf-8")),
|
|
|
+ "sha256": hashlib.sha256(content.encode("utf-8")).hexdigest(),
|
|
|
+ })
|
|
|
+ return result
|
|
|
+
|
|
|
+
|
|
|
+def _trace_duration(trace: list[dict], name: str) -> int:
|
|
|
+ return int(sum(float(item.get("duration_ms") or 0) for item in trace if item.get("term_name") == name))
|
|
|
+
|
|
|
+
|
|
|
+def _audit_trace(context: Context) -> list[dict]:
|
|
|
+ return [{
|
|
|
+ "term_name": item.term_name,
|
|
|
+ "term_id": item.term_id,
|
|
|
+ "duration_ms": item.duration_ms,
|
|
|
+ "model": item.model,
|
|
|
+ "tokens_used": item.tokens_used,
|
|
|
+ } for item in context.trace]
|
|
|
+
|
|
|
+
|
|
|
+def _record_paas_build(build_id: str, project_id: str, result: dict, trace: list[dict]) -> list[dict]:
|
|
|
+ common_input = {"build_id": build_id, "project_id": project_id, "source_count": len(result["normalized_sources"])}
|
|
|
+ return [
|
|
|
+ record_agent_run(
|
|
|
+ "asset-construction-agent", input_summary=common_input,
|
|
|
+ output_summary={"elements": len(result["structure"]["elements"]), "assertions": len(result["structure"]["assertions"])},
|
|
|
+ duration_ms=_trace_duration(trace, "asset-construction-agent"),
|
|
|
+ ),
|
|
|
+ record_agent_run(
|
|
|
+ "semantic-fusion-agent", input_summary=common_input,
|
|
|
+ output_summary={"elements": len(result["semantic"]["elements"]), "assertions": len(result["semantic"]["assertions"])},
|
|
|
+ duration_ms=_trace_duration(trace, "semantic-fusion-agent"),
|
|
|
+ ),
|
|
|
+ record_agent_run(
|
|
|
+ "ontology-validation-agent", input_summary=common_input,
|
|
|
+ output_summary=result["candidate_validation"],
|
|
|
+ duration_ms=_trace_duration(trace, "ontology-validation-agent"),
|
|
|
+ ),
|
|
|
+ ]
|
|
|
+
|
|
|
+
|
|
|
+def run_ontology_build(
|
|
|
+ db,
|
|
|
+ tenant_id: str,
|
|
|
+ project_id: str,
|
|
|
+ sources: list[dict],
|
|
|
+ *,
|
|
|
+ semantic_mode: str = "auto",
|
|
|
+ instruction: str = "",
|
|
|
+ environment: str = "development",
|
|
|
+ decision_target: str = "",
|
|
|
+) -> dict:
|
|
|
+ require_project(db, tenant_id, project_id)
|
|
|
+ if not 1 <= len(sources) <= 12:
|
|
|
+ raise GovernanceError("每次本体构建需要上传 1 到 12 份文件", code="INVALID_BUILD_SOURCE_COUNT")
|
|
|
+ if sum(len(str(item.get("content") or "").encode("utf-8")) for item in sources) > 3 * 1024 * 1024:
|
|
|
+ raise GovernanceError("本次构建文件总量超过 3MB", code="BUILD_TOO_LARGE", status=413)
|
|
|
+
|
|
|
+ settings = get_llm_settings()
|
|
|
+ resolved_mode = resolve_semantic_mode(semantic_mode, settings)
|
|
|
+ build_id, run_id, created_at = gen_id("ob_"), gen_id("gar_"), now_utc()
|
|
|
+ manifest = _source_manifest(sources)
|
|
|
+ input_hash = hashlib.sha256(_dump(manifest).encode("utf-8")).hexdigest()
|
|
|
+ project_context = collect_project_context(db, tenant_id, project_id, target_hint=decision_target)
|
|
|
+ context_json = _dump(project_context)
|
|
|
+ context_hash = hashlib.sha256(context_json.encode("utf-8")).hexdigest()
|
|
|
+ existing = db.fetchall(
|
|
|
+ "SELECT id,uri FROM ontology_elements WHERE tenant_id=? AND project_id=?",
|
|
|
+ (tenant_id, project_id),
|
|
|
+ )
|
|
|
+ id_to_uri = {item["id"]: item["uri"] for item in existing}
|
|
|
+ existing_assertions = db.fetchall(
|
|
|
+ "SELECT subject_id,predicate,object_id FROM governance_assertions WHERE tenant_id=? AND project_id=?",
|
|
|
+ (tenant_id, project_id),
|
|
|
+ )
|
|
|
+ existing_relation_uris = [
|
|
|
+ [id_to_uri[item["subject_id"]], item["predicate"], id_to_uri[item["object_id"]]]
|
|
|
+ for item in existing_assertions
|
|
|
+ if item.get("object_id") in id_to_uri and item.get("subject_id") in id_to_uri
|
|
|
+ ]
|
|
|
+ db.execute(
|
|
|
+ "INSERT INTO ontology_builds "
|
|
|
+ "(id,tenant_id,project_id,run_id,status,semantic_mode,decision_target,source_manifest,source_count,created_at) "
|
|
|
+ "VALUES (?,?,?,?,?,?,?,?,?,?)",
|
|
|
+ (build_id, tenant_id, project_id, run_id, "running", resolved_mode, decision_target,
|
|
|
+ _dump(manifest), len(sources), created_at),
|
|
|
+ )
|
|
|
+ db.execute(
|
|
|
+ "INSERT INTO governance_agent_runs "
|
|
|
+ "(id,tenant_id,project_id,source_type,input_hash,status,semantic_mode,llm_provider,llm_model,prompt_version,"
|
|
|
+ "context_hash,context_scope,created_at) VALUES (?,?,?,?,?,'running',?,?,?,?,?,?,?)",
|
|
|
+ (run_id, tenant_id, project_id, "ontology-build", input_hash, resolved_mode,
|
|
|
+ settings.provider if resolved_mode == "llm" else "", settings.model if resolved_mode == "llm" else "",
|
|
|
+ PROMPT_VERSION if resolved_mode == "llm" else "", context_hash,
|
|
|
+ _dump(project_context.get("scope") or {}), created_at),
|
|
|
+ )
|
|
|
+ db.commit()
|
|
|
+ context = Context(run_id=run_id)
|
|
|
+ try:
|
|
|
+ result = build_ontology_pipeline(resolved_mode, settings).apply({
|
|
|
+ "sources": sources, "environment": environment, "instruction": instruction,
|
|
|
+ "project_context": project_context,
|
|
|
+ "existing_uris": [item["uri"] for item in existing],
|
|
|
+ "existing_relation_uris": existing_relation_uris,
|
|
|
+ }, context)
|
|
|
+ if not result["candidate_validation"]["valid"]:
|
|
|
+ raise GovernanceError("候选本体未通过结构校验", code="INVALID_ONTOLOGY_BUILD")
|
|
|
+
|
|
|
+ evidence_ids = []
|
|
|
+ for source, source_info in zip(result["normalized_sources"], manifest):
|
|
|
+ evidence = create_evidence(db, tenant_id, project_id, {
|
|
|
+ "kind": "SourceArtifact", "uri": f"evidence://source/{source_info['sha256']}",
|
|
|
+ "title": source["source_name"], "content": source["content"], "source": source["source_name"],
|
|
|
+ "metadata": {"build_id": build_id, "source_type": source["source_type"], **source_info},
|
|
|
+ })
|
|
|
+ evidence_ids.append(evidence["id"])
|
|
|
+ for index, item in enumerate(result["combined_source"]["parsed"].get("evidence") or []):
|
|
|
+ if not isinstance(item, dict):
|
|
|
+ continue
|
|
|
+ evidence = create_evidence(db, tenant_id, project_id, {
|
|
|
+ **item,
|
|
|
+ "uri": str(item.get("uri") or f"evidence://ontology-build/{build_id}/fact/{index}"),
|
|
|
+ "title": str(item.get("title") or f"治理事实 {index + 1}"),
|
|
|
+ "metadata": {"build_id": build_id, **dict(item.get("metadata") or {})},
|
|
|
+ })
|
|
|
+ evidence_ids.append(evidence["id"])
|
|
|
+
|
|
|
+ id_map = {
|
|
|
+ item["local_id"]: item["existing_id"] for item in project_context.get("assets") or []
|
|
|
+ if item.get("local_id") and item.get("existing_id")
|
|
|
+ }
|
|
|
+ element_ids = []
|
|
|
+ for item in result["result"]["elements"]:
|
|
|
+ previous = db.fetchone(
|
|
|
+ "SELECT id,status FROM ontology_elements WHERE tenant_id=? AND project_id=? AND uri=?",
|
|
|
+ (tenant_id, project_id, item["uri"]),
|
|
|
+ )
|
|
|
+ saved = upsert_element(db, tenant_id, project_id, {
|
|
|
+ **item,
|
|
|
+ "status": "published" if previous and previous.get("status") == "published" else "candidate",
|
|
|
+ "attributes": {**dict(item.get("attributes") or {}), "build_id": build_id},
|
|
|
+ "source": str(item.get("source") or (
|
|
|
+ f"ontology-build:{build_id}:{'semantic-fusion' if item['local_id'].startswith('llm:') else 'asset-construction'}"
|
|
|
+ )),
|
|
|
+ })
|
|
|
+ id_map[item["local_id"]] = saved["id"]
|
|
|
+ element_ids.append(saved["id"])
|
|
|
+
|
|
|
+ llm_evidence = None
|
|
|
+ if result["result"].get("llm"):
|
|
|
+ llm_evidence = create_evidence(db, tenant_id, project_id, {
|
|
|
+ "kind": "ModelInference", "uri": f"evidence://ontology-build/{build_id}/llm",
|
|
|
+ "title": f"{settings.model} 本体语义融合结果",
|
|
|
+ "content": _dump(result["semantic"]), "source": f"{settings.provider}:{settings.model}",
|
|
|
+ "metadata": {"build_id": build_id, **result["result"]["llm"]},
|
|
|
+ })
|
|
|
+ evidence_ids.append(llm_evidence["id"])
|
|
|
+
|
|
|
+ assertion_ids = []
|
|
|
+ for item in result["result"]["assertions"]:
|
|
|
+ if item["subject"] not in id_map or item["object"] not in id_map:
|
|
|
+ continue
|
|
|
+ generated_by = str(item.get("generated_by") or (
|
|
|
+ f"lambdagent:semantic-fusion@{build_id}" if item.get("assertion_type") == "inferred"
|
|
|
+ else f"lambdagent:asset-construction@{build_id}"
|
|
|
+ ))
|
|
|
+ assertion = create_assertion(db, tenant_id, project_id, {
|
|
|
+ "subject_id": id_map[item["subject"]], "predicate": item["predicate"],
|
|
|
+ "object_id": id_map[item["object"]], "assertion_type": item["assertion_type"],
|
|
|
+ "confidence": item["confidence"], "review_status": "pending",
|
|
|
+ "evidence_ids": [] if generated_by == CATALOG_GENERATOR else (
|
|
|
+ [llm_evidence["id"]] if generated_by.startswith("longcat:") and llm_evidence else evidence_ids
|
|
|
+ ),
|
|
|
+ "generated_by": generated_by,
|
|
|
+ })
|
|
|
+ assertion_ids.append(assertion["id"])
|
|
|
+
|
|
|
+ issue_now = now_utc()
|
|
|
+ for item in result["result"]["issues"]:
|
|
|
+ db.execute(
|
|
|
+ "INSERT INTO governance_issues "
|
|
|
+ "(id,tenant_id,project_id,rule_id,target_id,severity,title,description,status,evidence_ids,created_at,updated_at) "
|
|
|
+ "VALUES (?,?,?,?,?,?,?,?,'open',?,?,?)",
|
|
|
+ (gen_id("gi_"), tenant_id, project_id, f"ontology-build:{build_id}:{item['code']}",
|
|
|
+ id_map.get(item["target"], ""), item["severity"], item["title"], item["description"],
|
|
|
+ _dump(evidence_ids), issue_now, issue_now),
|
|
|
+ )
|
|
|
+ db.commit()
|
|
|
+
|
|
|
+ validation = validate_project(db, tenant_id, project_id, persist=False)
|
|
|
+ trace = _audit_trace(context)
|
|
|
+ paas_runs = _record_paas_build(build_id, project_id, result, trace)
|
|
|
+ completed_at = now_utc()
|
|
|
+ db.execute(
|
|
|
+ "UPDATE ontology_builds SET status='review_required',evidence_ids=?,element_ids=?,assertion_ids=?,"
|
|
|
+ "candidate_rules=?,diff_json=?,validation_json=?,trace_json=?,llm_json=?,paas_runs=?,completed_at=? WHERE id=?",
|
|
|
+ (_dump(sorted(set(evidence_ids))), _dump(sorted(set(element_ids))), _dump(sorted(set(assertion_ids))),
|
|
|
+ _dump(result["candidate_rules"]), _dump(result["diff"]), _dump(validation), _dump(trace),
|
|
|
+ _dump(result["result"].get("llm") or {}), _dump(paas_runs), completed_at, build_id),
|
|
|
+ )
|
|
|
+ response = {
|
|
|
+ "build_id": build_id, "run_id": run_id, "status": "review_required",
|
|
|
+ "semantic_mode": resolved_mode, "agents": [
|
|
|
+ "asset-construction-agent", "semantic-fusion-agent", "ontology-validation-agent",
|
|
|
+ ],
|
|
|
+ "summary": result["result"]["summary"], "diff": result["diff"],
|
|
|
+ "validation": validation, "candidate_validation": result["candidate_validation"],
|
|
|
+ "llm": result["result"].get("llm") or {}, "trace": trace, "paas_runs": paas_runs,
|
|
|
+ "persisted": {"evidence": len(set(evidence_ids)), "elements": len(set(element_ids)), "assertions": len(set(assertion_ids))},
|
|
|
+ }
|
|
|
+ llm = response["llm"]
|
|
|
+ db.execute(
|
|
|
+ "UPDATE governance_agent_runs SET status='completed',result_json=?,trace_json=?,input_tokens=?,output_tokens=?,"
|
|
|
+ "llm_latency_ms=?,llm_request_hash=?,llm_response_hash=?,completed_at=? WHERE id=?",
|
|
|
+ (_dump(response), _dump(trace), int(llm.get("input_tokens") or 0), int(llm.get("output_tokens") or 0),
|
|
|
+ float(llm.get("latency_ms") or 0), str(llm.get("request_hash") or ""),
|
|
|
+ str(llm.get("response_hash") or ""), completed_at, run_id),
|
|
|
+ )
|
|
|
+ db.commit()
|
|
|
+ return response
|
|
|
+ except Exception as exc:
|
|
|
+ trace = _audit_trace(context)
|
|
|
+ db.execute(
|
|
|
+ "UPDATE ontology_builds SET status='failed',error=?,trace_json=?,completed_at=? WHERE id=?",
|
|
|
+ (str(exc)[:1000], _dump(trace), now_utc(), build_id),
|
|
|
+ )
|
|
|
+ db.execute(
|
|
|
+ "UPDATE governance_agent_runs SET status='failed',error=?,trace_json=?,completed_at=? WHERE id=?",
|
|
|
+ (str(exc)[:1000], _dump(trace), now_utc(), run_id),
|
|
|
+ )
|
|
|
+ db.commit()
|
|
|
+ if isinstance(exc, GovernanceError):
|
|
|
+ raise
|
|
|
+ raise GovernanceError(
|
|
|
+ f"本体构建失败:{str(exc)[:500]}",
|
|
|
+ code="ONTOLOGY_BUILD_FAILED",
|
|
|
+ status=422,
|
|
|
+ ) from exc
|
|
|
+
|
|
|
+
|
|
|
+def get_ontology_build(db, tenant_id: str, project_id: str, build_id: str) -> dict:
|
|
|
+ require_project(db, tenant_id, project_id)
|
|
|
+ value = db.fetchone(
|
|
|
+ "SELECT * FROM ontology_builds WHERE id=? AND tenant_id=? AND project_id=?",
|
|
|
+ (build_id, tenant_id, project_id),
|
|
|
+ )
|
|
|
+ if not value:
|
|
|
+ raise GovernanceError("本体构建批次不存在", code="ONTOLOGY_BUILD_NOT_FOUND", status=404)
|
|
|
+ return _build_row(value) # type: ignore[return-value]
|
|
|
+
|
|
|
+
|
|
|
+def list_ontology_builds(db, tenant_id: str, project_id: str, limit: int = 50) -> list[dict]:
|
|
|
+ require_project(db, tenant_id, project_id)
|
|
|
+ return [
|
|
|
+ _build_row(item) for item in db.fetchall(
|
|
|
+ "SELECT * FROM ontology_builds WHERE tenant_id=? AND project_id=? ORDER BY created_at DESC LIMIT ?",
|
|
|
+ (tenant_id, project_id, min(max(limit, 1), 200)),
|
|
|
+ )
|
|
|
+ ]
|
|
|
+
|
|
|
+
|
|
|
+def list_ontology_versions(db, tenant_id: str, project_id: str) -> list[dict]:
|
|
|
+ require_project(db, tenant_id, project_id)
|
|
|
+ values = db.fetchall(
|
|
|
+ "SELECT * FROM ontology_versions WHERE tenant_id=? AND project_id=? ORDER BY version_number DESC",
|
|
|
+ (tenant_id, project_id),
|
|
|
+ )
|
|
|
+ for item in values:
|
|
|
+ for field, default in (("element_ids", []), ("assertion_ids", []), ("snapshot_json", {})):
|
|
|
+ item[field] = _loads(item.get(field), default)
|
|
|
+ return values
|
|
|
+
|
|
|
+
|
|
|
+def publish_ontology_build(
|
|
|
+ db,
|
|
|
+ tenant_id: str,
|
|
|
+ project_id: str,
|
|
|
+ build_id: str,
|
|
|
+ *,
|
|
|
+ reviewer: str,
|
|
|
+ accept_semantic_assertions: bool = False,
|
|
|
+ decision_target: str = "",
|
|
|
+) -> dict:
|
|
|
+ if not reviewer.strip():
|
|
|
+ raise GovernanceError("发布本体必须提供审核人")
|
|
|
+ build = get_ontology_build(db, tenant_id, project_id, build_id)
|
|
|
+ if build["status"] == "published":
|
|
|
+ versions = list_ontology_versions(db, tenant_id, project_id)
|
|
|
+ version = next((item for item in versions if item["build_id"] == build_id), None)
|
|
|
+ return {"build": build, "version": version, "decision": None, "idempotent": True}
|
|
|
+ if build["status"] != "review_required":
|
|
|
+ raise GovernanceError("只有待审核的候选本体可以发布", code="ONTOLOGY_BUILD_NOT_REVIEWABLE")
|
|
|
+
|
|
|
+ now = now_utc()
|
|
|
+ element_ids = build["element_ids"]
|
|
|
+ if element_ids:
|
|
|
+ placeholders = ",".join("?" for _ in element_ids)
|
|
|
+ db.execute(
|
|
|
+ f"UPDATE ontology_elements SET status='published',updated_at=? WHERE tenant_id=? AND project_id=? AND id IN ({placeholders})",
|
|
|
+ (now, tenant_id, project_id, *element_ids),
|
|
|
+ )
|
|
|
+ accepted_ids, pending_ids = [], []
|
|
|
+ for assertion_id in build["assertion_ids"]:
|
|
|
+ assertion = db.fetchone(
|
|
|
+ "SELECT assertion_type,review_status FROM governance_assertions WHERE id=? AND tenant_id=? AND project_id=?",
|
|
|
+ (assertion_id, tenant_id, project_id),
|
|
|
+ )
|
|
|
+ if not assertion:
|
|
|
+ continue
|
|
|
+ accept = assertion["assertion_type"] != "inferred" or accept_semantic_assertions
|
|
|
+ status = "accepted" if accept else "pending"
|
|
|
+ db.execute(
|
|
|
+ "UPDATE governance_assertions SET review_status=?,reviewer=?,review_note=?,updated_at=? WHERE id=?",
|
|
|
+ (status, reviewer.strip() if accept else "", "本体构建发布" if accept else "等待语义复核", now, assertion_id),
|
|
|
+ )
|
|
|
+ (accepted_ids if accept else pending_ids).append(assertion_id)
|
|
|
+ for rule in build["candidate_rules"]:
|
|
|
+ if isinstance(rule, dict):
|
|
|
+ upsert_rule(db, tenant_id, project_id, rule)
|
|
|
+ db.commit()
|
|
|
+
|
|
|
+ validation = validate_project(db, tenant_id, project_id, persist=True)
|
|
|
+ version_number = int((db.fetchone(
|
|
|
+ "SELECT COALESCE(MAX(version_number),0) AS n FROM ontology_versions WHERE tenant_id=? AND project_id=?",
|
|
|
+ (tenant_id, project_id),
|
|
|
+ ) or {"n": 0})["n"]) + 1
|
|
|
+ snapshot = graph(db, tenant_id, project_id, include_pending=False)
|
|
|
+ published_nodes = [item for item in snapshot["nodes"] if item.get("status") == "published"]
|
|
|
+ published_ids = {item["id"] for item in published_nodes}
|
|
|
+ snapshot = {
|
|
|
+ "nodes": published_nodes,
|
|
|
+ "edges": [
|
|
|
+ item for item in snapshot["edges"]
|
|
|
+ if item.get("subject_id") in published_ids
|
|
|
+ and (not item.get("object_id") or item.get("object_id") in published_ids)
|
|
|
+ ],
|
|
|
+ }
|
|
|
+ version_id = gen_id("ov_")
|
|
|
+ db.execute(
|
|
|
+ "INSERT INTO ontology_versions "
|
|
|
+ "(id,tenant_id,project_id,build_id,version_number,label,element_ids,assertion_ids,snapshot_json,published_by,created_at) "
|
|
|
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?)",
|
|
|
+ (version_id, tenant_id, project_id, build_id, version_number, f"v{version_number}",
|
|
|
+ _dump(element_ids), _dump(accepted_ids), _dump(snapshot), reviewer.strip(), now),
|
|
|
+ )
|
|
|
+
|
|
|
+ target = decision_target.strip() or str(build.get("decision_target") or "").strip()
|
|
|
+ decision, decision_trace, paas_run = None, [], None
|
|
|
+ if target:
|
|
|
+ decision_context = Context(run_id=f"{build['run_id']}:decision")
|
|
|
+ decision_term = Tool(
|
|
|
+ "governance-decision-agent",
|
|
|
+ lambda value: evaluate_retirement_gate(
|
|
|
+ db, tenant_id, project_id, value["target"], persist=True,
|
|
|
+ run_id=build["run_id"], include_pending=True,
|
|
|
+ ),
|
|
|
+ )
|
|
|
+ decision = decision_term.apply({"target": target}, decision_context)
|
|
|
+ decision_trace = _audit_trace(decision_context)
|
|
|
+ paas_run = record_agent_run(
|
|
|
+ "governance-decision-agent",
|
|
|
+ input_summary={"build_id": build_id, "project_id": project_id, "target": target},
|
|
|
+ output_summary={"status": decision["status"], "summary": decision["summary"]},
|
|
|
+ duration_ms=_trace_duration(decision_trace, "governance-decision-agent"),
|
|
|
+ )
|
|
|
+ paas_runs = [*build["paas_runs"], *([paas_run] if paas_run else [])]
|
|
|
+ db.execute(
|
|
|
+ "UPDATE ontology_builds SET status='published',validation_json=?,trace_json=?,paas_runs=?,published_at=? WHERE id=?",
|
|
|
+ (_dump(validation), _dump([*build["trace_json"], *decision_trace]), _dump(paas_runs), now, build_id),
|
|
|
+ )
|
|
|
+ db.execute(
|
|
|
+ "UPDATE governance_projects SET version=?,updated_at=? WHERE id=? AND tenant_id=?",
|
|
|
+ (f"1.0.{version_number}", now, project_id, tenant_id),
|
|
|
+ )
|
|
|
+ if decision:
|
|
|
+ db.execute(
|
|
|
+ "UPDATE governance_agent_runs SET decision_id=? WHERE id=?",
|
|
|
+ (decision["id"], build["run_id"]),
|
|
|
+ )
|
|
|
+ db.commit()
|
|
|
+ version = {
|
|
|
+ "id": version_id, "build_id": build_id, "version_number": version_number,
|
|
|
+ "label": f"v{version_number}", "element_ids": element_ids, "assertion_ids": accepted_ids,
|
|
|
+ "published_by": reviewer.strip(), "created_at": now,
|
|
|
+ }
|
|
|
+ return {
|
|
|
+ "build": get_ontology_build(db, tenant_id, project_id, build_id),
|
|
|
+ "version": version, "validation": validation, "decision": decision,
|
|
|
+ "published": {"elements": len(element_ids), "accepted_assertions": len(accepted_ids), "pending_assertions": len(pending_ids)},
|
|
|
+ "paas_run": paas_run, "idempotent": False,
|
|
|
+ }
|