JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(symphony-orchestration): 增加交响乐编排核心组件
lin-xiaoyu6e39ff605dc0
diff --git a/jiuwenswarm/symphony/__init__.py b/jiuwenswarm/symphony/__init__.pynew file mode 100644index 0000000000..dda90101c9--- /dev/null+++ b/jiuwenswarm/symphony/__init__.py@@ -0,0 +1 @@+"""Symphony capabilities for JiuwenSwarm."""diff --git a/jiuwenswarm/symphony/build.py b/jiuwenswarm/symphony/build.pynew file mode 100644index 0000000000..2423b12477--- /dev/null+++ b/jiuwenswarm/symphony/build.py@@ -0,0 +1,414 @@+"""Symphony Score build APIs."""++from __future__ import annotations++import json+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Callable++from jiuwenswarm.symphony.config import (+ SymphonyBuildConfig,+ SymphonyConfig,+ default_symphony_config,+)+from jiuwenswarm.symphony.fingerprint import (+ FingerprintExtractor,+ LLMConfig,+ LLMIONameResolver,+ LLMSchemaExtractor,+ NormalizationConfig,+ SkillFolderScanner,+ SkillManifestParser,+ SkillFingerprintNormalizer,+ SkillSchemaExtractor,+ write_extraction_result,+)+from jiuwenswarm.symphony.graph.matcher import (+ OntologyMatcher,+ OpenAICompatibleOntologyMatcher,+)+from jiuwenswarm.symphony.graph.pipeline import GraphBuilder+from jiuwenswarm.symphony.graph.writer import write_graph_build_result+from jiuwenswarm.symphony.llm import reset_llm_token_usage+from jiuwenswarm.symphony.score_state import (+ SCORE_STATE_FILENAME,+ ScoreStateBuilder,+ load_score_state,+ write_score_state,+)+++@dataclass(frozen=True)+class ScoreStatus:+ success: bool+ score_dir: str+ exists: bool+ stale: bool+ skill_count: int+ changed_count: int+ added_count: int+ removed_count: int+ detail: str = ""++ def to_dict(self) -> dict[str, Any]:+ return {+ "success": self.success,+ "score_dir": self.score_dir,+ "exists": self.exists,+ "stale": self.stale,+ "skill_count": self.skill_count,+ "changed_count": self.changed_count,+ "added_count": self.added_count,+ "removed_count": self.removed_count,+ "detail": self.detail,+ }+++@dataclass(frozen=True)+class ScoreBuildResult:+ success: bool+ score_dir: str+ skill_count: int+ reused_count: int+ extracted_count: int+ removed_count: int+ edge_count: int+ diagnostics_count: int+ detail: str = ""++ def to_dict(self) -> dict[str, Any]:+ return {+ "success": self.success,+ "score_dir": self.score_dir,+ "skill_count": self.skill_count,+ "reused_count": self.reused_count,+ "extracted_count": self.extracted_count,+ "removed_count": self.removed_count,+ "edge_count": self.edge_count,+ "diagnostics_count": self.diagnostics_count,+ "detail": self.detail,+ }+++class ScoreBuildRuntimeFactory:+ """Create default runtime adapters for a Symphony Score build."""++ @staticmethod+ def schema_extractor(+ llm_config: LLMConfig | None,+ extraction_config: Any,+ ) -> SkillSchemaExtractor:+ if llm_config is None:+ raise ValueError("llm_config is required when schema_extractor is not provided")+ return LLMSchemaExtractor(+ llm_config,+ body_limit=extraction_config.body_limit,+ batch_size=extraction_config.batch_size,+ )++ @staticmethod+ def io_name_resolver(+ llm_config: LLMConfig | None,+ normalization_config: Any,+ ) -> Any:+ if llm_config is None:+ raise ValueError("llm_config is required when io_name_resolver is not provided")+ return LLMIONameResolver(+ llm_config,+ batch_size=normalization_config.batch_size,+ )++ @staticmethod+ def matcher(+ llm_config: LLMConfig | None,+ *,+ build_config: SymphonyBuildConfig,+ build_log: Callable[..., None] | None = None,+ ) -> OntologyMatcher:+ if llm_config is None:+ raise ValueError("llm_config is required when matcher is not provided")+ return OpenAICompatibleOntologyMatcher(+ llm_config,+ batch_size=build_config.batch_size,+ max_workers=build_config.workers,+ require_consensus=build_config.require_consensus,+ thresholds={"can_feed": build_config.min_edge_confidence},+ progress=(+ lambda event, current, total, details: _record_build_log(+ build_log,+ "graph.resolve.progress",+ event=event,+ current=current,+ total=total,+ details=details,+ )+ ),+ )+++class SymphonyScoreBuilder:+ """Build and refresh the offline Symphony Score."""++ def __init__(+ self,+ *,+ scanner: SkillFolderScanner | None = None,+ parser: SkillManifestParser | None = None,+ runtime_factory: ScoreBuildRuntimeFactory | None = None,+ state_builder: ScoreStateBuilder | None = None,+ ) -> None:+ self.scanner = scanner or SkillFolderScanner()+ self.parser = parser or SkillManifestParser()+ self.runtime_factory = runtime_factory or ScoreBuildRuntimeFactory()+ self.state_builder = state_builder or ScoreStateBuilder()++ def status(+ self,+ skills_root: str | Path,+ score_dir: str | Path,+ *,+ symphony_config: SymphonyConfig | None = None,+ ) -> ScoreStatus:+ runtime_config = symphony_config or default_symphony_config()+ output_dir = Path(score_dir).resolve()+ folders = self.scanner.scan(+ skills_root,+ max_depth=runtime_config.fingerprint.scan.max_depth,+ )+ current_hashes = self.state_builder.folder_hashes(folders)+ state = load_score_state(output_dir)+ active_entries = state.active_entries()+ exists = (output_dir / "score_manifest.json").is_file()+ added = [path for path in current_hashes if path not in active_entries]+ changed = [+ path+ for path, digest in current_hashes.items()+ if path in active_entries and active_entries[path].skill_md_sha256 != digest+ ]+ removed = [path for path in active_entries if path not in current_hashes]+ stale = (not exists) or bool(added or changed or removed)+ detail = "score is fresh"+ if not exists:+ detail = "Symphony Score is missing"+ elif stale:+ detail = "Symphony Score is stale"++ return ScoreStatus(+ success=True,+ score_dir=str(output_dir),+ exists=exists,+ stale=stale,+ skill_count=len(folders),+ changed_count=len(changed),+ added_count=len(added),+ removed_count=len(removed),+ detail=detail,+ )++ async def build(+ self,+ skills_root: str | Path,+ score_dir: str | Path,+ llm_config: LLMConfig | None = None,+ *,+ force: bool = False,+ schema_extractor: SkillSchemaExtractor | None = None,+ matcher: OntologyMatcher | None = None,+ io_name_resolver: Any | None = None,+ build_log: Callable[..., None] | None = None,+ symphony_config: SymphonyConfig | None = None,+ ) -> ScoreBuildResult:+ runtime_config = symphony_config or default_symphony_config()+ output_dir = Path(score_dir).resolve()+ output_dir.mkdir(parents=True, exist_ok=True)+ reset_llm_token_usage()++ normalization_runtime_config = runtime_config.fingerprint.normalization+ normalization_config = NormalizationConfig(+ max_vocab_size=normalization_runtime_config.max_vocab_size,+ possible_duplicate_name_similarity_threshold=(+ normalization_runtime_config.duplicate_name_similarity_threshold+ ),+ )+ normalizer = SkillFingerprintNormalizer(+ config=normalization_config,+ io_name_resolver=io_name_resolver+ or self.runtime_factory.io_name_resolver(+ llm_config,+ runtime_config.fingerprint.normalization,+ ),+ )+ schema_extractor = schema_extractor or self.runtime_factory.schema_extractor(+ llm_config,+ runtime_config.fingerprint.extraction,+ )++ fingerprint_extractor = FingerprintExtractor(+ schema_extractor=schema_extractor,+ scanner=self.scanner,+ parser=self.parser,+ normalizer=normalizer,+ progress=_fingerprint_progress_adapter(build_log),+ event_log=build_log,+ max_workers=runtime_config.fingerprint.extraction.workers,+ normalization_workers=runtime_config.fingerprint.normalization.workers,+ normalization_batch_size=runtime_config.fingerprint.normalization.batch_size,+ )+ _record_build_log(build_log, "scan.start", skills_root=str(skills_root))+ extraction_result = await fingerprint_extractor.extract_from_root(+ skills_root,+ output_dir=output_dir,+ max_depth=runtime_config.fingerprint.scan.max_depth,+ force=force,+ )+ _record_build_log(+ build_log,+ "artifact.fingerprints.write.start",+ fingerprint_count=len(extraction_result.fingerprints),+ diagnostics_count=len(extraction_result.diagnostics),+ )+ write_extraction_result(extraction_result, output_dir)+ _record_build_log(build_log, "artifact.fingerprints.write.done")++ _record_build_log(+ build_log,+ "graph.build.start",+ fingerprint_count=len(extraction_result.fingerprints),+ workers=runtime_config.build.workers,+ )+ matcher = matcher or self.runtime_factory.matcher(+ llm_config,+ build_config=runtime_config.build,+ build_log=build_log,+ )+ graph_builder = GraphBuilder(matcher=matcher)+ graph_result = await graph_builder.build(+ extraction_result.fingerprints,+ progress=build_log,+ )+ _record_build_log(+ build_log,+ "graph.build.done",+ candidate_count=len(graph_result.candidates),+ match_count=len(graph_result.llm_matches),+ edge_count=len(graph_result.graph.edges),+ diagnostics_count=len(graph_result.diagnostics),+ )+ _record_build_log(build_log, "artifact.graph.write.start")+ write_graph_build_result(graph_result, output_dir)+ _write_io_vocab(extraction_result.io_name_vocab, output_dir)+ _record_build_log(build_log, "artifact.graph.write.done")++ new_state = self.state_builder.next_state(+ folders=extraction_result.folders,+ current_hashes=extraction_result.current_hashes,+ fingerprints_by_path=extraction_result.fingerprints_by_path,+ old_state=load_score_state(output_dir),+ removed_paths=extraction_result.removed_paths,+ )+ _record_build_log(+ build_log,+ "state.write.start",+ path=str(output_dir / SCORE_STATE_FILENAME),+ )+ write_score_state(new_state, output_dir)+ _record_build_log(build_log, "state.write.done")++ return ScoreBuildResult(+ success=True,+ score_dir=str(output_dir),+ skill_count=len(extraction_result.folders),+ reused_count=extraction_result.reused_count,+ extracted_count=extraction_result.extracted_count,+ removed_count=len(extraction_result.removed_paths),+ edge_count=len(graph_result.graph.edges),+ diagnostics_count=(+ len(extraction_result.diagnostics) + len(graph_result.diagnostics)+ ),+ )+++def score_status(+ skills_root: str | Path,+ score_dir: str | Path,+ *,+ scanner: SkillFolderScanner | None = None,+ symphony_config: SymphonyConfig | None = None,+) -> ScoreStatus:+ """Report whether a Score exists and differs from the Skill folders."""++ return SymphonyScoreBuilder(scanner=scanner).status(+ skills_root,+ score_dir,+ symphony_config=symphony_config,+ )+++async def build_score(+ skills_root: str | Path,+ score_dir: str | Path,+ llm_config: LLMConfig | None = None,+ *,+ workers: int = 1,+ force: bool = False,+ schema_extractor: SkillSchemaExtractor | None = None,+ matcher: OntologyMatcher | None = None,+ io_name_resolver: Any | None = None,+ scanner: SkillFolderScanner | None = None,+ parser: SkillManifestParser | None = None,+ build_log: Callable[..., None] | None = None,+ symphony_config: SymphonyConfig | None = None,+ runtime_factory: ScoreBuildRuntimeFactory | None = None,+) -> ScoreBuildResult:+ """Build or refresh the offline Symphony Score."""++ del workers+ return await SymphonyScoreBuilder(+ scanner=scanner,+ parser=parser,+ runtime_factory=runtime_factory,+ ).build(+ skills_root,+ score_dir,+ llm_config,+ force=force,+ schema_extractor=schema_extractor,+ matcher=matcher,+ io_name_resolver=io_name_resolver,+ build_log=build_log,+ symphony_config=symphony_config,+ )+++def _fingerprint_progress_adapter(+ build_log: Callable[..., None] | None,+) -> Callable[[str, int, int, str], None] | None:+ if build_log is None:+ return None++ stage_map = {+ "parse": "fingerprint.parse.start",+ "extract": "fingerprint.extract.start",+ "normalize": "fingerprint.normalize.start",+ }++ def record(stage: str, current: int, total: int, item: str) -> None:+ build_stage = stage_map.get(stage)+ if build_stage is None:+ return+ build_log(build_stage, current=current, total=total, path=item)++ return record+++def _record_build_log(build_log: Callable[..., None] | None, stage: str, **details: Any) -> None:+ if build_log is not None:+ build_log(stage, **details)+++def _write_io_vocab(payload: dict[str, Any], score_dir: Path) -> None:+ (score_dir / "io_name_vocab.json").write_text(+ json.dumps(payload, ensure_ascii=False, indent=2),+ encoding="utf-8",+ )diff --git a/jiuwenswarm/symphony/config.py b/jiuwenswarm/symphony/config.pynew file mode 100644index 0000000000..f0bd30ab1e--- /dev/null+++ b/jiuwenswarm/symphony/config.py@@ -0,0 +1,288 @@+"""Runtime configuration for Symphony orchestration."""++from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path+from typing import Any++from jiuwenswarm.common.utils import get_agent_workspace_dir+++DEFAULT_FINGERPRINT_EXTRACTION_WORKERS = 1+DEFAULT_FINGERPRINT_EXTRACTION_BATCH_SIZE = 1+DEFAULT_FINGERPRINT_EXTRACTION_BODY_LIMIT = None+DEFAULT_FINGERPRINT_SCAN_MAX_DEPTH = None++DEFAULT_FINGERPRINT_NORMALIZATION_WORKERS = 1+DEFAULT_FINGERPRINT_NORMALIZATION_BATCH_SIZE = 1+DEFAULT_FINGERPRINT_NORMALIZATION_DUPLICATE_THRESHOLD = 0.86+DEFAULT_FINGERPRINT_NORMALIZATION_MAX_VOCAB_SIZE = None++DEFAULT_BUILD_WORKERS = 1+DEFAULT_BUILD_MATCHER_BATCH_SIZE = 12+DEFAULT_BUILD_REQUIRE_CONSENSUS = True+DEFAULT_BUILD_MIN_EDGE_CONFIDENCE = 0.7++DEFAULT_SYMPHONY_ENABLED = False++DEFAULT_ORCHESTRATION_MODE = "fast"+DEFAULT_ORCHESTRATION_TOP_K = 3+DEFAULT_ORCHESTRATION_MAX_DEPTH = 4+DEFAULT_ORCHESTRATION_MIN_EDGE_CONFIDENCE = 0.7+++@dataclass(frozen=True)+class SymphonyPathsConfig:+ skills_root: Path+ score_dir: Path+++@dataclass(frozen=True)+class FingerprintScanConfig:+ max_depth: int | None = DEFAULT_FINGERPRINT_SCAN_MAX_DEPTH+++@dataclass(frozen=True)+class FingerprintExtractionConfig:+ workers: int = DEFAULT_FINGERPRINT_EXTRACTION_WORKERS+ batch_size: int = DEFAULT_FINGERPRINT_EXTRACTION_BATCH_SIZE+ body_limit: int | None = DEFAULT_FINGERPRINT_EXTRACTION_BODY_LIMIT+++@dataclass(frozen=True)+class FingerprintNormalizationConfig:+ workers: int = DEFAULT_FINGERPRINT_NORMALIZATION_WORKERS+ batch_size: int = DEFAULT_FINGERPRINT_NORMALIZATION_BATCH_SIZE+ duplicate_name_similarity_threshold: float = (+ DEFAULT_FINGERPRINT_NORMALIZATION_DUPLICATE_THRESHOLD+ )+ max_vocab_size: int | None = DEFAULT_FINGERPRINT_NORMALIZATION_MAX_VOCAB_SIZE+++@dataclass(frozen=True)+class SymphonyFingerprintConfig:+ scan: FingerprintScanConfig+ extraction: FingerprintExtractionConfig+ normalization: FingerprintNormalizationConfig+++@dataclass(frozen=True)+class SymphonyBuildConfig:+ workers: int = DEFAULT_BUILD_WORKERS+ batch_size: int = DEFAULT_BUILD_MATCHER_BATCH_SIZE+ require_consensus: bool = DEFAULT_BUILD_REQUIRE_CONSENSUS+ min_edge_confidence: float = DEFAULT_BUILD_MIN_EDGE_CONFIDENCE+++@dataclass(frozen=True)+class SymphonyOrchestrationConfig:+ mode: str = DEFAULT_ORCHESTRATION_MODE+ top_k: int = DEFAULT_ORCHESTRATION_TOP_K+ max_depth: int = DEFAULT_ORCHESTRATION_MAX_DEPTH+ min_edge_confidence: float = DEFAULT_ORCHESTRATION_MIN_EDGE_CONFIDENCE+++@dataclass(frozen=True)+class SymphonyConfig:+ enabled: bool+ paths: SymphonyPathsConfig+ fingerprint: SymphonyFingerprintConfig+ build: SymphonyBuildConfig+ orchestration: SymphonyOrchestrationConfig+++def load_symphony_config(config: dict[str, Any] | None = None) -> SymphonyConfig:+ """Load and normalize ``config.yaml`` Symphony settings."""++ if config is None:+ from jiuwenswarm.common.config import get_config++ config = get_config() or {}+ raw = config.get("symphony") if isinstance(config, dict) else {}+ return symphony_config_from_dict(raw if isinstance(raw, dict) else {})+++def default_symphony_config() -> SymphonyConfig:+ return symphony_config_from_dict({})+++def symphony_config_from_dict(raw: dict[str, Any] | None) -> SymphonyConfig:+ data = raw if isinstance(raw, dict) else {}+ paths = data.get("paths") if isinstance(data.get("paths"), dict) else {}+ fingerprint = (+ data.get("fingerprint") if isinstance(data.get("fingerprint"), dict) else {}+ )+ scan = fingerprint.get("scan") if isinstance(fingerprint.get("scan"), dict) else {}+ extraction = (+ fingerprint.get("extraction")+ if isinstance(fingerprint.get("extraction"), dict)+ else {}+ )+ normalization = (+ fingerprint.get("normalization")+ if isinstance(fingerprint.get("normalization"), dict)+ else {}+ )+ build = data.get("build") if isinstance(data.get("build"), dict) else {}+ orchestration = (+ data.get("orchestration") if isinstance(data.get("orchestration"), dict) else {}+ )++ return SymphonyConfig(+ enabled=_bool(data.get("enabled"), DEFAULT_SYMPHONY_ENABLED),+ paths=SymphonyPathsConfig(+ skills_root=_resolve_path(+ paths.get("skills_root"),+ get_agent_workspace_dir() / "skills",+ ),+ score_dir=_resolve_path(+ paths.get("score_dir"),+ get_agent_workspace_dir() / "symphony" / "score",+ ),+ ),+ fingerprint=SymphonyFingerprintConfig(+ scan=FingerprintScanConfig(+ max_depth=_optional_non_negative_int(+ scan.get("max_depth"),+ DEFAULT_FINGERPRINT_SCAN_MAX_DEPTH,+ ),+ ),+ extraction=FingerprintExtractionConfig(+ workers=_positive_int(+ extraction.get("workers"),+ DEFAULT_FINGERPRINT_EXTRACTION_WORKERS,+ ),+ batch_size=_positive_int(+ extraction.get("batch_size"),+ DEFAULT_FINGERPRINT_EXTRACTION_BATCH_SIZE,+ ),+ body_limit=_optional_body_limit(+ extraction.get("body_limit"),+ DEFAULT_FINGERPRINT_EXTRACTION_BODY_LIMIT,+ ),+ ),+ normalization=FingerprintNormalizationConfig(+ workers=_positive_int(+ normalization.get("workers"),+ DEFAULT_FINGERPRINT_NORMALIZATION_WORKERS,+ ),+ batch_size=_positive_int(+ normalization.get("batch_size"),+ DEFAULT_FINGERPRINT_NORMALIZATION_BATCH_SIZE,+ ),+ duplicate_name_similarity_threshold=_clamped_float(+ normalization.get("duplicate_name_similarity_threshold"),+ DEFAULT_FINGERPRINT_NORMALIZATION_DUPLICATE_THRESHOLD,+ ),+ max_vocab_size=_optional_positive_int(+ normalization.get("max_vocab_size"),+ DEFAULT_FINGERPRINT_NORMALIZATION_MAX_VOCAB_SIZE,+ ),+ ),+ ),+ build=SymphonyBuildConfig(+ workers=_positive_int(build.get("workers"), DEFAULT_BUILD_WORKERS),+ batch_size=_positive_int(+ build.get("batch_size"),+ DEFAULT_BUILD_MATCHER_BATCH_SIZE,+ ),+ require_consensus=_bool(+ build.get("require_consensus"),+ DEFAULT_BUILD_REQUIRE_CONSENSUS,+ ),+ min_edge_confidence=_clamped_float(+ build.get("min_edge_confidence"),+ DEFAULT_BUILD_MIN_EDGE_CONFIDENCE,+ ),+ ),+ orchestration=SymphonyOrchestrationConfig(+ mode=_orchestration_mode(+ orchestration.get("mode"),+ DEFAULT_ORCHESTRATION_MODE,+ ),+ top_k=_positive_int(+ orchestration.get("top_k"),+ DEFAULT_ORCHESTRATION_TOP_K,+ ),+ max_depth=_positive_int(+ orchestration.get("max_depth"),+ DEFAULT_ORCHESTRATION_MAX_DEPTH,+ ),+ min_edge_confidence=_clamped_float(+ orchestration.get("min_edge_confidence"),+ DEFAULT_ORCHESTRATION_MIN_EDGE_CONFIDENCE,+ ),+ ),+ )+++def _resolve_path(value: Any, default: Path) -> Path:+ text = str(value or "").strip()+ if not text:+ return default.resolve()+ return Path(text).expanduser().resolve()+++def _positive_int(value: Any, default: int) -> int:+ try:+ parsed = int(value)+ except (TypeError, ValueError):+ return default+ return max(1, parsed)+++def _optional_positive_int(value: Any, default: int | None) -> int | None:+ if value is None or str(value).strip() == "":+ return default+ return _positive_int(value, default or 1)+++def _optional_non_negative_int(value: Any, default: int | None) -> int | None:+ if value is None or str(value).strip() == "":+ return default+ try:+ parsed = int(value)+ except (TypeError, ValueError):+ return default+ return max(0, parsed)+++def _optional_body_limit(value: Any, default: int | None) -> int | None:+ if value is None or str(value).strip() == "":+ return default+ try:+ parsed = int(value)+ except (TypeError, ValueError):+ return default+ return parsed if parsed > 0 else None+++def _clamped_float(value: Any, default: float) -> float:+ try:+ parsed = float(value)+ except (TypeError, ValueError):+ return default+ return max(0.0, min(1.0, parsed))+++def _bool(value: Any, default: bool) -> bool:+ if isinstance(value, bool):+ return value+ if value is None:+ return default+ text = str(value).strip().lower()+ if text in {"1", "true", "yes", "on"}:+ return True+ if text in {"0", "false", "no", "off"}:+ return False+ return default+++def _orchestration_mode(value: Any, default: str) -> str:+ text = str(value or "").strip().lower()+ if not text:+ return default+ if text in {"beam", "default", "fast"}:+ return "fast"+ raise ValueError(f"Unsupported Symphony orchestration mode: {value}")diff --git a/jiuwenswarm/symphony/fingerprint/__init__.py b/jiuwenswarm/symphony/fingerprint/__init__.pynew file mode 100644index 0000000000..ba4eb66e2c--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/__init__.py@@ -0,0 +1,119 @@+"""Skill fingerprint extraction.++This module provides a stage-based pipeline for extracting structured+fingerprints from Skill folders containing SKILL.md files.++Stages:+- scan: Discover Skill folders containing SKILL.md entrypoints+- parse: Parse SKILL.md into frontmatter and body+- extract: LLM schema extraction from parsed content+- normalize: Normalize I/O names, types, and identities via vocabularies+- write: Write extraction artifacts to disk+"""++# Models - core data contracts+from jiuwenswarm.symphony.fingerprint.models import (+ ArtifactSpec,+ ExtractedSkillSchema,+ ExtractionDiagnostic,+ NormalizationConfig,+ NormalizationDecision,+ NormalizationResult,+ ParameterSpec,+ RawSkillManifest,+ FingerprintExtractionResult,+ SkillFolder,+ SkillFingerprint,+ SkillSchemaExtractor,+)++# Stage: scan+from jiuwenswarm.symphony.fingerprint.scan import SkillFolderScanner++# Stage: parse+from jiuwenswarm.symphony.fingerprint.manifest import SkillManifestParser++# Stage: extract+from jiuwenswarm.symphony.fingerprint.extract import (+ LLMSchemaExtractor,+ schema_from_llm_payload,+)++# Stage: normalize+from jiuwenswarm.symphony.fingerprint.normalize import (+ # Metadata normalization+ MetadataNormalizer,+ # Base vocabulary+ BaseCandidate,+ BaseResolution,+ BaseVocabTerm,+ BaseVocabulary,+ term_similarity,+ # I/O name vocabulary+ IONameCandidate,+ IONameResolution,+ IONameResolver,+ IONameVocabTerm,+ IONameVocabulary,+ LLMIONameResolver,+ # Normalizer+ SkillFingerprintNormalizer,+)++# Stage: write+from jiuwenswarm.symphony.fingerprint.artifacts import (+ write_extraction_result,+ write_json_file,+)++# Pipeline+from jiuwenswarm.symphony.fingerprint.pipeline import FingerprintExtractor++# LLM config+from jiuwenswarm.symphony.llm import LLMConfig++__all__ = [+ # Models+ "ArtifactSpec",+ "MetadataNormalizer",+ "ExtractedSkillSchema",+ "ExtractionDiagnostic",+ "NormalizationConfig",+ "NormalizationDecision",+ "NormalizationResult",+ "ParameterSpec",+ "RawSkillManifest",+ "FingerprintExtractionResult",+ "SkillFolder",+ "SkillFingerprint",+ "SkillSchemaExtractor",+ # Stage: scan+ "SkillFolderScanner",+ # Stage: parse+ "SkillManifestParser",+ # Stage: extract+ "LLMSchemaExtractor",+ "schema_from_llm_payload",+ # Stage: normalize - base vocabulary+ "BaseCandidate",+ "BaseResolution",+ "BaseVocabTerm",+ "BaseVocabulary",+ "term_similarity",+ # Stage: normalize - I/O name vocabulary+ "IONameCandidate",+ "IONameResolution",+ "IONameResolver",+ "IONameVocabTerm",+ "IONameVocabulary",+ "LLMIONameResolver",+ # Stage: normalize - normalizer+ "SkillFingerprintNormalizer",+ # Stage: write+ "write_extraction_result",+ "write_json_file",+ # Pipeline+ "FingerprintExtractor",+ # LLM config+ "LLMConfig",+]diff --git a/jiuwenswarm/symphony/fingerprint/artifacts.py b/jiuwenswarm/symphony/fingerprint/artifacts.pynew file mode 100644index 0000000000..b5124ae857--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/artifacts.py@@ -0,0 +1,79 @@+"""Write fingerprint extraction artifacts to disk."""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any, Dict, Union++from jiuwenswarm.symphony.fingerprint.models import FingerprintExtractionResult+++def write_json_file(path: Path, data: Dict[str, Any]) -> None:+ """Write a JSON file with consistent formatting.++ Args:+ path: Target file path.+ data: Dictionary to serialize as JSON.+ """+ path.write_text(+ json.dumps(data, ensure_ascii=False, indent=2),+ encoding="utf-8",+ )+++def write_extraction_result(+ result: FingerprintExtractionResult,+ out_dir: Union[Path, str],+) -> None:+ """Write minimal extraction artifacts to the output directory.++ Creates the output directory if it doesn't exist and writes:+ - fingerprints.json: Normalized Skill fingerprints.+ - diagnostics.json: Extraction diagnostics.+ - normalization_decisions.json: Normalization decision trace.+ - io_name_vocab.json: Final I/O name vocabulary.+ - llm_token_usage.json: LLM request token usage grouped by stage.++ Args:+ result: The extraction result to write.+ out_dir: Output directory path.+ """+ output_path = Path(out_dir)+ output_path.mkdir(parents=True, exist_ok=True)++ write_json_file(+ output_path / "fingerprints.json",+ {+ "fingerprints": [+ fingerprint.to_dict()+ for fingerprint in result.fingerprints+ ]+ },+ )+ write_json_file(+ output_path / "io_name_vocab.json",+ result.io_name_vocab,+ )+ write_json_file(+ output_path / "diagnostics.json",+ {+ "diagnostics": [+ diagnostic.to_dict()+ for diagnostic in result.diagnostics+ ]+ },+ )+ write_json_file(+ output_path / "normalization_decisions.json",+ {+ "normalization_decisions": [+ decision.to_dict()+ for decision in result.normalization_decisions+ ]+ },+ )+ write_json_file(+ output_path / "llm_token_usage.json",+ result.llm_token_usage,+ )diff --git a/jiuwenswarm/symphony/fingerprint/batching.py b/jiuwenswarm/symphony/fingerprint/batching.pynew file mode 100644index 0000000000..54606a1fb1--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/batching.py@@ -0,0 +1,36 @@+"""Batching helpers for fingerprint extraction stages."""++from __future__ import annotations++import asyncio+from typing import Awaitable, Callable, Iterable, List, Sequence, TypeVar++T = TypeVar("T")+R = TypeVar("R")+++def chunked(items: Sequence[T], batch_size: int) -> List[List[T]]:+ size = max(1, int(batch_size))+ return [list(items[start: start + size]) for start in range(0, len(items), size)]+++async def gather_limited(+ batches: Iterable[List[T]],+ *,+ max_workers: int,+ run_batch: Callable[[List[T]], Awaitable[R]],+) -> List[R]:+ semaphore = asyncio.Semaphore(max(1, int(max_workers)))++ async def run_with_limit(batch: List[T]) -> R:+ async with semaphore:+ return await run_batch(batch)++ return await asyncio.gather(*(run_with_limit(batch) for batch in batches))+++def ensure_result_count(actual: int, expected: int, label: str) -> None:+ if actual != expected:+ raise RuntimeError(+ f"{label} returned {actual} results for {expected} inputs."+ )diff --git a/jiuwenswarm/symphony/fingerprint/extract/__init__.py b/jiuwenswarm/symphony/fingerprint/extract/__init__.pynew file mode 100644index 0000000000..2558836821--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/extract/__init__.py@@ -0,0 +1,8 @@+"""LLM schema extraction."""++from jiuwenswarm.symphony.fingerprint.extract.extractor import (+ LLMSchemaExtractor,+ schema_from_llm_payload,+)++__all__ = ["LLMSchemaExtractor", "schema_from_llm_payload"]\ No newline at end of filediff --git a/jiuwenswarm/symphony/fingerprint/extract/extractor.py b/jiuwenswarm/symphony/fingerprint/extract/extractor.pynew file mode 100644index 0000000000..7e2d8f7164--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/extract/extractor.py@@ -0,0 +1,337 @@+"""LLM-backed schema extraction."""++from __future__ import annotations++import json+from typing import Any, Dict, List++from jiuwenswarm.symphony.llm import (+ LLMConfig,+ create_llm_client,+ llm_usage_context,+)+from jiuwenswarm.symphony.fingerprint.models import (+ ArtifactSpec,+ ExtractedSkillSchema,+ ParameterSpec,+ RawSkillManifest,+)++_LOW_REASONING_REQUEST_OVERRIDES = {+ "extra_body": {"thinking": {"type": "disabled"}},+}+++class LLMSchemaExtractor:+ """Extract Skill IO schema using LLM."""++ def __init__(+ self,+ config: LLMConfig,+ *,+ body_limit: int | None = None,+ batch_size: int = 1,+ ) -> None:+ self.config = config+ self.client = create_llm_client(config)+ self.batch_size = max(1, int(batch_size))+ self.use_batch = self.batch_size > 1+ self.body_limit = _normalize_body_limit(body_limit)++ async def extract(self, manifest: RawSkillManifest) -> ExtractedSkillSchema:+ with llm_usage_context("fingerprint_extraction", "schema_extraction"):+ content = await self.client.complete_json_async(+ system_prompt=_SCHEMA_EXTRACTION_PROMPT,+ user_content=json.dumps(+ _build_llm_context(manifest, body_limit=self.body_limit),+ ensure_ascii=False,+ indent=2,+ ),+ error_context="LLM schema extraction",+ request_overrides=_LOW_REASONING_REQUEST_OVERRIDES,+ )+ try:+ payload = json.loads(content)+ except json.JSONDecodeError as exc:+ raise RuntimeError(+ "LLM response is not valid JSON. "+ f"content_prefix={content[:1000]!r}"+ ) from exc+ return schema_from_llm_payload(payload)++ async def extract_many(+ self,+ manifests: List[RawSkillManifest],+ ) -> List[ExtractedSkillSchema]:+ if self.batch_size > 1:+ return await self._extract_many_prompt_batch(manifests)++ with llm_usage_context("fingerprint_extraction", "schema_extraction_batch"):+ contents = await self.client.complete_json_many_async(+ [+ {+ "system_prompt": _SCHEMA_EXTRACTION_PROMPT,+ "user_content": json.dumps(+ _build_llm_context(manifest, body_limit=self.body_limit),+ ensure_ascii=False,+ indent=2,+ ),+ }+ for manifest in manifests+ ],+ error_context="LLM schema extraction batch",+ request_overrides=_LOW_REASONING_REQUEST_OVERRIDES,+ )+ schemas: List[ExtractedSkillSchema] = []+ for index, content in enumerate(contents, start=1):+ try:+ payload = json.loads(content)+ except json.JSONDecodeError as exc:+ raise RuntimeError(+ "LLM batch response item is not valid JSON. "+ f"item={index} content_prefix={content[:1000]!r}"+ ) from exc+ schemas.append(schema_from_llm_payload(payload))+ return schemas++ async def _extract_many_prompt_batch(+ self,+ manifests: List[RawSkillManifest],+ ) -> List[ExtractedSkillSchema]:+ if not manifests:+ return []+ if len(manifests) == 1:+ return [await self.extract(manifests[0])]++ try:+ return await self._extract_many_prompt_batch_once(manifests)+ except RuntimeError:+ midpoint = len(manifests) // 2+ if midpoint <= 0:+ return [await self.extract(manifests[0])]+ return (+ await self._extract_many_prompt_batch(manifests[:midpoint])+ + await self._extract_many_prompt_batch(manifests[midpoint:])+ )++ async def _extract_many_prompt_batch_once(+ self,+ manifests: List[RawSkillManifest],+ ) -> List[ExtractedSkillSchema]:+ with llm_usage_context(+ "fingerprint_extraction",+ "schema_extraction_prompt_batch",+ ):+ content = await self.client.complete_json_async(+ system_prompt=_SCHEMA_EXTRACTION_BATCH_PROMPT,+ user_content=json.dumps(+ {+ "skills": [+ _build_llm_context(+ manifest,+ body_limit=self.body_limit,+ )+ for manifest in manifests+ ],+ },+ ensure_ascii=False,+ indent=2,+ ),+ error_context="LLM schema extraction prompt batch",+ request_overrides=_LOW_REASONING_REQUEST_OVERRIDES,+ )+ try:+ payload = json.loads(content)+ except json.JSONDecodeError as exc:+ raise RuntimeError(+ "LLM prompt batch response is not valid JSON. "+ f"content_prefix={content[:1000]!r}"+ ) from exc++ schemas_payload = payload.get("schemas")+ if not isinstance(schemas_payload, list):+ raise RuntimeError("LLM prompt batch response must contain schemas array.")++ expected_refs = [manifest.folder.relative_path for manifest in manifests]+ by_ref: Dict[str, Dict[str, Any]] = {}+ for item in schemas_payload:+ if not isinstance(item, dict):+ raise RuntimeError("LLM prompt batch schema items must be objects.")+ skill_ref = str(item.get("skill_ref") or "")+ if skill_ref in by_ref:+ raise RuntimeError(+ f"LLM prompt batch returned duplicate skill_ref: {skill_ref!r}."+ )+ by_ref[skill_ref] = item++ missing_refs = [+ skill_ref for skill_ref in expected_refs if skill_ref not in by_ref+ ]+ extra_refs = sorted(set(by_ref) - set(expected_refs))+ if missing_refs or extra_refs:+ raise RuntimeError(+ "LLM prompt batch response skill_ref mismatch. "+ f"missing={missing_refs!r} extra={extra_refs!r}"+ )++ return [schema_from_llm_payload(by_ref[skill_ref]) for skill_ref in expected_refs]+++def schema_from_llm_payload(payload: Dict[str, Any]) -> ExtractedSkillSchema:+ """Convert a raw LLM JSON payload into ExtractedSkillSchema."""++ warnings = [str(item) for item in payload.get("warnings", [])]+ raw_output_notes = payload.get("raw_output_notes", [])+ if isinstance(raw_output_notes, str):+ raw_output_notes = [raw_output_notes]+ warnings.extend(str(item) for item in raw_output_notes if str(item).strip())++ return ExtractedSkillSchema(+ description=str(payload.get("description") or ""),+ inputs=[_parameter_from_payload(item) for item in payload.get("inputs", [])],+ outputs=[_artifact_from_payload(item) for item in payload.get("outputs", [])],+ confidence=payload.get("confidence"),+ warnings=warnings,+ )+++def _parameter_from_payload(payload: Dict[str, Any]) -> ParameterSpec:+ return ParameterSpec(+ name=str(payload.get("name") or "input"),+ type=_combined_type_from_payload(payload, "text"),+ required=bool(payload.get("required", True)),+ description=str(payload.get("description") or ""),+ default=payload.get("default"),+ )+++def _artifact_from_payload(payload: Dict[str, Any]) -> ArtifactSpec:+ return ArtifactSpec(+ name=str(payload.get("name") or "result"),+ type=_combined_type_from_payload(payload, "unknown"),+ description=str(payload.get("description") or ""),+ )+++def _combined_type_from_payload(payload: Dict[str, Any], default: str) -> str:+ return str(payload.get("format") or payload.get("type") or default)+++def _build_llm_context(+ manifest: RawSkillManifest,+ *,+ body_limit: int | None = None,+) -> Dict[str, Any]:+ body_limit = _normalize_body_limit(body_limit)+ body = manifest.body if body_limit is None else manifest.body[:body_limit]+ return {+ "source": {+ "relative_path": manifest.folder.relative_path,+ "entry": "SKILL.md",+ },+ "frontmatter": manifest.frontmatter,+ "body": body,+ "body_truncated": body_limit is not None and len(manifest.body) > body_limit,+ }+++def _normalize_body_limit(body_limit: int | None) -> int | None:+ if body_limit is None:+ return None+ parsed = int(body_limit)+ return parsed if parsed > 0 else None++_SCHEMA_EXTRACTION_PROMPT = """You extract structured Skill IO fingerprints from SKILL.md files.++Return only a valid JSON object. Do not include markdown fences, explanations,+analysis, or reasoning text.++Required JSON object fields:+- description: concise string+- inputs: array of {name, type, required, description}+- outputs: array of {name, type, description}+- confidence: number between 0 and 1+- warnings: array of strings+Optional JSON object fields:+- raw_output_notes: array of strings describing raw API or script return fields+ that helped your reasoning but should not be recorded as output artifacts.++Read the entire SKILL.md content provided in this request, not only+input/output tables. Sections such as+"when to use", "output example", "return format", "notes", "summary", and final+instructions may enrich or override formal API field tables.+If body_truncated is true and important sections appear missing, add a warning+instead of inventing missing inputs or outputs.++Extract only capabilities, inputs, and outputs supported by the provided+SKILL.md/frontmatter. Do not infer tools, formats, or deliverables that are not+stated or strongly implied by the document.++Outputs must represent user-facing/downstream deliverables: artifacts the Skill+promises to hand to the user or to another Skill. Do not emit raw API/control fields as outputs.+This includes errorCode, errorMsg, status, logs, debug fields, or internal JSON+containers such as raw result, imageResult, or textResult, unless the document+says that raw structure is the actual deliverable.++If a raw API response contains a useful deliverable inside a nested field,+extract the deliverable as a semantic output instead of the raw container. For+example, textResult[].translateText may become translated_text with type text.+If the document says to send, show, return, or provide something in markdown,+markdown delivery instructions must be represented as markdown outputs.++Use name for the semantic role and type for the data format or carrier that is+passed between Skills.++Prefer these type values:+text, markdown, json, csv, table, yaml, xml, pdf, html, docx, pptx, xlsx,+image, png, jpg, svg, webp, gif, audio, video, file, path, url, code,+archive, unknown.++For example, a PDF paper should use name=paper and type=pdf. A markdown+summary should use name=summary and type=markdown.++Use input and output names as canonical semantic vocab terms for graph linking. Prefer+short noun roles such as query, topic, url, paper, summary, report, table,+image, code, file, path, or result when they fit. Put details in description+instead of making highly specific parameter names.++Inputs are runtime caller-provided values. Include content inputs and explicit+control/configuration inputs such as target_language, output_format, limit, or+command when the caller must provide them for normal execution. Do not turn+environment setup, API keys, permissions, installed tools, caches, or persistent+local configuration into inputs; mention them in warnings when relevant.++Set required=true only when the caller must provide the value for normal+execution. Use required=false for optional preferences, limits, defaults, or+output format choices that the Skill can infer or default.++Do not emit duplicate inputs for the same caller-provided value. Omit logging,+analytics, telemetry, statistics, tracing, debug evidence, or original-copy+fields unless the Skill truly consumes that value as a separate runtime input.++If unsure, use unknown and add a warning.+"""++_SCHEMA_EXTRACTION_BATCH_PROMPT = f"""{_SCHEMA_EXTRACTION_PROMPT}++You will receive a JSON object with a skills array. Each item is one independent+Skill context and includes source.relative_path.++Return only a valid JSON object with this shape:+{{+ "schemas": [+ {{+ "skill_ref": "the exact source.relative_path from the input skill",+ "description": "concise string",+ "inputs": [],+ "outputs": [],+ "confidence": 0.0,+ "warnings": []+ }}+ ]+}}++Return exactly one schema object for each input skill. Do not merge Skills, copy+inputs or outputs across Skills, or add schemas for Skills not present in the+request. Preserve skill_ref exactly so the caller can match results.+"""diff --git a/jiuwenswarm/symphony/fingerprint/incremental.py b/jiuwenswarm/symphony/fingerprint/incremental.pynew file mode 100644index 0000000000..26b1b6a4f5--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/incremental.py@@ -0,0 +1,102 @@+"""Incremental fingerprint reuse support."""++from __future__ import annotations++import json+from dataclasses import dataclass+from pathlib import Path+from typing import Callable++from jiuwenswarm.symphony.fingerprint.models import SkillFolder, SkillFingerprint+from jiuwenswarm.symphony.fingerprint.normalize import (+ IONameVocabulary,+ SkillFingerprintNormalizer,+)+from jiuwenswarm.symphony.score_state import load_score_state++IndexedSkillFolder = tuple[int, SkillFolder]+++@dataclass(frozen=True)+class FingerprintReusePlan:+ changed_folders: list[IndexedSkillFolder]+ fingerprints: list[SkillFingerprint]+ fingerprints_by_path: dict[str, SkillFingerprint]+ removed_paths: set[str]+ reused_count: int+++class IncrementalFingerprintStore:+ """Load prior Score artifacts and decide what must be re-extracted."""++ def __init__(self, output_dir: Path) -> None:+ self.output_dir = output_dir+ self.old_state = load_score_state(output_dir)+ self.old_fingerprints = load_fingerprints(output_dir)+ self.old_fingerprints_by_id = {item.id: item for item in self.old_fingerprints}++ def plan(+ self,+ folders: list[SkillFolder],+ current_hashes: dict[str, str],+ *,+ force: bool,+ on_reuse: Callable[[int, SkillFolder, SkillFingerprint], None] | None = None,+ ) -> FingerprintReusePlan:+ old_active_entries = self.old_state.active_entries()+ removed_paths = {+ relative_path+ for relative_path in old_active_entries+ if relative_path not in current_hashes+ }+ changed_folders: list[IndexedSkillFolder] = []+ fingerprints: list[SkillFingerprint] = []+ fingerprints_by_path: dict[str, SkillFingerprint] = {}+ reused_count = 0++ for folder_index, folder in enumerate(folders):+ old_entry = old_active_entries.get(folder.relative_path)+ if (+ not force+ and old_entry is not None+ and old_entry.skill_md_sha256 == current_hashes[folder.relative_path]+ ):+ old_fingerprint = self.old_fingerprints_by_id.get(old_entry.skill_id)+ if old_fingerprint is not None:+ fingerprints.append(old_fingerprint)+ fingerprints_by_path[folder.relative_path] = old_fingerprint+ reused_count += 1+ if on_reuse is not None:+ on_reuse(folder_index, folder, old_fingerprint)+ continue+ changed_folders.append((folder_index, folder))++ return FingerprintReusePlan(+ changed_folders=changed_folders,+ fingerprints=fingerprints,+ fingerprints_by_path=fingerprints_by_path,+ removed_paths=removed_paths,+ reused_count=reused_count,+ )+++def load_fingerprints(output_dir: Path) -> list[SkillFingerprint]:+ path = output_dir / "fingerprints.json"+ if not path.exists():+ return []+ payload = json.loads(path.read_text(encoding="utf-8"))+ return [+ SkillFingerprint.from_dict(item)+ for item in payload.get("fingerprints", [])+ if isinstance(item, dict)+ ]+++def load_io_name_vocabulary(+ output_dir: Path,+ normalizer: SkillFingerprintNormalizer,+) -> IONameVocabulary:+ path = output_dir / "io_name_vocab.json"+ if not path.exists():+ return IONameVocabulary.from_config(normalizer.config)+ return IONameVocabulary.load(path, normalizer.config)diff --git a/jiuwenswarm/symphony/fingerprint/manifest.py b/jiuwenswarm/symphony/fingerprint/manifest.pynew file mode 100644index 0000000000..961361b725--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/manifest.py@@ -0,0 +1,90 @@+"""SKILL.md parsing."""++from __future__ import annotations++import hashlib+from typing import Any, Dict, List, Tuple++import yaml++from jiuwenswarm.symphony.fingerprint.models import (+ ExtractionDiagnostic,+ RawSkillManifest,+ SkillFolder,+)+++class SkillManifestParser:+ """Parse a SkillFolder's SKILL.md into frontmatter and body."""++ def parse(self, folder: SkillFolder) -> RawSkillManifest:+ text = folder.entry.read_text(encoding="utf-8-sig")+ metadata, body, diagnostics = self._split_frontmatter(text, folder)+ body_sha256 = hashlib.sha256(body.encode("utf-8")).hexdigest()+ return RawSkillManifest(+ folder=folder,+ frontmatter=metadata,+ body=body,+ body_sha256=body_sha256,+ diagnostics=diagnostics,+ )++ def _split_frontmatter(+ self,+ text: str,+ folder: SkillFolder,+ ) -> Tuple[Dict[str, Any], str, List[ExtractionDiagnostic]]:+ diagnostics: List[ExtractionDiagnostic] = []++ try:+ metadata, body = self._load_frontmatter(text)+ except Exception as exc:+ diagnostics.append(+ ExtractionDiagnostic(+ stage="manifest",+ severity="warning",+ code="invalid_frontmatter",+ message="frontmatter could not be parsed",+ path=str(folder.path),+ details={"error": str(exc)},+ )+ )+ return {}, text, diagnostics++ if not isinstance(metadata, dict):+ diagnostics.append(+ ExtractionDiagnostic(+ stage="manifest",+ severity="warning",+ code="invalid_frontmatter",+ message="frontmatter must be a YAML mapping",+ path=str(folder.path),+ )+ )+ return {}, text, diagnostics++ return metadata, body, diagnostics++ @staticmethod+ def _load_frontmatter(text: str) -> Tuple[Any, str]:+ lines = text.splitlines()+ if not lines or lines[0].strip() != "---":+ return {}, text++ end_index = None+ for index, line in enumerate(lines[1:], start=1):+ if line.strip() == "---":+ end_index = index+ break++ if end_index is None:+ return {}, text++ frontmatter_text = "\n".join(lines[1:end_index])+ body = "\n".join(lines[end_index + 1:])+ metadata = yaml.safe_load(frontmatter_text)+ if metadata is None:+ metadata = {}+ if not isinstance(metadata, dict):+ raise ValueError("frontmatter content must be a YAML mapping")+ return metadata, bodydiff --git a/jiuwenswarm/symphony/fingerprint/models.py b/jiuwenswarm/symphony/fingerprint/models.pynew file mode 100644index 0000000000..e4a0fdbf1e--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/models.py@@ -0,0 +1,264 @@+# -*- coding: utf-8 -*-+"""Data contracts for Skill fingerprint extraction."""++from __future__ import annotations++from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Dict, List, Optional, Protocol, Union+++@dataclass(frozen=True)+class SkillFolder:+ """A discovered Skill folder with a SKILL.md entrypoint."""++ id_hint: str+ path: Path+ entry: Path+ relative_path: str+++@dataclass(frozen=True)+class ExtractionDiagnostic:+ """Structured diagnostic emitted during fingerprint extraction."""++ stage: str+ severity: str+ code: str+ message: str+ skill_id: Optional[str] = None+ path: Optional[str] = None+ details: Dict[str, Any] = field(default_factory=dict)++ def to_dict(self) -> Dict[str, Any]:+ return {+ "skill_id": self.skill_id,+ "path": self.path,+ "stage": self.stage,+ "severity": self.severity,+ "code": self.code,+ "message": self.message,+ "details": self.details,+ }+++@dataclass(frozen=True)+class RawSkillManifest:+ """Parsed SKILL.md content before LLM schema extraction."""++ folder: SkillFolder+ frontmatter: Dict[str, Any]+ body: str+ body_sha256: str+ diagnostics: List[ExtractionDiagnostic] = field(default_factory=list)+++@dataclass(frozen=True)+class ParameterSpec:+ """A Skill input parameter."""++ name: str+ type: str+ required: bool = True+ description: str = ""+ default: Any = None++ def to_dict(self) -> Dict[str, Any]:+ return {+ "name": self.name,+ "type": self.type,+ "required": self.required,+ "description": self.description,+ "default": self.default,+ }+++@dataclass(frozen=True)+class ArtifactSpec:+ """A Skill output artifact."""++ name: str+ type: str+ description: str = ""++ def to_dict(self) -> Dict[str, Any]:+ return {+ "name": self.name,+ "type": self.type,+ "description": self.description,+ }+++@dataclass(frozen=True)+class ExtractedSkillSchema:+ """LLM-extracted candidate schema before deterministic normalization."""++ description: str = ""+ inputs: List[Union[ParameterSpec, Dict[str, Any]]] = field(default_factory=list)+ outputs: List[Union[ArtifactSpec, Dict[str, Any]]] = field(default_factory=list)+ confidence: Optional[float] = None+ warnings: List[str] = field(default_factory=list)+++@dataclass(frozen=True)+class SkillFingerprint:+ """Normalized Skill fingerprint v1."""++ id: str+ name: str+ description: str+ version: str+ inputs: List[ParameterSpec]+ outputs: List[ArtifactSpec]++ def to_dict(self) -> Dict[str, Any]:+ return {+ "id": self.id,+ "name": self.name,+ "description": self.description,+ "version": self.version,+ "inputs": [item.to_dict() for item in self.inputs],+ "outputs": [item.to_dict() for item in self.outputs],+ }++ @classmethod+ def from_dict(cls, payload: Dict[str, Any]) -> "SkillFingerprint":+ return cls(+ id=str(payload.get("id") or ""),+ name=str(payload.get("name") or ""),+ description=str(payload.get("description") or ""),+ version=str(payload.get("version") or "1.0.0"),+ inputs=[+ ParameterSpec(+ name=str(item.get("name") or "input"),+ type=str(item.get("type") or "text"),+ required=bool(item.get("required", True)),+ description=str(item.get("description") or ""),+ default=item.get("default"),+ )+ for item in payload.get("inputs", [])+ ],+ outputs=[+ ArtifactSpec(+ name=str(item.get("name") or "result"),+ type=str(item.get("type") or "unknown"),+ description=str(item.get("description") or ""),+ )+ for item in payload.get("outputs", [])+ ],+ )+++@dataclass(frozen=True)+class NormalizationConfig:+ """Configuration and vocabularies used by the deterministic normalizer.++ This object owns the normalizer defaults, vocabulary versions, and optional+ alias maps. `SkillFingerprint` keeps only normalized `name` and `type`+ values; the evidence for each choice is stored in `NormalizationDecision`.++ `name` and `type` have different roles:+ - `name` is the I/O semantic term used by graph construction.+ - `type` is the data format or carrier, such as text, pdf, csv,+ or markdown.+ """++ # Dynamic vocabulary version for normalized I/O semantic names.+ io_name_vocab_version: str = "io-name-vocab-v1"++ # Optional soft cap for canonical I/O name terms. None means the+ # vocabulary can grow with the observed Skill corpus instead of forcing+ # unrelated runtime semantics into broad buckets.+ max_vocab_size: Optional[int] = None++ # Warn when a newly-created I/O name is very close to an existing term.+ # This is review guidance only; it does not force a merge.+ possible_duplicate_name_similarity_threshold: float = 0.86++ # Default Skill version when frontmatter does not declare one.+ default_version: str = "1.0.0"++ # Default input created when the extractor returns no inputs.+ default_input_name: str = "input"++ # Default type for generated fallback inputs.+ default_input_type: str = "text"++ # Default output created when the extractor returns no outputs.+ default_output_name: str = "result"++ # Type used when a data format cannot be recognized.+ unknown_type: str = "unknown"+++@dataclass(frozen=True)+class MetadataNormalizationResult:+ """Result of metadata normalization: id, name, version, description."""++ id: str+ name: str+ description: str+ version: str+++@dataclass(frozen=True)+class NormalizationDecision:+ """Trace record for a normalization choice kept outside fingerprints."""++ skill_id: str+ path: Optional[str]+ direction: str+ field: str+ raw_value: str+ token: str+ normalized_value: str+ method: str+ vocab: str+ vocab_version: str+ confidence: float+ details: Dict[str, Any] = field(default_factory=dict)++ def to_dict(self) -> Dict[str, Any]:+ return {+ "skill_id": self.skill_id,+ "path": self.path,+ "direction": self.direction,+ "field": self.field,+ "raw_value": self.raw_value,+ "token": self.token,+ "normalized_value": self.normalized_value,+ "method": self.method,+ "vocab": self.vocab,+ "vocab_version": self.vocab_version,+ "confidence": self.confidence,+ "details": self.details,+ }+++@dataclass(frozen=True)+class NormalizationResult:+ fingerprint: SkillFingerprint+ diagnostics: List[ExtractionDiagnostic]+ decisions: List[NormalizationDecision] = field(default_factory=list)+++@dataclass(frozen=True)+class FingerprintExtractionResult:+ fingerprints: List[SkillFingerprint]+ diagnostics: List[ExtractionDiagnostic]+ normalization_decisions: List[NormalizationDecision] = field(default_factory=list)+ io_name_vocab: Dict[str, Any] = field(default_factory=dict)+ llm_token_usage: Dict[str, Any] = field(default_factory=dict)+ folders: List[SkillFolder] = field(default_factory=list)+ current_hashes: Dict[str, str] = field(default_factory=dict)+ removed_paths: set[str] = field(default_factory=set)+ fingerprints_by_path: Dict[str, SkillFingerprint] = field(default_factory=dict)+ reused_count: int = 0+ extracted_count: int = 0+++class SkillSchemaExtractor(Protocol):+ """Protocol for LLM-backed schema extractors."""++ async def extract(self, manifest: RawSkillManifest) -> ExtractedSkillSchema:+ ...diff --git a/jiuwenswarm/symphony/fingerprint/normalize/__init__.py b/jiuwenswarm/symphony/fingerprint/normalize/__init__.pynew file mode 100644index 0000000000..0474b756b5--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/normalize/__init__.py@@ -0,0 +1,52 @@+"""Normalization infrastructure."""++from jiuwenswarm.symphony.fingerprint.normalize.vocabulary import (+ BaseCandidate,+ BaseResolution,+ BaseVocabTerm,+ BaseVocabulary,+ DynamicVocabulary,+ StaticVocabulary,+ term_similarity,+)+from jiuwenswarm.symphony.fingerprint.normalize.data_type_vocab import (+ DataTypeInference,+ DataTypeResolution,+ DataTypeVocabulary,+)+from jiuwenswarm.symphony.fingerprint.normalize.io_name_vocab import (+ IONameCandidate,+ IONameResolution,+ IONameResolver,+ IONameVocabTerm,+ IONameVocabulary,+)+from jiuwenswarm.symphony.fingerprint.normalize.io_name_resolver import LLMIONameResolver+from jiuwenswarm.symphony.fingerprint.normalize.metadata_normalizer import MetadataNormalizer+from jiuwenswarm.symphony.fingerprint.normalize.normalizer import SkillFingerprintNormalizer++__all__ = [+ # Metadata normalization+ "MetadataNormalizer",+ # Base vocabulary+ "BaseCandidate",+ "BaseResolution",+ "BaseVocabTerm",+ "BaseVocabulary",+ "DynamicVocabulary",+ "StaticVocabulary",+ "term_similarity",+ # DataType vocabulary+ "DataTypeInference",+ "DataTypeResolution",+ "DataTypeVocabulary",+ # I/O name vocabulary+ "IONameCandidate",+ "IONameResolution",+ "IONameResolver",+ "IONameVocabTerm",+ "IONameVocabulary",+ "LLMIONameResolver",+ # Normalizer+ "SkillFingerprintNormalizer",+]diff --git a/jiuwenswarm/symphony/fingerprint/normalize/data_type_vocab.py b/jiuwenswarm/symphony/fingerprint/normalize/data_type_vocab.pynew file mode 100644index 0000000000..126612da31--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/normalize/data_type_vocab.py@@ -0,0 +1,532 @@+"""Static vocabulary for DataType (formats/carriers).++This module defines the controlled vocabulary for data types used in+Skill I/O specifications, such as text, markdown, json, pdf, etc.+The default vocabulary is loaded from an embedded YAML resource so the+controlled vocabulary can be reviewed and maintained in one place.+"""++from __future__ import annotations++import re+from collections.abc import Iterable+from dataclasses import dataclass+from importlib import resources+from typing import Any, ClassVar, Dict, FrozenSet, List, Optional++import yaml++from jiuwenswarm.symphony.fingerprint.normalize.vocabulary import StaticVocabulary+from jiuwenswarm.symphony.fingerprint.utils import normalize_token++_VOCAB_RESOURCE_PACKAGE = __package__ or "jiuwenswarm.symphony.fingerprint.normalize"+_VOCAB_RESOURCE_NAME = "data_type_vocab.yaml"+_INFERENCE_MIN_SCORE = 0.65+_INFERENCE_TIE_EPSILON = 0.05+++@dataclass(frozen=True)+class DataTypeResolution:+ """Resolution result for DataType vocabulary lookup."""++ normalized_value: Optional[str]+ method: str+ confidence: float++ def to_dict(self) -> Dict[str, Any]:+ return {+ "normalized_value": self.normalized_value,+ "method": self.method,+ "confidence": self.confidence,+ }+++@dataclass(frozen=True)+class DataTypeInference:+ """Semantic inference result for DataType lookup."""++ data_type: str+ reason: str+ confidence: float+ evidence: Dict[str, Any]+ method: str = "semantic_score"++ def to_dict(self) -> Dict[str, Any]:+ return {+ "data_type": self.data_type,+ "reason": self.reason,+ "confidence": self.confidence,+ "evidence": self.evidence,+ "method": self.method,+ }+++@dataclass(frozen=True)+class _DataTypeDefaults:+ version: str+ vocab: FrozenSet[str]+ aliases: Dict[str, str]+ hierarchy: Dict[str, FrozenSet[str]]+ content_carrier_types: FrozenSet[str]+ markup_text_types: FrozenSet[str]+ structured_text_types: FrozenSet[str]+ type_hints: Dict[str, Dict[str, Any]]+++class DataTypeVocabulary(StaticVocabulary):+ """Static vocabulary for DataType formats/carriers.++ This vocabulary is immutable and predefined, containing common+ data formats like text, markdown, json, pdf, etc. Default terms,+ aliases, hierarchy, traits, and semantic inference hints are loaded+ from the adjacent ``data_type_vocab.yaml`` resource.++ Example usage:+ vocab = DataTypeVocabulary() # Uses defaults+ vocab.resolve("natural_language") # Returns "text"+ vocab.resolve("pdf") # Returns "pdf"+ vocab.resolve("unknown_format") # Returns normalized_value=None+ """++ VERSION: ClassVar[str] = "data-type-v1"+ DEFAULT_VOCAB: ClassVar[FrozenSet[str]]+ DEFAULT_ALIASES: ClassVar[Dict[str, str]]+ TYPE_HIERARCHY: ClassVar[Dict[str, FrozenSet[str]]]+ CONTENT_CARRIER_TYPES: ClassVar[FrozenSet[str]]+ MARKUP_TEXT_TYPES: ClassVar[FrozenSet[str]]+ STRUCTURED_TEXT_TYPES: ClassVar[FrozenSet[str]]+ TYPE_HINTS: ClassVar[Dict[str, Dict[str, Any]]]+ _DEFAULTS: ClassVar[_DataTypeDefaults]++ @classmethod+ def install_defaults(cls, defaults: _DataTypeDefaults) -> None:+ cls.VERSION = defaults.version+ cls._DEFAULTS = defaults+ cls.DEFAULT_VOCAB = defaults.vocab+ cls.DEFAULT_ALIASES = defaults.aliases+ cls.TYPE_HIERARCHY = defaults.hierarchy+ cls.CONTENT_CARRIER_TYPES = defaults.content_carrier_types+ cls.MARKUP_TEXT_TYPES = defaults.markup_text_types+ cls.STRUCTURED_TEXT_TYPES = defaults.structured_text_types+ cls.TYPE_HINTS = defaults.type_hints++ def __init__(+ self,+ version: Optional[str] = None,+ vocab: Optional[FrozenSet[str]] = None,+ aliases: Optional[Dict[str, str]] = None,+ ) -> None:+ """Initialize DataTypeVocabulary with optional custom parameters.++ Args:+ version: Vocabulary version string. Defaults to VERSION.+ vocab: Set of canonical vocabulary terms. Defaults to DEFAULT_VOCAB.+ aliases: Alias mappings. Defaults to DEFAULT_ALIASES.+ """+ base_aliases = aliases or self.DEFAULT_ALIASES+ normalized_aliases = dict(base_aliases)+ for alias, target in base_aliases.items():+ token = normalize_token(alias)+ if token:+ existing = normalized_aliases.get(token)+ if existing is not None and existing != target:+ raise ValueError(+ f"DataType alias '{alias}' normalizes to '{token}', "+ f"which already maps to '{existing}', not '{target}'."+ )+ normalized_aliases[token] = target++ super().__init__(+ version=version or self.VERSION,+ vocab=vocab or self.DEFAULT_VOCAB,+ aliases=normalized_aliases,+ )++ @classmethod+ def default(cls) -> "DataTypeVocabulary":+ """Create the default DataType vocabulary with predefined terms and aliases."""+ return cls(+ version=cls.VERSION,+ vocab=cls.DEFAULT_VOCAB,+ aliases=cls.DEFAULT_ALIASES,+ )++ @classmethod+ def from_config(cls, config: Any) -> "DataTypeVocabulary":+ """Build vocabulary from NormalizationConfig.++ Uses the default vocabulary terms. If config provides custom+ aliases via data_type_aliases, they are merged with defaults.+ """+ aliases = cls.DEFAULT_ALIASES+ if hasattr(config, "data_type_aliases") and config.data_type_aliases:+ aliases = {**cls.DEFAULT_ALIASES, **config.data_type_aliases}+ return cls(+ version=cls.VERSION,+ vocab=cls.DEFAULT_VOCAB,+ aliases=aliases,+ )++ @classmethod+ def with_custom_aliases(+ cls,+ aliases: Dict[str, str],+ ) -> "DataTypeVocabulary":+ """Create a DataType vocabulary with additional custom aliases.++ Custom aliases are merged with the default aliases. If a custom alias+ conflicts with a default alias, the custom alias takes precedence.++ Args:+ aliases: Additional alias mappings to add.++ Returns:+ A new DataTypeVocabulary instance with merged aliases.+ """+ merged_aliases = {**cls.DEFAULT_ALIASES, **aliases}+ return cls(+ version=cls.VERSION,+ vocab=cls.DEFAULT_VOCAB,+ aliases=merged_aliases,+ )++ @property+ def unknown_type(self) -> str:+ """Return the unknown type marker."""+ return "unknown"++ def resolve(self, raw_token: str) -> DataTypeResolution:+ """Resolve a raw token to a canonical vocabulary term.++ Returns a DataTypeResolution with the normalized value, method,+ and confidence score.+ """+ normalized = raw_token.lower().strip()+ token = normalize_token(raw_token)+ if normalized in self.vocab or token in self.vocab:+ return DataTypeResolution(+ normalized_value=normalized if normalized in self.vocab else token,+ method="exact",+ confidence=1.0,+ )+ alias_result = self.aliases.get(normalized) or self.aliases.get(token)+ if alias_result and alias_result in self.vocab:+ return DataTypeResolution(+ normalized_value=alias_result,+ method="alias_map",+ confidence=0.95,+ )+ return DataTypeResolution(+ normalized_value=None,+ method="unknown",+ confidence=0.0,+ )++ def contains(self, token: str) -> bool:+ """Check if a token is in the vocabulary (canonical or alias)."""+ normalized = token.lower().strip()+ normalized_token = normalize_token(token)+ return (+ normalized in self.vocab+ or normalized in self.aliases+ or normalized_token in self.vocab+ or normalized_token in self.aliases+ )++ def infer_from_io_semantics(+ self,+ io_name: str,+ description: str,+ ) -> Optional[DataTypeInference]:+ """Infer a DataType from I/O name and description evidence."""+ name_token = normalize_token(io_name)+ description_token = normalize_token(description)+ name_tokens = _semantic_tokens(io_name)+ description_tokens = _semantic_tokens(description)+ all_tokens = name_tokens | description_tokens++ candidates: List[Dict[str, Any]] = []+ for target in sorted(self.vocab):+ if target == self.unknown_type:+ continue+ score, evidence = _score_inference_candidate(+ target=target,+ aliases=self.aliases,+ hints=self.TYPE_HINTS.get(target, {}),+ name_token=name_token,+ description_token=description_token,+ name_tokens=name_tokens,+ description_tokens=description_tokens,+ all_tokens=all_tokens,+ )+ if score < _INFERENCE_MIN_SCORE:+ continue+ candidates.append(+ {+ "target": target,+ "score": score,+ "evidence": evidence,+ }+ )+ if not candidates:+ return None++ candidates.sort(key=lambda item: (-float(item["score"]), str(item["target"])))+ winner = candidates[0]+ if (+ len(candidates) > 1+ and float(winner["score"]) - float(candidates[1]["score"])+ <= _INFERENCE_TIE_EPSILON+ ):+ return None++ target = str(winner["target"])+ score = float(winner["score"])+ evidence = dict(winner["evidence"])+ evidence["score"] = round(score, 4)+ if len(candidates) > 1:+ evidence["runner_up"] = {+ "data_type": candidates[1]["target"],+ "score": round(float(candidates[1]["score"]), 4),+ }+ confidence = min(0.95, round(0.5 + score / 4.0, 4))+ return DataTypeInference(+ data_type=target,+ reason=f"semantic evidence matched DataType '{target}'",+ confidence=confidence,+ evidence=evidence,+ )++ def is_subtype(self, sub_type: str, super_type: str) -> bool:+ """Check if sub_type is a subtype of super_type in the type hierarchy.++ This method supports transitive hierarchy checks. For example,+ is_subtype("png", "file") returns True because:+ png -> image -> file++ Args:+ sub_type: The potential subtype to check.+ super_type: The potential supertype to check against.++ Returns:+ True if sub_type is a (direct or transitive) subtype of super_type,+ False otherwise.+ """+ if super_type not in self.TYPE_HIERARCHY:+ return False+ children = self.TYPE_HIERARCHY[super_type]+ if sub_type in children:+ return True+ return any(self.is_subtype(sub_type, child) for child in children)++ def can_feed_by_type(self, output_type: str, input_type: str) -> bool:+ """Check if output_type can feed into input_type.++ This implements the type compatibility logic for Skill graph construction:+ 1. Unknown types cannot feed+ 2. Same types can always feed+ 3. Subtypes can feed to their supertypes+ 4. Textual carriers can feed generic text inputs+ 5. Closely related text formats can interoperate conservatively++ Args:+ output_type: The type of the output artifact.+ input_type: The type of the input parameter.++ Returns:+ True if the output type can satisfy the input type requirement.+ """+ if output_type == "unknown" or input_type == "unknown":+ return False+ if output_type == input_type:+ return True+ if self.is_subtype(output_type, input_type):+ return True+ if input_type == "text" and output_type in self.CONTENT_CARRIER_TYPES:+ return True+ if output_type == "text" and input_type in self.MARKUP_TEXT_TYPES:+ return True+ if output_type in self.MARKUP_TEXT_TYPES and input_type in self.MARKUP_TEXT_TYPES:+ return True+ if (+ output_type in self.STRUCTURED_TEXT_TYPES+ and input_type in self.STRUCTURED_TEXT_TYPES+ ):+ return True+ return False+++def _load_default_data_type_defaults() -> _DataTypeDefaults:+ raw = _load_default_vocab_resource()+ version = str(raw.get("version") or DataTypeVocabulary.VERSION)+ types = raw.get("types")+ if not isinstance(types, dict) or not types:+ raise ValueError(+ "DataType vocabulary YAML must define a non-empty 'types' mapping."+ )++ vocab = frozenset(str(name).strip() for name in types if str(name).strip())+ aliases: Dict[str, str] = {}+ hierarchy: Dict[str, set[str]] = {}+ traits: Dict[str, set[str]] = {}+ type_hints: Dict[str, Dict[str, Any]] = {}++ for raw_name, raw_spec in types.items():+ name = str(raw_name).strip()+ if not name:+ continue+ spec = raw_spec if isinstance(raw_spec, dict) else {}+ for alias in _string_list(spec.get("aliases")):+ aliases[alias] = name+ for parent in _string_list(spec.get("parents")):+ if parent not in vocab:+ raise ValueError(+ f"DataType vocabulary parent '{parent}' for '{name}' is not a canonical type."+ )+ hierarchy.setdefault(parent, set()).add(name)+ for trait in _string_list(spec.get("traits")):+ traits.setdefault(trait, set()).add(name)+ hints = spec.get("hints")+ if hints is not None:+ if not isinstance(hints, dict):+ raise ValueError(+ f"DataType vocabulary hints for '{name}' must be a mapping."+ )+ type_hints[name] = {+ "name_terms": frozenset(_normalized_items(hints.get("name_terms"))),+ "description_terms": frozenset(+ _normalized_items(hints.get("description_terms"))+ ),+ "suffixes": tuple(_normalized_suffixes(hints.get("suffixes"))),+ "requires_any": frozenset(_normalized_items(hints.get("requires_any"))),+ }++ return _DataTypeDefaults(+ version=version,+ vocab=vocab,+ aliases=aliases,+ hierarchy={key: frozenset(value) for key, value in hierarchy.items()},+ content_carrier_types=frozenset(traits.get("content_carrier", set())),+ markup_text_types=frozenset(traits.get("markup_text", set())),+ structured_text_types=frozenset(traits.get("structured_text", set())),+ type_hints=type_hints,+ )+++def _load_default_vocab_resource() -> Dict[str, Any]:+ resource = resources.files(_VOCAB_RESOURCE_PACKAGE).joinpath(_VOCAB_RESOURCE_NAME)+ data = yaml.safe_load(resource.read_text(encoding="utf-8"))+ if not isinstance(data, dict):+ raise ValueError("DataType vocabulary YAML must contain a mapping.")+ return data+++def _string_list(value: Any) -> List[str]:+ if value is None:+ return []+ if not isinstance(value, Iterable) or isinstance(value, (str, bytes)):+ item = str(value).strip()+ return [item] if item else []+ return [str(item).strip() for item in value if str(item).strip()]+++def _normalized_items(value: Any) -> List[str]:+ return [normalize_token(item) for item in _string_list(value) if normalize_token(item)]+++def _normalized_suffixes(value: Any) -> List[str]:+ suffixes: List[str] = []+ for item in _string_list(value):+ suffix = normalize_token(item)+ if suffix:+ suffixes.append(f"_{suffix}" if not suffix.startswith("_") else suffix)+ return suffixes+++def _semantic_tokens(value: str) -> set[str]:+ token = normalize_token(value)+ if not token:+ return set()+ parts = token.split("_")+ tokens = set(parts)+ tokens.add(token)+ for size in (2, 3):+ for index in range(0, max(0, len(parts) - size + 1)):+ tokens.add("_".join(parts[index: index + size]))+ for raw_match in re.findall(r"[A-Za-z0-9.+-]+/[A-Za-z0-9.+-]+", value):+ raw_token = normalize_token(raw_match)+ if raw_token:+ tokens.add(raw_token)+ return tokens+++def _score_inference_candidate(+ *,+ target: str,+ aliases: Dict[str, str],+ hints: Dict[str, Any],+ name_token: str,+ description_token: str,+ name_tokens: set[str],+ description_tokens: set[str],+ all_tokens: set[str],+) -> tuple[float, Dict[str, Any]]:+ required = set(hints.get("requires_any", frozenset()))+ if required and not required.intersection(all_tokens):+ return 0.0, {}++ evidence: Dict[str, Any] = {+ "name_token": name_token,+ "description_token": description_token,+ "matches": {},+ }+ score = 0.0+ matched_terms: set[str] = set()++ def add(amount: float, key: str, values: Iterable[str]) -> None:+ nonlocal score+ clean_values = sorted({value for value in values if value})+ if not clean_values:+ return+ score += amount+ evidence["matches"][key] = clean_values+ matched_terms.update(clean_values)++ if name_token == target:+ add(0.95, "name_exact", [target])+ if target in name_tokens:+ add(0.75, "name_type_term", [target])+ if target in description_tokens:+ add(0.65, "description_type_term", [target])++ alias_tokens = {+ normalize_token(alias)+ for alias, mapped_target in aliases.items()+ if mapped_target == target and normalize_token(alias)+ }+ add(0.85, "name_alias", alias_tokens & name_tokens)+ add(0.65, "description_alias", alias_tokens & description_tokens)++ suffixes = tuple(hints.get("suffixes", ()))+ add(+ 0.7,+ "name_suffix",+ [suffix for suffix in suffixes if name_token.endswith(suffix)],+ )++ name_term_matches = set(hints.get("name_terms", frozenset())) & name_tokens+ add(0.45, "name_hint", name_term_matches)++ description_term_matches = (+ set(hints.get("description_terms", frozenset())) & description_tokens+ )+ if description_term_matches:+ amount = min(0.5, 0.25 * len(description_term_matches))+ add(amount, "description_hint", description_term_matches)++ evidence["matched_terms"] = sorted(matched_terms)+ return score, evidence+++_DEFAULTS = _load_default_data_type_defaults()+DataTypeVocabulary.install_defaults(_DEFAULTS)diff --git a/jiuwenswarm/symphony/fingerprint/normalize/data_type_vocab.yaml b/jiuwenswarm/symphony/fingerprint/normalize/data_type_vocab.yamlnew file mode 100644index 0000000000..b9f8403d4a--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/normalize/data_type_vocab.yaml@@ -0,0 +1,349 @@+version: data-type-v1++# This file is the single source of truth for DataType normalization.+#+# Field guide:+# - types: Canonical DataType names accepted by fingerprints and graph matching.+# - aliases: Raw spellings that should normalize to the canonical type. MIME types+# such as "application/json" are intentionally kept here for human readability;+# the Python loader also registers their normalize_token form, e.g.+# "application_json".+# - parents: Direct supertypes. The loader derives TYPE_HIERARCHY from these+# parent links, so maintainers do not need to update a second structure.+# - traits: Behavioral tags used by compatibility rules. They are not user-facing+# taxonomy labels.+# - content_carrier: text-like content that can satisfy a generic text input.+# - markup_text: lightweight markup formats such as HTML and Markdown.+# - structured_text: parseable structured text such as JSON, XML, and YAML.+# - hints: Optional generic scoring hints used only when the extracted raw type+# is unknown or unsupported. Hints do not define a type-specific algorithm;+# they only add evidence to the shared semantic scorer.+# - name_terms: Terms in an I/O name that support this type.+# - description_terms: Terms in a description that support this type.+# - suffixes: I/O name suffixes that support this type, such as "_url".+# - requires_any: Optional guard; at least one listed term must appear in the+# I/O name or description before this type can be inferred.++types:+ text:+ aliases:+ - natural_language+ - natural_language_query+ - plain_text+ - txt+ - text/plain+ traits:+ - content_carrier++ markdown:+ aliases:+ - md+ - text/markdown+ parents:+ - text+ traits:+ - content_carrier+ - markup_text++ json:+ aliases:+ - json_object+ - application/json+ - text/json+ parents:+ - file+ - text+ traits:+ - content_carrier+ - structured_text++ csv:+ aliases:+ - text/csv+ - application/csv+ parents:+ - file+ - table+ - text+ traits:+ - content_carrier++ table:+ aliases:+ - tabular_data+ - table_data+ - data_table+ - dataframe+ - rows+ - records+ parents:+ - text+ traits:+ - content_carrier++ yaml:+ aliases:+ - yml+ - application/yaml+ - application/x-yaml+ - text/yaml+ parents:+ - file+ - text+ traits:+ - content_carrier+ - structured_text++ xml:+ aliases:+ - xml_document+ - application/xml+ - text/xml+ parents:+ - file+ - text+ traits:+ - content_carrier+ - structured_text++ pdf:+ aliases:+ - application/pdf+ parents:+ - file++ html:+ aliases:+ - text/html+ - application/xhtml+xml+ parents:+ - file+ - text+ traits:+ - content_carrier+ - markup_text++ docx:+ aliases:+ - word+ - word_document+ - msword+ - doc+ parents:+ - file++ pptx:+ aliases:+ - slides+ - deck+ - presentation+ - powerpoint+ - ppt+ parents:+ - file++ xlsx:+ aliases:+ - excel+ - workbook+ - xls+ parents:+ - file+ - table++ image:+ aliases:+ - photo+ - picture+ - screenshot+ - scan+ - scanned_image+ - images+ parents:+ - file+ hints:+ name_terms:+ - image+ - photo+ - picture+ - screenshot+ - scan+ description_terms:+ - image+ - images+ - photo+ - picture+ - screenshot+ - scan+ - base64+ - bmp+ - gif+ - jpeg+ - jpg+ - png+ - svg+ - tiff+ - wbmp+ - webp+ suffixes:+ - _image+ - _photo+ - _picture+ - _screenshot+ - _scan+ requires_any:+ - image+ - images+ - photo+ - picture+ - screenshot+ - scan+ - base64+ - bmp+ - gif+ - jpeg+ - jpg+ - png+ - svg+ - tiff+ - wbmp+ - webp++ png:+ aliases:+ - image/png+ parents:+ - image++ jpg:+ aliases:+ - image/jpg+ - image/jpeg+ - jpeg+ parents:+ - image++ svg:+ aliases:+ - image/svg+xml+ parents:+ - image++ webp:+ aliases:+ - image/webp+ parents:+ - image++ gif:+ aliases:+ - image/gif+ parents:+ - image++ url:+ aliases:+ - link+ - uri+ - webpage+ - http_url+ - https_url+ - image_url+ - remote_url+ - download_url+ - source_url+ - file_url+ hints:+ name_terms:+ - url+ - uri+ - link+ - remote_url+ - download_url+ - source_url+ - file_url+ description_terms:+ - http+ - https+ - link+ - url+ - uri+ - webpage+ - remote_url+ - download_url+ - source_url+ - file_url+ suffixes:+ - _url+ - _uri+ - _link+ requires_any:+ - http+ - https+ - link+ - url+ - uri+ - webpage+ - remote_url+ - download_url+ - source_url+ - file_url+ file: {}++ path:+ aliases:+ - file_path+ - filepath+ - folder_path+ - directory_path+ parents:+ - file++ audio:+ aliases:+ - mp3+ - wav+ - m4a+ - audio/mpeg+ - audio/wav+ parents:+ - file++ video:+ aliases:+ - mp4+ - mov+ - webm+ - video/mp4+ - video/webm+ parents:+ - file++ code:+ aliases:+ - source_code+ - code_file+ - kernel_code+ - operator_code+ - cpp_code+ - python_code+ - javascript_code+ - program+ - shell_script+ parents:+ - file+ - text+ traits:+ - content_carrier++ archive:+ aliases:+ - zip+ - tar+ - tar_gz+ - tgz+ - application/zip+ parents:+ - file++ unknown: {}diff --git a/jiuwenswarm/symphony/fingerprint/normalize/data_types.py b/jiuwenswarm/symphony/fingerprint/normalize/data_types.pynew file mode 100644index 0000000000..93e78c2c86--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/normalize/data_types.py@@ -0,0 +1,223 @@+"""DataType normalization for Skill fingerprint fields."""++from __future__ import annotations++from dataclasses import dataclass+from typing import List++from jiuwenswarm.symphony.fingerprint.models import (+ ExtractionDiagnostic,+ NormalizationConfig,+ NormalizationDecision,+ RawSkillManifest,+ SkillFingerprint,+)+from jiuwenswarm.symphony.fingerprint.normalize.data_type_vocab import (+ DataTypeInference,+ DataTypeVocabulary,+)+from jiuwenswarm.symphony.fingerprint.normalize.decisions import (+ NormalizationDecisionRecorder,+)+from jiuwenswarm.symphony.fingerprint.utils import normalize_token+++@dataclass(frozen=True)+class DataTypeNormalizationContext:+ io_name: str+ description: str+ manifest: RawSkillManifest+ skill_id: str+ direction: str+ diagnostics: List[ExtractionDiagnostic]+ decisions: List[NormalizationDecision]+++class DataTypeNormalizer:+ """Normalize artifact carrier/format types against DataTypeVocabulary."""++ def __init__(+ self,+ config: NormalizationConfig,+ vocabulary: DataTypeVocabulary,+ recorder: NormalizationDecisionRecorder,+ ) -> None:+ self.config = config+ self.vocabulary = vocabulary+ self.recorder = recorder++ def normalize(+ self,+ raw_type: str,+ context: DataTypeNormalizationContext,+ ) -> str:+ token = normalize_token(raw_type)+ resolution = self.vocabulary.resolve(token)+ if resolution.normalized_value == self.vocabulary.unknown_type:+ inferred = self.vocabulary.infer_from_io_semantics(+ context.io_name,+ context.description,+ )+ if inferred is not None:+ context.diagnostics.append(+ ExtractionDiagnostic(+ stage="normalization",+ severity="info",+ code="unknown_type_inferred",+ message="unknown artifact type inferred from I/O semantics",+ skill_id=context.skill_id,+ path=str(context.manifest.folder.path),+ details={+ "original_type": raw_type,+ "normalized_token": token,+ "inferred_type": inferred.data_type,+ "io_name": context.io_name,+ "method": inferred.method,+ "confidence": inferred.confidence,+ "reason": inferred.reason,+ "evidence": inferred.evidence,+ },+ )+ )+ self._record_inference(+ context,+ raw_type,+ token,+ inferred,+ )+ return inferred.data_type+ if resolution.normalized_value is not None:+ self.recorder.record(+ context.decisions,+ skill_id=context.skill_id,+ path=str(context.manifest.folder.path),+ direction=context.direction,+ field="type",+ raw_value=raw_type,+ token=token,+ normalized_value=resolution.normalized_value,+ method=resolution.method,+ vocab="data_type_vocab",+ vocab_version=self.vocabulary.version,+ confidence=resolution.confidence,+ )+ return resolution.normalized_value++ inferred = self.vocabulary.infer_from_io_semantics(+ context.io_name,+ context.description,+ )+ if inferred is not None:+ context.diagnostics.append(+ ExtractionDiagnostic(+ stage="normalization",+ severity="info",+ code="unsupported_type_inferred",+ message="unsupported artifact type inferred from I/O semantics",+ skill_id=context.skill_id,+ path=str(context.manifest.folder.path),+ details={+ "original_type": raw_type,+ "normalized_token": token,+ "inferred_type": inferred.data_type,+ "io_name": context.io_name,+ "method": inferred.method,+ "confidence": inferred.confidence,+ "reason": inferred.reason,+ "evidence": inferred.evidence,+ },+ )+ )+ self._record_inference(+ context,+ raw_type,+ token,+ inferred,+ )+ return inferred.data_type++ context.diagnostics.append(+ ExtractionDiagnostic(+ stage="normalization",+ severity="warning",+ code="unsupported_type_normalized",+ message="artifact type is not supported; normalized to unknown",+ skill_id=context.skill_id,+ path=str(context.manifest.folder.path),+ details={"original_type": raw_type, "normalized_token": token},+ )+ )+ self.recorder.record(+ context.decisions,+ skill_id=context.skill_id,+ path=str(context.manifest.folder.path),+ direction=context.direction,+ field="type",+ raw_value=raw_type,+ token=token,+ normalized_value=self.vocabulary.unknown_type,+ method="unknown",+ vocab="data_type_vocab",+ vocab_version=self.vocabulary.version,+ confidence=0.0,+ )+ return self.vocabulary.unknown_type++ def validate(+ self,+ fingerprint: SkillFingerprint,+ manifest: RawSkillManifest,+ diagnostics: List[ExtractionDiagnostic],+ ) -> None:+ if not fingerprint.outputs:+ diagnostics.append(+ ExtractionDiagnostic(+ stage="normalization",+ severity="error",+ code="schema_validation_failed",+ message="outputs must not be empty",+ skill_id=fingerprint.id,+ path=str(manifest.folder.path),+ )+ )+ for item in [*fingerprint.inputs, *fingerprint.outputs]:+ if not self.vocabulary.contains(item.type):+ diagnostics.append(+ ExtractionDiagnostic(+ stage="normalization",+ severity="error",+ code="schema_validation_failed",+ message="type is outside DataType vocabulary",+ skill_id=fingerprint.id,+ path=str(manifest.folder.path),+ details={"type": item.type},+ )+ )++ def _record_inference(+ self,+ context: DataTypeNormalizationContext,+ raw_type: str,+ token: str,+ inferred: DataTypeInference,+ ) -> None:+ self.recorder.record(+ context.decisions,+ skill_id=context.skill_id,+ path=str(context.manifest.folder.path),+ direction=context.direction,+ field="type",+ raw_value=raw_type,+ token=token,+ normalized_value=inferred.data_type,+ method=inferred.method,+ vocab="data_type_vocab",+ vocab_version=self.vocabulary.version,+ confidence=inferred.confidence,+ details={+ "reason": inferred.reason,+ "io_name": context.io_name,+ "method": inferred.method,+ "evidence": inferred.evidence,+ },+ )diff --git a/jiuwenswarm/symphony/fingerprint/normalize/decisions.py b/jiuwenswarm/symphony/fingerprint/normalize/decisions.pynew file mode 100644index 0000000000..d01f8ee432--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/normalize/decisions.py@@ -0,0 +1,45 @@+"""Normalization decision recording helpers."""++from __future__ import annotations++from typing import Any, Dict, List, Optional++from jiuwenswarm.symphony.fingerprint.models import NormalizationDecision+++class NormalizationDecisionRecorder:+ """Append structured normalization decisions to a trace list."""++ @staticmethod+ def record(+ decisions: List[NormalizationDecision],+ *,+ skill_id: str,+ path: Optional[str],+ direction: str,+ field: str,+ raw_value: str,+ token: str,+ normalized_value: str,+ method: str,+ vocab: str,+ vocab_version: str,+ confidence: float,+ details: Optional[Dict[str, Any]] = None,+ ) -> None:+ decisions.append(+ NormalizationDecision(+ skill_id=skill_id,+ path=path,+ direction=direction,+ field=field,+ raw_value=raw_value,+ token=token,+ normalized_value=normalized_value,+ method=method,+ vocab=vocab,+ vocab_version=vocab_version,+ confidence=confidence,+ details=details or {},+ )+ )diff --git a/jiuwenswarm/symphony/fingerprint/normalize/fields.py b/jiuwenswarm/symphony/fingerprint/normalize/fields.pynew file mode 100644index 0000000000..2bea37f366--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/normalize/fields.py@@ -0,0 +1,412 @@+"""Input and output field normalization."""++from __future__ import annotations++from typing import Any, Dict, List, Tuple, Union++from jiuwenswarm.symphony.fingerprint.models import (+ ArtifactSpec,+ ExtractionDiagnostic,+ NormalizationConfig,+ NormalizationDecision,+ ParameterSpec,+ RawSkillManifest,+)+from jiuwenswarm.symphony.fingerprint.normalize.data_types import (+ DataTypeNormalizationContext,+ DataTypeNormalizer,+)+from jiuwenswarm.symphony.fingerprint.normalize.decisions import (+ NormalizationDecisionRecorder,+)+from jiuwenswarm.symphony.fingerprint.normalize.io_names import (+ IONameNormalizationContext,+ IONameNormalizer,+)+from jiuwenswarm.symphony.fingerprint.utils import to_dict+++class SchemaFieldNormalizer:+ """Normalize extracted input/output fields into fingerprint specs."""++ def __init__(+ self,+ config: NormalizationConfig,+ io_names: IONameNormalizer,+ data_types: DataTypeNormalizer,+ recorder: NormalizationDecisionRecorder,+ ) -> None:+ self.config = config+ self.io_names = io_names+ self.data_types = data_types+ self.recorder = recorder++ async def normalize_inputs(+ self,+ raw_inputs: List[Union[ParameterSpec, Dict[str, Any]]],+ manifest: RawSkillManifest,+ skill_id: str,+ diagnostics: List[ExtractionDiagnostic],+ decisions: List[NormalizationDecision],+ ) -> List[ParameterSpec]:+ if not raw_inputs:+ return self._default_inputs(manifest, skill_id, diagnostics, decisions)++ inputs: List[ParameterSpec] = []+ for raw in raw_inputs:+ data = to_dict(raw)+ raw_type = str(data.get("type") or self.config.default_input_type)+ raw_name = str(data.get("name") or self.config.default_input_name)+ description = str(data.get("description") or "")+ name = await self.io_names.normalize(+ raw_name,+ IONameNormalizationContext(+ raw_type=raw_type,+ description=description,+ manifest=manifest,+ skill_id=skill_id,+ direction="input",+ diagnostics=diagnostics,+ decisions=decisions,+ ),+ )+ if name is None:+ continue+ data_type = self.data_types.normalize(+ raw_type,+ DataTypeNormalizationContext(+ io_name=name,+ description=description,+ manifest=manifest,+ skill_id=skill_id,+ direction="input",+ diagnostics=diagnostics,+ decisions=decisions,+ ),+ )+ inputs.append(+ ParameterSpec(+ name=name,+ type=data_type,+ required=bool(data.get("required", True)),+ description=description,+ default=data.get("default"),+ )+ )+ return self._deduplicate_inputs(inputs, manifest, skill_id, diagnostics)++ async def normalize_outputs(+ self,+ raw_outputs: List[Union[ArtifactSpec, Dict[str, Any]]],+ manifest: RawSkillManifest,+ skill_id: str,+ diagnostics: List[ExtractionDiagnostic],+ decisions: List[NormalizationDecision],+ ) -> List[ArtifactSpec]:+ if not raw_outputs:+ return self._default_outputs(manifest, skill_id, diagnostics, decisions)++ outputs: List[ArtifactSpec] = []+ for raw in raw_outputs:+ data = to_dict(raw)+ raw_type = str(data.get("type") or self.config.unknown_type)+ raw_name = str(data.get("name") or self.config.default_output_name)+ description = str(data.get("description") or "")+ name = await self.io_names.normalize(+ raw_name,+ IONameNormalizationContext(+ raw_type=raw_type,+ description=description,+ manifest=manifest,+ skill_id=skill_id,+ direction="output",+ diagnostics=diagnostics,+ decisions=decisions,+ ),+ )+ if name is None:+ continue+ data_type = self.data_types.normalize(+ raw_type,+ DataTypeNormalizationContext(+ io_name=name,+ description=description,+ manifest=manifest,+ skill_id=skill_id,+ direction="output",+ diagnostics=diagnostics,+ decisions=decisions,+ ),+ )+ outputs.append(+ ArtifactSpec(+ name=name,+ type=data_type,+ description=description,+ )+ )+ return self._deduplicate_outputs(outputs, manifest, skill_id, diagnostics)++ def _default_inputs(+ self,+ manifest: RawSkillManifest,+ skill_id: str,+ diagnostics: List[ExtractionDiagnostic],+ decisions: List[NormalizationDecision],+ ) -> List[ParameterSpec]:+ diagnostics.append(+ ExtractionDiagnostic(+ stage="normalization",+ severity="warning",+ code="default_input_created",+ message="inputs missing; created default text input",+ skill_id=skill_id,+ path=str(manifest.folder.path),+ )+ )+ self.recorder.record(+ decisions,+ skill_id=skill_id,+ path=str(manifest.folder.path),+ direction="input",+ field="name",+ raw_value=self.config.default_input_name,+ token=self.config.default_input_name,+ normalized_value=self.config.default_input_name,+ method="default",+ vocab="io_name_vocab",+ vocab_version=self.config.io_name_vocab_version,+ confidence=1.0,+ )+ self.recorder.record(+ decisions,+ skill_id=skill_id,+ path=str(manifest.folder.path),+ direction="input",+ field="type",+ raw_value=self.config.default_input_type,+ token=self.config.default_input_type,+ normalized_value=self.config.default_input_type,+ method="default",+ vocab="data_type_vocab",+ vocab_version=self.data_types.vocabulary.version,+ confidence=1.0,+ )+ return [+ ParameterSpec(+ name=self.config.default_input_name,+ type=self.config.default_input_type,+ required=True,+ description="Default text input",+ default=None,+ )+ ]++ def _default_outputs(+ self,+ manifest: RawSkillManifest,+ skill_id: str,+ diagnostics: List[ExtractionDiagnostic],+ decisions: List[NormalizationDecision],+ ) -> List[ArtifactSpec]:+ diagnostics.append(+ ExtractionDiagnostic(+ stage="normalization",+ severity="warning",+ code="unknown_output_created",+ message="outputs missing; created unknown result output",+ skill_id=skill_id,+ path=str(manifest.folder.path),+ )+ )+ self.recorder.record(+ decisions,+ skill_id=skill_id,+ path=str(manifest.folder.path),+ direction="output",+ field="name",+ raw_value=self.config.default_output_name,+ token=self.config.default_output_name,+ normalized_value=self.config.default_output_name,+ method="default",+ vocab="io_name_vocab",+ vocab_version=self.config.io_name_vocab_version,+ confidence=1.0,+ )+ self.recorder.record(+ decisions,+ skill_id=skill_id,+ path=str(manifest.folder.path),+ direction="output",+ field="type",+ raw_value=self.config.unknown_type,+ token=self.config.unknown_type,+ normalized_value=self.config.unknown_type,+ method="default_unknown",+ vocab="data_type_vocab",+ vocab_version=self.data_types.vocabulary.version,+ confidence=0.0,+ )+ return [+ ArtifactSpec(+ name=self.config.default_output_name,+ type=self.config.unknown_type,+ description="Unknown output",+ )+ ]++ def _deduplicate_inputs(+ self,+ inputs: List[ParameterSpec],+ manifest: RawSkillManifest,+ skill_id: str,+ diagnostics: List[ExtractionDiagnostic],+ ) -> List[ParameterSpec]:+ merged: List[ParameterSpec] = []+ by_name: Dict[str, int] = {}+ for item in inputs:+ existing_index = by_name.get(item.name)+ if existing_index is None:+ by_name[item.name] = len(merged)+ merged.append(item)+ continue++ existing = merged[existing_index]+ merged_item, details = self._merge_input(existing, item)+ merged[existing_index] = merged_item+ diagnostics.append(+ ExtractionDiagnostic(+ stage="normalization",+ severity="warning",+ code="duplicate_input_merged",+ message="duplicate normalized input name was merged",+ skill_id=skill_id,+ path=str(manifest.folder.path),+ details={+ "name": item.name,+ "merged_type": merged_item.type,+ **details,+ },+ )+ )+ return merged++ def _deduplicate_outputs(+ self,+ outputs: List[ArtifactSpec],+ manifest: RawSkillManifest,+ skill_id: str,+ diagnostics: List[ExtractionDiagnostic],+ ) -> List[ArtifactSpec]:+ merged: List[ArtifactSpec] = []+ by_name: Dict[str, int] = {}+ for item in outputs:+ existing_index = by_name.get(item.name)+ if existing_index is None:+ by_name[item.name] = len(merged)+ merged.append(item)+ continue++ existing = merged[existing_index]+ merged_item, details = self._merge_output(existing, item)+ merged[existing_index] = merged_item+ diagnostics.append(+ ExtractionDiagnostic(+ stage="normalization",+ severity="warning",+ code="duplicate_output_merged",+ message="duplicate normalized output name was merged",+ skill_id=skill_id,+ path=str(manifest.folder.path),+ details={+ "name": item.name,+ "merged_type": merged_item.type,+ **details,+ },+ )+ )+ return merged++ def _merge_input(+ self,+ existing: ParameterSpec,+ incoming: ParameterSpec,+ ) -> Tuple[ParameterSpec, Dict[str, Any]]:+ merged_type, details = self._merge_type(existing.type, incoming.type)+ default, default_conflict = self._merge_optional_value(+ existing.default,+ incoming.default,+ )+ details.update(+ {+ "required_values": [existing.required, incoming.required],+ "default_conflict": default_conflict,+ }+ )+ return (+ ParameterSpec(+ name=existing.name,+ type=merged_type,+ required=existing.required or incoming.required,+ description=self._merge_description(+ existing.description,+ incoming.description,+ ),+ default=default,+ ),+ details,+ )++ def _merge_output(+ self,+ existing: ArtifactSpec,+ incoming: ArtifactSpec,+ ) -> Tuple[ArtifactSpec, Dict[str, Any]]:+ merged_type, details = self._merge_type(existing.type, incoming.type)+ return (+ ArtifactSpec(+ name=existing.name,+ type=merged_type,+ description=self._merge_description(+ existing.description,+ incoming.description,+ ),+ ),+ details,+ )++ def _merge_type(self, existing: str, incoming: str) -> Tuple[str, Dict[str, Any]]:+ if existing == incoming:+ return existing, {"type_conflict": False, "type_values": [existing]}+ if existing == self.config.unknown_type:+ return incoming, {+ "type_conflict": True,+ "type_values": [existing, incoming],+ }+ return existing, {+ "type_conflict": True,+ "type_values": [existing, incoming],+ }++ @staticmethod+ def _merge_optional_value(+ existing: Any,+ incoming: Any,+ ) -> Tuple[Any, bool]:+ if existing in (None, ""):+ return incoming, False+ if incoming in (None, "") or incoming == existing:+ return existing, False+ return existing, True++ @staticmethod+ def _merge_description(existing: str, incoming: str) -> str:+ parts: List[str] = []+ seen: set[str] = set()+ for value in [existing, incoming]:+ text = str(value or "").strip()+ if not text or text in seen:+ continue+ parts.append(text)+ seen.add(text)+ return " ".join(parts)diff --git a/jiuwenswarm/symphony/fingerprint/normalize/io_name_resolver.py b/jiuwenswarm/symphony/fingerprint/normalize/io_name_resolver.pynew file mode 100644index 0000000000..10c9861550--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/normalize/io_name_resolver.py@@ -0,0 +1,300 @@+"""LLM-backed resolver for unseen I/O vocabulary terms."""++from __future__ import annotations++import json+from threading import RLock+from typing import Any, Callable, Dict, List, Optional, Set, Tuple++from jiuwenswarm.symphony.fingerprint.normalize.io_name_vocab import (+ IONameCandidate,+ IONameResolution,+ IONameVocabulary,+)+from jiuwenswarm.symphony.llm import (+ LLMConfig,+ create_llm_client,+ llm_usage_context,+)++_ACTION_ALIAS_EXISTING = "alias_existing"+_ACTION_CREATE_NEW = "create_new"+_ACTION_MERGE_EXISTING = "merge_existing"+_ACTION_EXCLUDE_FROM_VOCAB = "exclude_from_vocab"+_ALLOWED_ACTIONS = frozenset(+ {+ _ACTION_ALIAS_EXISTING,+ _ACTION_CREATE_NEW,+ _ACTION_MERGE_EXISTING,+ _ACTION_EXCLUDE_FROM_VOCAB,+ }+)+++class LLMIONameResolver:+ """LLM-backed resolver for unseen io_name_vocab terms."""++ def __init__(+ self,+ config: LLMConfig,+ *,+ batch_size: int = 1,+ progress: Optional[Callable[[str, IONameCandidate, Optional[IONameResolution]], None]] = None,+ ) -> None:+ self.config = config+ self.client = create_llm_client(config)+ self.batch_size = max(1, int(batch_size))+ self.progress = progress+ self._cache: Dict[str, IONameResolution] = {}+ self._cache_lock = RLock()++ async def resolve_async(+ self,+ candidates_by_skill: List[List[IONameCandidate]],+ vocabulary: IONameVocabulary,+ ) -> Dict[str, IONameResolution]:+ candidate_groups: List[Tuple[str, List[IONameCandidate]]] = []+ resolutions: Dict[str, IONameResolution] = {}+ seen: Set[str] = set()+ for index, candidates in enumerate(candidates_by_skill):+ unique_candidates: List[IONameCandidate] = []+ for candidate in candidates:+ if not candidate.token or candidate.token in seen:+ continue+ seen.add(candidate.token)+ with self._cache_lock:+ cached = self._cache.get(candidate.token)+ if cached is not None:+ resolutions[candidate.token] = cached+ continue+ unique_candidates.append(candidate)+ if unique_candidates:+ candidate_groups.append(+ (_candidate_group_ref(index, unique_candidates), unique_candidates)+ )++ if not candidate_groups:+ return resolutions++ context = {+ "skills": [+ {+ "skill_ref": skill_ref,+ "candidates": [+ _candidate_prompt_payload(candidate)+ for candidate in candidates+ ],+ }+ for skill_ref, candidates in candidate_groups+ ],+ "vocabulary": _compact_vocabulary_context(vocabulary),+ "allowed_actions": sorted(_ALLOWED_ACTIONS),+ }+ for _, candidates in candidate_groups:+ for candidate in candidates:+ self._emit_progress("start", candidate, None)+ with llm_usage_context("fingerprint_extraction", "io_name_resolution_prompt_batch"):+ content = await self.client.complete_json_async(+ system_prompt=_IO_NAME_PROMPT_BATCH_RESOLVER_PROMPT,+ user_content=json.dumps(context, ensure_ascii=False, indent=2),+ timeout=200,+ error_context="IO name vocabulary prompt batch LLM",+ request_overrides={+ "extra_body": {"thinking": {"type": "disabled"}},+ },+ )+ try:+ payload = json.loads(content)+ except json.JSONDecodeError as exc:+ raise RuntimeError(+ "IO name vocabulary prompt batch LLM response is not valid JSON. "+ f"content_prefix={content[:1000]!r}"+ ) from exc++ payload_skills = payload.get("skills", [])+ if not isinstance(payload_skills, list):+ raise RuntimeError(+ "IO name vocabulary prompt batch LLM response must contain skills array."+ )++ candidates_by_ref = {+ skill_ref: {candidate.token: candidate for candidate in candidates}+ for skill_ref, candidates in candidate_groups+ }+ remaining_tokens = {+ skill_ref: set(candidates)+ for skill_ref, candidates in candidates_by_ref.items()+ }+ for skill_payload in payload_skills:+ if not isinstance(skill_payload, dict):+ continue+ skill_ref = str(skill_payload.get("skill_ref") or "").strip()+ if skill_ref not in candidates_by_ref:+ continue+ payload_items = skill_payload.get("resolutions", [])+ if not isinstance(payload_items, list):+ continue+ for item in payload_items:+ if not isinstance(item, dict):+ continue+ token = str(item.get("token") or "").strip()+ if token not in remaining_tokens[skill_ref]:+ continue+ resolution = _resolution_from_payload(item, vocabulary)+ resolutions[token] = resolution+ with self._cache_lock:+ self._cache[token] = resolution+ remaining_tokens[skill_ref].remove(token)+ self._emit_progress(+ "done",+ candidates_by_ref[skill_ref][token],+ resolution,+ )++ missing = {+ skill_ref: sorted(tokens)+ for skill_ref, tokens in remaining_tokens.items()+ if tokens+ }+ if missing:+ raise RuntimeError(+ "IO name vocabulary prompt batch LLM response omitted resolutions: "+ + json.dumps(missing, ensure_ascii=False, sort_keys=True)+ )+ return resolutions++ def _emit_progress(+ self,+ stage: str,+ candidate: IONameCandidate,+ resolution: Optional[IONameResolution],+ ) -> None:+ if self.progress is not None:+ self.progress(stage, candidate, resolution)+++def _candidate_group_ref(index: int, candidates: List[IONameCandidate]) -> str:+ if not candidates:+ return str(index)+ first = candidates[0]+ return f"{index}:{first.token}"+++def _candidate_prompt_payload(candidate: IONameCandidate) -> Dict[str, str]:+ return {+ "raw_value": candidate.raw_value,+ "token": candidate.token,+ "description": candidate.description,+ "direction": candidate.direction,+ "type": candidate.data_type,+ }+++def _compact_vocabulary_context(vocabulary: IONameVocabulary) -> Dict[str, Any]:+ context = vocabulary.resolver_context()+ terms = []+ for item in context.get("terms", []):+ if not isinstance(item, dict):+ continue+ terms.append(+ {+ "name": str(item.get("name") or ""),+ "definition": str(item.get("definition") or ""),+ "aliases": [+ str(alias)+ for alias in item.get("aliases", [])+ if str(alias).strip()+ ],+ }+ )+ return {+ "version": context.get("version"),+ "max_vocab_size": context.get("max_vocab_size"),+ "is_full": context.get("is_full"),+ "terms": terms,+ }+++def _resolution_from_payload(+ payload: Dict[str, Any],+ vocabulary: IONameVocabulary,+) -> IONameResolution:+ action = str(payload.get("action") or _ACTION_MERGE_EXISTING)+ if action not in _ALLOWED_ACTIONS:+ action = _ACTION_MERGE_EXISTING++ target = (+ payload.get("target")+ or payload.get("normalized_value")+ or payload.get("normalized_name")+ )+ normalized_value = str(target).strip() if target is not None else None+ definition = str(payload.get("definition") or "").strip()+ if action == _ACTION_EXCLUDE_FROM_VOCAB:+ normalized_value = None+ definition = ""+ elif action == _ACTION_CREATE_NEW and vocabulary.is_full():+ action = _ACTION_MERGE_EXISTING+ normalized_value = vocabulary.closest_term(normalized_value or "")++ return IONameResolution(+ action=action,+ normalized_value=normalized_value,+ confidence=_coerce_confidence(payload.get("confidence")),+ reason=str(payload.get("reason") or ""),+ forced_merge=bool(payload.get("forced_merge")) or action == _ACTION_MERGE_EXISTING,+ definition=definition,+ )+++def _coerce_confidence(value: Any) -> float:+ try:+ number = float(value)+ except (TypeError, ValueError):+ return 0.0+ return max(0.0, min(1.0, number))+++_IO_NAME_PROMPT_BATCH_RESOLVER_PROMPT = """Resolve Skill input/output names against io_name_vocab.++Return only a valid JSON object. Do not include markdown fences, explanations,+analysis, or reasoning text.++Required JSON shape:+{+ "skills": [+ {+ "skill_ref": "the exact skill_ref from the input",+ "resolutions": [+ {+ "token": "candidate_token",+ "action": "alias_existing|create_new|merge_existing|exclude_from_vocab",+ "target": "existing_or_new_vocab_term_or_null",+ "confidence": 0.0,+ "reason": "short explanation",+ "definition": "semantic definition or enrichment suggestion"+ }+ ]+ }+ ]+}++Return exactly one resolution for every input candidate token. Preserve+skill_ref exactly. skill_ref is only an opaque correlation id.++Allowed actions:+- alias_existing: candidate is synonymous with an existing vocabulary term.+- create_new: candidate is a genuinely new runtime semantic role.+- merge_existing: candidate should be merged into the closest existing term.+- exclude_from_vocab: candidate is bookkeeping-only telemetry, analytics,+ tracking, or original-copy data.++The type field is only the data format or carrier, not the semantic role.+Existing terms have definitions in the vocabulary context - use them to judge+semantic equivalence.++Prefer recall for graph linking. Singular/plural forms, input/output variants,+and compound variants such as text/content/body or path/output_path often share+one semantic role. Directional qualifiers should block merging only when feeding+would be clearly wrong, such as source_language vs target_language or api_key vs query.+"""diff --git a/jiuwenswarm/symphony/fingerprint/normalize/io_name_vocab.py b/jiuwenswarm/symphony/fingerprint/normalize/io_name_vocab.pynew file mode 100644index 0000000000..aa5fcc48d1--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/normalize/io_name_vocab.py@@ -0,0 +1,101 @@+"""Dynamic vocabulary for normalizing Skill input/output names.++This module provides specialized vocabulary classes for normalizing+I/O names (like 'query', 'paper', 'summary'). It builds on the+shared vocabulary infrastructure from vocabulary.py.+"""++from __future__ import annotations++import json+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Dict, List, Protocol, Union++from jiuwenswarm.symphony.fingerprint.normalize.vocabulary import (+ BaseCandidate,+ BaseResolution,+ BaseVocabTerm,+ DynamicVocabulary,+ _max_vocab_size_from_data,+)+from jiuwenswarm.symphony.fingerprint.models import NormalizationConfig+++@dataclass(frozen=True)+class IONameCandidate(BaseCandidate):+ """Candidate for I/O name vocabulary resolution with direction and type context."""++ direction: str = ""+ data_type: str = ""++ def to_dict(self) -> Dict[str, Any]:+ data = super().to_dict()+ data["direction"] = self.direction+ data["type"] = self.data_type+ return data+++# IONameResolution is identical to BaseResolution, use it as alias.+IONameResolution = BaseResolution+++class IONameResolver(Protocol):+ """Async resolver protocol for unseen io_name_vocab terms."""++ async def resolve_async(+ self,+ candidates_by_skill: List[List[IONameCandidate]],+ vocabulary: "IONameVocabulary",+ ) -> Dict[str, IONameResolution]:+ ...+++# IONameVocabTerm is identical to BaseVocabTerm, use it as alias.+IONameVocabTerm = BaseVocabTerm+++class IONameVocabulary(DynamicVocabulary):+ """Mutable io_name_vocab with bounded canonical terms and unbounded aliases.++ This vocabulary manages I/O name terms used for graph linking.+ """++ @classmethod+ def from_config(cls, config: NormalizationConfig) -> "IONameVocabulary":+ """Build vocabulary from NormalizationConfig."""+ return cls(+ version=config.io_name_vocab_version,+ max_vocab_size=config.max_vocab_size,+ terms=[],+ )++ @classmethod+ def from_dict(+ cls,+ data: Dict[str, Any],+ config: NormalizationConfig,+ ) -> "IONameVocabulary":+ """Build vocabulary from a dictionary with config defaults."""+ return cls(+ version=str(data.get("version") or config.io_name_vocab_version),+ max_vocab_size=_max_vocab_size_from_data(+ data.get("max_vocab_size"),+ config.max_vocab_size,+ ),+ terms=[+ IONameVocabTerm.from_dict(item)+ for item in data.get("terms", [])+ if isinstance(item, dict)+ ],+ )++ @classmethod+ def load(+ cls,+ path: Union[Path, str],+ config: NormalizationConfig,+ ) -> "IONameVocabulary":+ """Load vocabulary from a JSON file with config defaults."""+ data = json.loads(Path(path).read_text(encoding="utf-8"))+ return cls.from_dict(data, config)diff --git a/jiuwenswarm/symphony/fingerprint/normalize/io_names.py b/jiuwenswarm/symphony/fingerprint/normalize/io_names.pynew file mode 100644index 0000000000..01a645e98d--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/normalize/io_names.py@@ -0,0 +1,300 @@+"""I/O semantic name normalization."""++from __future__ import annotations++from dataclasses import dataclass+from threading import RLock+from typing import Dict, List, Optional++from jiuwenswarm.symphony.fingerprint.models import (+ ExtractedSkillSchema,+ ExtractionDiagnostic,+ NormalizationConfig,+ NormalizationDecision,+ RawSkillManifest,+)+from jiuwenswarm.symphony.fingerprint.normalize.decisions import (+ NormalizationDecisionRecorder,+)+from jiuwenswarm.symphony.fingerprint.normalize.io_name_vocab import (+ IONameCandidate,+ IONameResolver,+ IONameResolution,+ IONameVocabulary,+)+from jiuwenswarm.symphony.fingerprint.normalize.vocabulary import term_similarity+from jiuwenswarm.symphony.fingerprint.utils import normalize_parameter_name, to_dict+++@dataclass(frozen=True)+class IONameNormalizationContext:+ raw_type: str+ description: str+ manifest: RawSkillManifest+ skill_id: str+ direction: str+ diagnostics: List[ExtractionDiagnostic]+ decisions: List[NormalizationDecision]+++class IONameNormalizer:+ """Normalize Skill input/output semantic names through io_name_vocab."""++ def __init__(+ self,+ config: NormalizationConfig,+ vocabulary: IONameVocabulary,+ resolver: IONameResolver,+ recorder: NormalizationDecisionRecorder,+ ) -> None:+ self.config = config+ self.vocabulary = vocabulary+ self.resolver = resolver+ self.recorder = recorder+ self._resolution_cache: Dict[str, IONameResolution] = {}+ self._resolution_cache_lock = RLock()++ def collect_candidates(+ self,+ manifest: RawSkillManifest,+ extracted: ExtractedSkillSchema,+ skill_id: str,+ ) -> List[IONameCandidate]:+ candidates: List[IONameCandidate] = []+ seen: set[str] = set()+ fields = [+ ("input", extracted.inputs, self.config.default_input_name, self.config.default_input_type),+ ("output", extracted.outputs, self.config.default_output_name, self.config.unknown_type),+ ]+ for direction, items, default_name, default_type in fields:+ for raw in items:+ data = to_dict(raw)+ raw_name = str(data.get("name") or default_name)+ raw_type = str(data.get("type") or default_type)+ token = normalize_parameter_name(raw_name)+ if (+ not token+ or token in seen+ or self.vocabulary.lookup(token) is not None+ ):+ continue+ with self._resolution_cache_lock:+ cached = token in self._resolution_cache+ if cached:+ continue+ seen.add(token)+ candidates.append(+ IONameCandidate(+ raw_value=raw_name,+ token=token,+ direction=direction,+ data_type=raw_type,+ description=str(data.get("description") or ""),+ skill_id=skill_id,+ path=str(manifest.folder.path),+ )+ )+ return candidates++ async def prime_resolutions(+ self,+ candidates_by_skill: List[List[IONameCandidate]],+ ) -> None:+ candidates_by_skill = [candidates for candidates in candidates_by_skill if candidates]+ if not candidates_by_skill:+ return+ resolutions = await self.resolver.resolve_async(+ candidates_by_skill,+ self.vocabulary,+ )+ self._ensure_batch_canonical_terms(candidates_by_skill, resolutions)+ with self._resolution_cache_lock:+ self._resolution_cache.update(resolutions)++ async def normalize(+ self,+ raw_name: str,+ context: IONameNormalizationContext,+ ) -> Optional[str]:+ token = normalize_parameter_name(raw_name)+ resolution = self._cached_resolution(token)+ if resolution is None:+ existing = self.vocabulary.lookup(token)+ if existing is not None:+ method = "vocab_alias" if existing != token else "vocab_exact"+ confidence = 0.95 if existing != token else 1.0+ self.recorder.record(+ context.decisions,+ skill_id=context.skill_id,+ path=str(context.manifest.folder.path),+ direction=context.direction,+ field="name",+ raw_value=raw_name,+ token=token,+ normalized_value=existing,+ method=method,+ vocab="io_name_vocab",+ vocab_version=self.vocabulary.version,+ confidence=confidence,+ )+ return existing++ candidate = IONameCandidate(+ raw_value=raw_name,+ token=token,+ direction=context.direction,+ data_type=context.raw_type,+ description=context.description,+ skill_id=context.skill_id,+ path=str(context.manifest.folder.path),+ )+ resolutions = await self.resolver.resolve_async(+ [[candidate]],+ self.vocabulary,+ )+ resolution = resolutions.get(token)+ if resolution is None:+ resolution = IONameResolution(+ normalized_value=token,+ action="create_new",+ confidence=0.0,+ reason="resolver omitted candidate",+ )+ with self._resolution_cache_lock:+ self._resolution_cache[token] = resolution+ normalized = self._apply_resolution(+ token,+ resolution,+ context,+ )+ self.recorder.record(+ context.decisions,+ skill_id=context.skill_id,+ path=str(context.manifest.folder.path),+ direction=context.direction,+ field="name",+ raw_value=raw_name,+ token=token,+ normalized_value=normalized or "",+ method=resolution.action,+ vocab="io_name_vocab",+ vocab_version=self.vocabulary.version,+ confidence=resolution.confidence,+ details={+ "reason": resolution.reason,+ "forced_merge": resolution.forced_merge,+ "vocab_size": self.vocabulary.size(),+ "max_vocab_size": self.vocabulary.max_vocab_size,+ },+ )+ return normalized++ def _cached_resolution(self, token: str) -> IONameResolution | None:+ with self._resolution_cache_lock:+ return self._resolution_cache.get(token)++ def _ensure_batch_canonical_terms(+ self,+ candidates_by_skill: List[List[IONameCandidate]],+ resolutions: Dict[str, IONameResolution],+ ) -> None:+ candidates_by_token = {+ candidate.token: candidate+ for candidates in candidates_by_skill+ for candidate in candidates+ }+ known_terms = set(self.vocabulary.term_names())+ for token, resolution in resolutions.items():+ if resolution.action != "create_new":+ continue+ target = (resolution.normalized_value or token).strip()+ if not target or target in known_terms:+ continue+ candidate = candidates_by_token.get(token)+ self.vocabulary.ensure_term(+ target,+ alias=token,+ example=candidate.description if candidate is not None else "",+ definition=resolution.definition,+ )+ known_terms.add(target)++ def _apply_resolution(+ self,+ token: str,+ resolution: IONameResolution,+ context: IONameNormalizationContext,+ ) -> Optional[str]:+ if resolution.action == "exclude_from_vocab":+ return None++ if resolution.action == "create_new" and not self.vocabulary.is_full():+ self._warn_possible_duplicate(+ token,+ context,+ )+ return self.vocabulary.create_term(+ resolution.normalized_value or token,+ alias=token,+ example=context.description,+ definition=resolution.definition,+ )++ target = resolution.normalized_value or self.vocabulary.closest_term(token)+ if target is None:+ return self.vocabulary.create_term(+ token,+ alias=token,+ example=context.description,+ definition=context.description,+ )+ if target not in self.vocabulary.term_names():+ closest = self.vocabulary.closest_term(target)+ if closest is None:+ return self.vocabulary.create_term(+ token,+ alias=token,+ example=context.description,+ definition=context.description,+ )+ target = closest+ self.vocabulary.add_alias(+ token,+ target,+ example=context.description,+ definition=resolution.definition,+ )+ return target++ def _warn_possible_duplicate(+ self,+ token: str,+ context: IONameNormalizationContext,+ ) -> None:+ threshold = self.config.possible_duplicate_name_similarity_threshold+ if threshold <= 0:+ return+ term_names = self.vocabulary.term_names()+ if not term_names:+ return+ closest = max(term_names, key=lambda name: term_similarity(token, name))+ score = term_similarity(token, closest)+ if score < threshold:+ return+ context.diagnostics.append(+ ExtractionDiagnostic(+ stage="normalization",+ severity="warning",+ code="possible_duplicate_io_name",+ message="new I/O name is similar to an existing vocabulary term; review aliasing",+ skill_id=context.skill_id,+ path=str(context.manifest.folder.path),+ details={+ "direction": context.direction,+ "token": token,+ "closest_term": closest,+ "similarity": round(score, 4),+ "threshold": threshold,+ },+ )+ )diff --git a/jiuwenswarm/symphony/fingerprint/normalize/metadata_normalizer.py b/jiuwenswarm/symphony/fingerprint/normalize/metadata_normalizer.pynew file mode 100644index 0000000000..6476d39808--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/normalize/metadata_normalizer.py@@ -0,0 +1,74 @@+"""Metadata normalization for Skill identity: id, name, version, description."""++from __future__ import annotations++from typing import Optional++from jiuwenswarm.symphony.fingerprint.models import (+ ExtractedSkillSchema,+ MetadataNormalizationResult,+ NormalizationConfig,+ RawSkillManifest,+)+from jiuwenswarm.symphony.fingerprint.utils import normalize_human_name, normalize_slug+++class MetadataNormalizer:+ """Normalize Skill metadata: id, name, version, description.++ This class handles the "metadata" dimension of the three-dimensional+ normalization process:+ - name dimension: I/O semantic names (handled by IONameNormalizer)+ - type dimension: data types (handled by DataTypeVocabulary)+ - metadata dimension: Skill identity fields (handled by this class)++ The metadata normalization derives Skill identity from:+ 1. frontmatter.name → normalized slug for id+ 2. folder.id_hint → fallback for id derivation+ 3. folder.relative_path → final fallback for id+ """++ def __init__(self, config: Optional[NormalizationConfig] = None) -> None:+ self.config = config or NormalizationConfig()++ def normalize(+ self,+ manifest: RawSkillManifest,+ extracted: ExtractedSkillSchema,+ ) -> MetadataNormalizationResult:+ """Normalize Skill metadata from frontmatter and folder path.++ Args:+ manifest: Raw Skill manifest with frontmatter and folder info.+ extracted: LLM-extracted schema with description.++ Returns:+ MetadataNormalizationResult with normalized id, name, version, description.+ """+ frontmatter = manifest.frontmatter++ # Derive id from name → id_hint → relative_path+ raw_name = str(frontmatter.get("name") or manifest.folder.id_hint)+ skill_id = normalize_slug(raw_name) or normalize_slug(+ manifest.folder.relative_path+ )++ # Derive human-readable name+ name = normalize_human_name(raw_name) or skill_id++ # Derive version from frontmatter or config default+ version = str(+ frontmatter.get("version") or self.config.default_version+ )++ # Derive description from extracted schema or frontmatter+ description = str(+ extracted.description or frontmatter.get("description") or ""+ ).strip()++ return MetadataNormalizationResult(+ id=skill_id,+ name=name,+ description=description,+ version=version,+ )diff --git a/jiuwenswarm/symphony/fingerprint/normalize/normalizer.py b/jiuwenswarm/symphony/fingerprint/normalize/normalizer.pynew file mode 100644index 0000000000..7e941bb106--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/normalize/normalizer.py@@ -0,0 +1,186 @@+"""Deterministic normalization for LLM-extracted Skill schemas."""++from __future__ import annotations++from dataclasses import dataclass+from typing import List, Optional, Tuple++from jiuwenswarm.symphony.fingerprint.models import (+ ExtractedSkillSchema,+ ExtractionDiagnostic,+ NormalizationConfig,+ NormalizationDecision,+ NormalizationResult,+ RawSkillManifest,+ SkillFingerprint,+)+from jiuwenswarm.symphony.fingerprint.normalize.data_type_vocab import DataTypeVocabulary+from jiuwenswarm.symphony.fingerprint.normalize.data_types import DataTypeNormalizer+from jiuwenswarm.symphony.fingerprint.normalize.decisions import (+ NormalizationDecisionRecorder,+)+from jiuwenswarm.symphony.fingerprint.normalize.fields import SchemaFieldNormalizer+from jiuwenswarm.symphony.fingerprint.normalize.io_name_vocab import (+ IONameCandidate,+ IONameResolver,+ IONameVocabulary,+)+from jiuwenswarm.symphony.fingerprint.normalize.io_names import IONameNormalizer+from jiuwenswarm.symphony.fingerprint.normalize.metadata_normalizer import (+ MetadataNormalizer,+)++NormalizationItem = Tuple[RawSkillManifest, ExtractedSkillSchema]+++@dataclass+class _NormalizationContext:+ manifest: RawSkillManifest+ extracted: ExtractedSkillSchema+ diagnostics: List[ExtractionDiagnostic]+ decisions: List[NormalizationDecision]+ skill_id: str+ name: str+ description: str+ version: str+ io_name_candidates: List[IONameCandidate]+++class SkillFingerprintNormalizer:+ """Convert ExtractedSkillSchema batches into SkillFingerprint v1."""++ def __init__(+ self,+ config: Optional[NormalizationConfig] = None,+ io_name_vocabulary: Optional[IONameVocabulary] = None,+ io_name_resolver: Optional[IONameResolver] = None,+ metadata_normalizer: Optional[MetadataNormalizer] = None,+ ) -> None:+ self.config = config or NormalizationConfig()+ self.data_type_vocabulary = DataTypeVocabulary.from_config(self.config)+ self._io_name_vocabulary = (+ io_name_vocabulary+ or IONameVocabulary.from_config(self.config)+ )+ if io_name_resolver is None:+ raise ValueError("SkillFingerprintNormalizer requires io_name_resolver.")+ self.io_name_resolver = io_name_resolver+ self.metadata_normalizer = metadata_normalizer or MetadataNormalizer(self.config)+ self.decision_recorder = NormalizationDecisionRecorder()+ self.data_type_normalizer = DataTypeNormalizer(+ self.config,+ self.data_type_vocabulary,+ self.decision_recorder,+ )+ self.io_name_normalizer = IONameNormalizer(+ self.config,+ self._io_name_vocabulary,+ self.io_name_resolver,+ self.decision_recorder,+ )+ self.field_normalizer = SchemaFieldNormalizer(+ self.config,+ self.io_name_normalizer,+ self.data_type_normalizer,+ self.decision_recorder,+ )++ @property+ def io_name_vocabulary(self) -> IONameVocabulary:+ return self._io_name_vocabulary++ @io_name_vocabulary.setter+ def io_name_vocabulary(self, vocabulary: IONameVocabulary) -> None:+ self._io_name_vocabulary = vocabulary+ self.io_name_normalizer.vocabulary = vocabulary++ async def normalize(+ self,+ items: List[NormalizationItem],+ ) -> List[NormalizationResult]:+ contexts = self._prepare_contexts(items)+ await self._prime_io_name_resolutions(contexts)+ return [await self._normalize_context(context) for context in contexts]++ async def normalize_single(+ self,+ manifest: RawSkillManifest,+ extracted: ExtractedSkillSchema,+ ) -> NormalizationResult:+ return (await self.normalize([(manifest, extracted)]))[0]++ def _prepare_contexts(+ self,+ items: List[NormalizationItem],+ ) -> List[_NormalizationContext]:+ contexts: List[_NormalizationContext] = []+ for manifest, extracted in items:+ identity = self.metadata_normalizer.normalize(manifest, extracted)+ candidates = self.io_name_normalizer.collect_candidates(+ manifest,+ extracted,+ identity.id,+ )+ contexts.append(+ _NormalizationContext(+ manifest=manifest,+ extracted=extracted,+ diagnostics=list(manifest.diagnostics),+ decisions=[],+ skill_id=identity.id,+ name=identity.name,+ description=identity.description,+ version=identity.version,+ io_name_candidates=candidates,+ )+ )+ return contexts++ async def _prime_io_name_resolutions(+ self,+ contexts: List[_NormalizationContext],+ ) -> None:+ batch_size = max(1, int(getattr(self.io_name_resolver, "batch_size", 1)))+ for start in range(0, len(contexts), batch_size):+ batch = contexts[start: start + batch_size]+ await self.io_name_normalizer.prime_resolutions(+ [context.io_name_candidates for context in batch]+ )++ async def _normalize_context(+ self,+ context: _NormalizationContext,+ ) -> NormalizationResult:+ inputs = await self.field_normalizer.normalize_inputs(+ context.extracted.inputs,+ context.manifest,+ context.skill_id,+ context.diagnostics,+ context.decisions,+ )+ outputs = await self.field_normalizer.normalize_outputs(+ context.extracted.outputs,+ context.manifest,+ context.skill_id,+ context.diagnostics,+ context.decisions,+ )++ fingerprint = SkillFingerprint(+ id=context.skill_id,+ name=context.name,+ description=context.description,+ version=context.version,+ inputs=inputs,+ outputs=outputs,+ )+ self.data_type_normalizer.validate(+ fingerprint,+ context.manifest,+ context.diagnostics,+ )+ return NormalizationResult(+ fingerprint=fingerprint,+ diagnostics=context.diagnostics,+ decisions=context.decisions,+ )diff --git a/jiuwenswarm/symphony/fingerprint/normalize/vocabulary.py b/jiuwenswarm/symphony/fingerprint/normalize/vocabulary.pynew file mode 100644index 0000000000..f934abb574--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/normalize/vocabulary.py@@ -0,0 +1,475 @@+# -*- coding: utf-8 -*-+"""Base classes and utilities for dynamic vocabularies."""++from __future__ import annotations++import json+from dataclasses import dataclass, field+from difflib import SequenceMatcher+from pathlib import Path+from threading import RLock+from typing import Any, Dict, List, Optional, Protocol, Set, Union+++def term_similarity(left: str, right: str) -> float:+ """Compute similarity between two vocabulary terms.++ Uses both word overlap (Jaccard on split parts) and sequence matching.+ """+ left_parts = set(left.split("_"))+ right_parts = set(right.split("_"))+ overlap = len(left_parts & right_parts) / max(1, len(left_parts | right_parts))+ ratio = SequenceMatcher(None, left, right).ratio()+ return max(overlap, ratio)+++def _merge_definitions(existing: str, incoming: str) -> str:+ """Merge two definitions, avoiding duplication.++ If the incoming definition is already contained in the existing one,+ return the existing definition unchanged. Otherwise, append the+ incoming definition with a separator.+ """+ existing = existing.strip()+ incoming = incoming.strip()+ if not incoming:+ return existing+ if not existing:+ return incoming+ # Check if incoming is already contained (case-insensitive)+ if incoming.lower() in existing.lower():+ return existing+ # Avoid duplication of similar content+ if existing.lower() == incoming.lower():+ return existing+ # Append with separator+ return f"{existing}; {incoming}"+++@dataclass(frozen=True)+class BaseCandidate:+ """Base class for vocabulary resolution candidates."""++ raw_value: str+ token: str+ description: str+ skill_id: str+ path: Optional[str] = None++ def to_dict(self) -> Dict[str, Any]:+ return {+ "raw_value": self.raw_value,+ "token": self.token,+ "description": self.description,+ "skill_id": self.skill_id,+ "path": self.path,+ }+++@dataclass(frozen=True)+class BaseResolution:+ """Base class for vocabulary resolution results."""++ action: str+ normalized_value: Optional[str]+ confidence: float+ reason: str = ""+ forced_merge: bool = False+ definition: str = ""+++@dataclass+class BaseVocabTerm:+ """Base class for vocabulary terms."""++ name: str+ aliases: Set[str] = field(default_factory=set)+ definition: str = ""+ examples: List[str] = field(default_factory=list)+ count: int = 0++ def to_dict(self) -> Dict[str, Any]:+ return {+ "name": self.name,+ "definition": self.definition,+ "aliases": sorted(alias for alias in self.aliases if alias != self.name),+ "examples": list(self.examples),+ "count": self.count,+ }++ @classmethod+ def from_dict(cls, data: Dict[str, Any]) -> "BaseVocabTerm":+ name = str(data.get("name") or "").strip()+ aliases = {+ str(alias).strip()+ for alias in data.get("aliases", [])+ if str(alias).strip()+ }+ return cls(+ name=name,+ aliases=aliases,+ definition=str(data.get("definition") or ""),+ examples=[str(item) for item in data.get("examples", [])],+ count=int(data.get("count") or 0),+ )+++class BaseVocabulary(Protocol):+ """Protocol defining the common interface for all vocabularies.++ Both static and dynamic vocabularies implement this interface,+ allowing consistent usage across different vocabulary types.+ """++ version: str++ def lookup(self, token: str) -> Optional[str]:+ """Look up a token in the vocabulary, returning the canonical term."""+ ...++ def term_names(self) -> List[str]:+ """Return sorted list of canonical term names."""+ ...++ def to_dict(self) -> Dict[str, Any]:+ """Serialize vocabulary to a dictionary."""+ ...++ def save(self, path: Union[Path, str]) -> None:+ """Save vocabulary to a JSON file."""+ ...+++@dataclass(frozen=True)+class StaticVocabulary:+ """Immutable vocabulary with fixed terms and alias mappings.++ Suitable for controlled vocabularies that don't need dynamic growth,+ such as DataType vocabulary with predefined formats/carriers.+ """++ version: str+ vocab: frozenset+ aliases: Dict[str, str] = field(default_factory=dict)++ def lookup(self, token: str) -> Optional[str]:+ """Look up a token, returning the canonical term if found."""+ if token in self.vocab:+ return token+ return self.aliases.get(token)++ def resolve(self, raw_token: str) -> str:+ """Resolve a raw token to a canonical vocabulary term.++ Returns the canonical term if found, otherwise returns "unknown"+ (or the raw token if "unknown" is not in vocab).+ """+ normalized = raw_token.lower().strip()+ # Direct match in vocab+ if normalized in self.vocab:+ return normalized+ # Check aliases+ alias_result = self.aliases.get(normalized)+ if alias_result and alias_result in self.vocab:+ return alias_result+ # Fallback to "unknown" if available+ if "unknown" in self.vocab:+ return "unknown"+ return normalized++ def term_names(self) -> List[str]:+ """Return sorted list of canonical term names."""+ return sorted(self.vocab)++ def to_dict(self) -> Dict[str, Any]:+ """Serialize vocabulary to a dictionary."""+ return {+ "version": self.version,+ "vocab": sorted(self.vocab),+ "aliases": dict(self.aliases),+ }++ def save(self, path: Union[Path, str]) -> None:+ """Save vocabulary to a JSON file."""+ Path(path).write_text(+ json.dumps(self.to_dict(), ensure_ascii=False, indent=2),+ encoding="utf-8",+ )++ @classmethod+ def from_dict(+ cls,+ data: Dict[str, Any],+ *,+ default_version: str = "static-vocab-v1",+ ) -> "StaticVocabulary":+ """Build vocabulary from a dictionary."""+ vocab_data = data.get("vocab", [])+ vocab = frozenset(+ str(item).strip()+ for item in vocab_data+ if str(item).strip()+ )+ aliases = {+ str(k).strip(): str(v).strip()+ for k, v in data.get("aliases", {}).items()+ if str(k).strip() and str(v).strip()+ }+ return cls(+ version=str(data.get("version") or default_version),+ vocab=vocab,+ aliases=aliases,+ )++ @classmethod+ def load(+ cls,+ path: Union[Path, str],+ *,+ default_version: str = "static-vocab-v1",+ ) -> "StaticVocabulary":+ """Load vocabulary from a JSON file."""+ data = json.loads(Path(path).read_text(encoding="utf-8"))+ return cls.from_dict(data, default_version=default_version)++ def __contains__(self, token: str) -> bool:+ """Check if a token is in the vocabulary (canonical or alias)."""+ return token in self.vocab or token in self.aliases+++class DynamicVocabulary:+ """Thread-safe mutable bounded vocabulary for semantic fields.++ Suitable for vocabularies that need to grow dynamically based on+ observed data, such as I/O name vocabulary.+ """++ def __init__(+ self,+ *,+ version: str,+ max_vocab_size: Optional[int],+ terms: Optional[List[BaseVocabTerm]] = None,+ ) -> None:+ self.version = version+ self.max_vocab_size = _normalize_max_vocab_size(max_vocab_size)+ self._terms: Dict[str, BaseVocabTerm] = {}+ self._aliases: Dict[str, str] = {}+ self._lock = RLock()+ for term in terms or []:+ self.add_term(term)++ @classmethod+ def from_aliases(+ cls,+ *,+ version: str,+ max_vocab_size: Optional[int],+ aliases: Dict[str, str],+ ) -> "DynamicVocabulary":+ """Build vocabulary from an alias mapping."""+ terms: Dict[str, BaseVocabTerm] = {}+ for alias, name in aliases.items():+ term = terms.setdefault(name, BaseVocabTerm(name=name))+ term.aliases.add(alias)+ for name, term in list(terms.items()):+ term.aliases.discard(name)+ return cls(+ version=version,+ max_vocab_size=max_vocab_size,+ terms=list(terms.values()),+ )++ @classmethod+ def from_dict(+ cls,+ data: Dict[str, Any],+ *,+ default_version: str,+ default_max_vocab_size: Optional[int],+ ) -> "DynamicVocabulary":+ return cls(+ version=str(data.get("version") or default_version),+ max_vocab_size=_max_vocab_size_from_data(+ data.get("max_vocab_size"),+ default_max_vocab_size,+ ),+ terms=[+ BaseVocabTerm.from_dict(item)+ for item in data.get("terms", [])+ if isinstance(item, dict)+ ],+ )++ @classmethod+ def load(+ cls,+ path: Union[Path, str],+ *,+ default_version: str,+ default_max_vocab_size: Optional[int],+ ) -> "DynamicVocabulary":+ data = json.loads(Path(path).read_text(encoding="utf-8"))+ return cls.from_dict(+ data,+ default_version=default_version,+ default_max_vocab_size=default_max_vocab_size,+ )++ def save(self, path: Union[Path, str]) -> None:+ Path(path).write_text(+ json.dumps(self.to_dict(), ensure_ascii=False, indent=2),+ encoding="utf-8",+ )++ def add_term(self, term: BaseVocabTerm) -> None:+ if not term.name:+ return+ with self._lock:+ self._terms[term.name] = term+ self._aliases[term.name] = term.name+ for alias in term.aliases:+ if alias:+ self._aliases[alias] = term.name++ def lookup(self, token: str) -> Optional[str]:+ with self._lock:+ return self._aliases.get(token)++ def term_names(self) -> List[str]:+ with self._lock:+ return sorted(self._terms)++ def size(self) -> int:+ with self._lock:+ return len(self._terms)++ def is_full(self) -> bool:+ return self.max_vocab_size is not None and self.size() >= self.max_vocab_size++ def add_alias(+ self,+ alias: str,+ target: str,+ *,+ example: str = "",+ definition: str = "",+ ) -> None:+ with self._lock:+ term = self._terms.get(target)+ if term is None:+ return+ if alias and alias != target:+ term.aliases.add(alias)+ self._aliases[alias] = target+ if example and example not in term.examples:+ term.examples.append(example)+ if definition:+ term.definition = _merge_definitions(term.definition, definition)+ term.count += 1++ def ensure_term(+ self,+ name: str,+ *,+ alias: str = "",+ example: str = "",+ definition: str = "",+ ) -> str:+ with self._lock:+ if (+ self.max_vocab_size is not None+ and name not in self._terms+ and len(self._terms) >= self.max_vocab_size+ ):+ return self.closest_term(name) or name+ term = self._terms.get(name)+ if term is None:+ term = BaseVocabTerm(name=name, definition=definition)+ self._terms[name] = term+ self._aliases[name] = name+ elif definition:+ term.definition = _merge_definitions(term.definition, definition)+ if alias and alias != name:+ term.aliases.add(alias)+ self._aliases[alias] = name+ if example and example not in term.examples:+ term.examples.append(example)+ return name++ def create_term(+ self,+ name: str,+ *,+ alias: str = "",+ example: str = "",+ definition: str = "",+ ) -> str:+ with self._lock:+ if (+ self.max_vocab_size is not None+ and name not in self._terms+ and len(self._terms) >= self.max_vocab_size+ ):+ return self.closest_term(name) or name+ term = self._terms.get(name)+ if term is None:+ term = BaseVocabTerm(name=name, definition=definition)+ self._terms[name] = term+ self._aliases[name] = name+ if alias and alias != name:+ term.aliases.add(alias)+ self._aliases[alias] = name+ if example:+ term.examples.append(example)+ term.count += 1+ return name++ def closest_term(self, token: str) -> Optional[str]:+ with self._lock:+ if not self._terms:+ return None+ return max(self._terms, key=lambda name: term_similarity(token, name))++ def resolver_context(self) -> Dict[str, Any]:+ with self._lock:+ return {+ "version": self.version,+ "max_vocab_size": self.max_vocab_size,+ "is_full": self.is_full(),+ "terms": [+ self._terms[name].to_dict()+ for name in sorted(self._terms)+ ],+ }++ def to_dict(self) -> Dict[str, Any]:+ with self._lock:+ return {+ "version": self.version,+ "max_vocab_size": self.max_vocab_size,+ "terms": [+ self._terms[name].to_dict()+ for name in sorted(self._terms)+ ],+ }+++# Backward compatibility alias: BaseVocabulary was previously the dynamic class.+# Now BaseVocabulary is a Protocol, but we keep this alias for gradual migration.+BaseVocabularyImpl = DynamicVocabulary+++def _normalize_max_vocab_size(value: Optional[int]) -> Optional[int]:+ if value is None:+ return None+ return max(1, int(value))+++def _max_vocab_size_from_data(+ value: Any,+ default: Optional[int],+) -> Optional[int]:+ if value is None:+ return default+ return _normalize_max_vocab_size(int(value))diff --git a/jiuwenswarm/symphony/fingerprint/pipeline.py b/jiuwenswarm/symphony/fingerprint/pipeline.pynew file mode 100644index 0000000000..567097522b--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/pipeline.py@@ -0,0 +1,298 @@+"""Fingerprint extraction orchestration."""++from __future__ import annotations++from pathlib import Path+from typing import Callable, Dict, Iterable, Optional, Union++from jiuwenswarm.symphony.llm import get_llm_token_usage_summary+from jiuwenswarm.symphony.fingerprint.batching import (+ chunked,+ ensure_result_count,+ gather_limited,+)+from jiuwenswarm.symphony.fingerprint.incremental import (+ IncrementalFingerprintStore,+ load_io_name_vocabulary,+)+from jiuwenswarm.symphony.fingerprint.manifest import SkillManifestParser+from jiuwenswarm.symphony.fingerprint.models import (+ ExtractedSkillSchema,+ FingerprintExtractionResult,+ NormalizationResult,+ RawSkillManifest,+ SkillFolder,+ SkillSchemaExtractor,+)+from jiuwenswarm.symphony.fingerprint.normalize import SkillFingerprintNormalizer+from jiuwenswarm.symphony.fingerprint.scan import SkillFolderScanner++ProgressCallback = Callable[[str, int, int, str], None]+EventCallback = Callable[..., None]+IndexedSkillFolder = tuple[int, SkillFolder]+++class FingerprintExtractor:+ """Scan, parse, extract, and normalize Skill fingerprints."""++ def __init__(+ self,+ schema_extractor: SkillSchemaExtractor,+ scanner: Optional[SkillFolderScanner] = None,+ parser: Optional[SkillManifestParser] = None,+ normalizer: SkillFingerprintNormalizer | None = None,+ progress: Optional[ProgressCallback] = None,+ event_log: Optional[EventCallback] = None,+ max_workers: int = 1,+ normalization_workers: int | None = None,+ normalization_batch_size: int | None = None,+ ) -> None:+ self.schema_extractor = schema_extractor+ self.scanner = scanner or SkillFolderScanner()+ self.parser = parser or SkillManifestParser()+ if normalizer is None:+ raise ValueError("FingerprintExtractor requires normalizer.")+ self.normalizer = normalizer+ self.progress = progress+ self.event_log = event_log+ self.max_workers = max(1, max_workers)+ self.normalization_workers = max(+ 1,+ int(normalization_workers if normalization_workers is not None else max_workers),+ )+ self.normalization_batch_size = normalization_batch_size++ async def extract_from_root(+ self,+ skills_root: Union[Path, str],+ output_dir: Union[Path, str],+ *,+ max_depth: int | None = None,+ force: bool = False,+ ) -> FingerprintExtractionResult:+ output_path = Path(output_dir).resolve()+ folders, current_hashes = self.scanner.snapshot(+ skills_root,+ max_depth=max_depth,+ )+ self._emit_event("scan.done", skill_count=len(folders))+ incremental_store = IncrementalFingerprintStore(output_path)+ self.normalizer.io_name_vocabulary = load_io_name_vocabulary(+ output_path,+ self.normalizer,+ )+ reuse_plan = incremental_store.plan(+ folders,+ current_hashes,+ force=force,+ on_reuse=lambda folder_index, folder, fingerprint: self._emit_event(+ "fingerprint.reuse",+ folder_index + 1,+ total=len(folders),+ path=folder.relative_path,+ skill_id=fingerprint.id,+ ),+ )+ self._emit_event(+ "diff.done",+ changed_count=len(reuse_plan.changed_folders),+ removed_count=len(reuse_plan.removed_paths),+ )++ diagnostics = []+ decisions = []+ extracted_results = await self._extract_selected(+ reuse_plan.changed_folders,+ total=len(folders),+ emit_done=False,+ )+ fingerprints = list(reuse_plan.fingerprints)+ fingerprints_by_path = dict(reuse_plan.fingerprints_by_path)+ for folder_index, folder in reuse_plan.changed_folders:+ normalized = extracted_results[folder_index]+ fingerprints.append(normalized.fingerprint)+ fingerprints_by_path[folder.relative_path] = normalized.fingerprint+ diagnostics.extend(normalized.diagnostics)+ decisions.extend(normalized.decisions)+ self._emit_event(+ "fingerprint.done",+ folder_index + 1,+ total=len(folders),+ path=folder.relative_path,+ skill_id=normalized.fingerprint.id,+ diagnostics=len(normalized.diagnostics),+ )++ fingerprints = sorted(fingerprints, key=lambda item: item.id)+ return FingerprintExtractionResult(+ fingerprints=fingerprints,+ diagnostics=diagnostics,+ normalization_decisions=decisions,+ io_name_vocab=self.normalizer.io_name_vocabulary.to_dict(),+ llm_token_usage=get_llm_token_usage_summary(),+ folders=folders,+ current_hashes=current_hashes,+ removed_paths=reuse_plan.removed_paths,+ fingerprints_by_path=fingerprints_by_path,+ reused_count=reuse_plan.reused_count,+ extracted_count=len(reuse_plan.changed_folders),+ )++ async def _extract_selected(+ self,+ indexed_folders: Iterable[IndexedSkillFolder],+ *,+ total: int | None = None,+ emit_done: bool = True,+ ) -> dict[int, NormalizationResult]:+ """Run parse, schema extraction, and normalization for selected folders.++ The input keeps each folder's original scan index so progress events and+ returned results can still line up with the full scan order.+ """+ selected_folders = list(indexed_folders)+ if not selected_folders:+ return {}++ progress_total = total+ if progress_total is None:+ progress_total = max(folder_index for folder_index, _folder in selected_folders) + 1++ manifests = self._parse_manifests(selected_folders, progress_total)+ extracted = await self._extract_schemas(selected_folders, progress_total, manifests)+ results = await self._normalize_schemas(+ selected_folders,+ progress_total,+ manifests,+ extracted,+ )+ if emit_done:+ for folder_index, folder in selected_folders:+ self._emit_progress("done", folder_index + 1, progress_total, folder.relative_path)+ return results++ def _parse_manifests(+ self,+ indexed_folders: list[IndexedSkillFolder],+ total: int,+ ) -> dict[int, RawSkillManifest]:+ manifests: dict[int, RawSkillManifest] = {}+ for folder_index, folder in indexed_folders:+ self._emit_progress("parse", folder_index + 1, total, folder.relative_path)+ manifests[folder_index] = self.parser.parse(folder)+ return manifests++ def _emit_progress(self, stage: str, current: int, total: int, item: str) -> None:+ if self.progress is not None:+ self.progress(stage, current, total, item)++ def _emit_event(self, stage: str, current: int | None = None, **details: object) -> None:+ if self.event_log is None:+ return+ if current is not None:+ details["current"] = current+ self.event_log(stage, **details)++ def _should_extract_in_batches(self) -> bool:+ return bool(+ getattr(self.schema_extractor, "use_batch", False)+ and hasattr(self.schema_extractor, "extract_many")+ )++ async def _extract_schemas(+ self,+ indexed_folders: list[IndexedSkillFolder],+ total: int,+ manifests_by_index: dict[int, RawSkillManifest],+ ) -> dict[int, ExtractedSkillSchema]:+ batch_results = await gather_limited(+ self._schema_extraction_batches(indexed_folders),+ max_workers=self.max_workers,+ run_batch=lambda batch: self._extract_schema_batch(+ batch,+ total,+ manifests_by_index,+ ),+ )++ results: dict[int, ExtractedSkillSchema] = {}+ for batch_result in batch_results:+ results.update(batch_result)+ return results++ def _schema_extraction_batches(+ self,+ indexed_folders: list[IndexedSkillFolder],+ ) -> list[list[IndexedSkillFolder]]:+ batch_size = 1+ if self._should_extract_in_batches():+ batch_size = max(+ 1,+ int(getattr(self.schema_extractor, "batch_size", 32)),+ )+ return chunked(indexed_folders, batch_size)++ async def _normalize_schemas(+ self,+ indexed_folders: list[IndexedSkillFolder],+ total: int,+ manifests_by_index: Dict[int, RawSkillManifest],+ extracted_by_index: Dict[int, ExtractedSkillSchema],+ ) -> dict[int, NormalizationResult]:+ results_by_index: dict[int, NormalizationResult] = {}+ for batch in chunked(indexed_folders, self._normalization_batch_size()):+ for folder_index, folder in batch:+ self._emit_progress("normalize", folder_index + 1, total, folder.relative_path)+ results = await self.normalizer.normalize(+ [+ (manifests_by_index[folder_index], extracted_by_index[folder_index])+ for folder_index, _folder in batch+ ]+ )+ ensure_result_count(+ len(results),+ len(batch),+ "Batch normalizer",+ )+ results_by_index.update(+ {+ folder_index: result+ for (folder_index, _folder), result in zip(batch, results)+ }+ )+ return results_by_index++ async def _extract_schema_batch(+ self,+ batch: list[IndexedSkillFolder],+ total: int,+ manifests_by_index: Dict[int, RawSkillManifest],+ ) -> dict[int, ExtractedSkillSchema]:+ for folder_index, folder in batch:+ self._emit_progress("extract", folder_index + 1, total, folder.relative_path)+ batch_indexes = [folder_index for folder_index, _folder in batch]+ batch_manifests = [manifests_by_index[index] for index in batch_indexes]+ extract_many = getattr(self.schema_extractor, "extract_many", None)+ if self._should_extract_in_batches() and callable(extract_many):+ batch_extracted = list(await extract_many(batch_manifests))+ else:+ batch_extracted = [+ await self.schema_extractor.extract(manifest)+ for manifest in batch_manifests+ ]+ ensure_result_count(+ len(batch_extracted),+ len(batch_manifests),+ "Batch schema extractor",+ )+ return dict(zip(batch_indexes, batch_extracted))++ def _normalization_batch_size(self) -> int:+ if self.normalization_batch_size is not None:+ return max(1, int(self.normalization_batch_size))+ return max(+ 1,+ int(+ getattr(self.normalizer.io_name_resolver, "batch_size", 1)+ ),+ )diff --git a/jiuwenswarm/symphony/fingerprint/scan.py b/jiuwenswarm/symphony/fingerprint/scan.pynew file mode 100644index 0000000000..a7ed87d0b8--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/scan.py@@ -0,0 +1,57 @@+"""Skill folder discovery."""++from __future__ import annotations++import hashlib+from pathlib import Path+from typing import List, Optional, Union++from jiuwenswarm.symphony.fingerprint.models import SkillFolder+++class SkillFolderScanner:+ """Find folders that contain a SKILL.md entrypoint."""++ @staticmethod+ def scan(+ skills_root: Union[Path, str],+ max_depth: Optional[int] = None,+ ) -> List[SkillFolder]:+ root = Path(skills_root).resolve()+ if not root.exists():+ raise FileNotFoundError(f"skills_root does not exist: {root}")+ if not root.is_dir():+ raise NotADirectoryError(f"skills_root is not a directory: {root}")++ folders: List[SkillFolder] = []+ for entry in sorted(root.rglob("SKILL.md"), key=lambda path: path.as_posix().lower()):+ folder_path = entry.parent+ relative_path = folder_path.relative_to(root).as_posix()+ if max_depth is not None and max_depth >= 0:+ depth = 0 if relative_path == "." else len(folder_path.relative_to(root).parts)+ if depth > max_depth:+ continue+ folders.append(+ SkillFolder(+ id_hint=folder_path.name,+ path=folder_path,+ entry=entry,+ relative_path=relative_path,+ )+ )+ return folders++ def snapshot(+ self,+ skills_root: Union[Path, str],+ max_depth: Optional[int] = None,+ ) -> tuple[List[SkillFolder], dict[str, str]]:+ folders = self.scan(skills_root, max_depth=max_depth)+ return folders, {+ folder.relative_path: _file_sha256(folder.entry)+ for folder in folders+ }+++def _file_sha256(path: Path) -> str:+ return hashlib.sha256(path.read_bytes()).hexdigest()diff --git a/jiuwenswarm/symphony/fingerprint/utils.py b/jiuwenswarm/symphony/fingerprint/utils.pynew file mode 100644index 0000000000..42726e0d67--- /dev/null+++ b/jiuwenswarm/symphony/fingerprint/utils.py@@ -0,0 +1,42 @@+# -*- coding: utf-8 -*-+"""Small shared utilities for fingerprint normalization."""++from __future__ import annotations++import re+import unicodedata+from typing import Any, Dict+++def normalize_token(raw: str) -> str:+ value = unicodedata.normalize("NFKC", raw)+ value = value.strip().lower()+ value = re.sub(r"[^a-z0-9]+", "_", value)+ value = re.sub(r"_+", "_", value).strip("_")+ return value+++def normalize_parameter_name(raw: str) -> str:+ return normalize_token(raw) or "input"+++def normalize_slug(raw: str) -> str:+ value = unicodedata.normalize("NFKC", raw)+ value = value.strip().lower().replace("_", "-")+ value = re.sub(r"[^a-z0-9-]+", "-", value)+ value = re.sub(r"-+", "-", value).strip("-")+ return value+++def normalize_human_name(raw: str) -> str:+ return str(raw).strip()+++def to_dict(value: Any) -> Dict[str, Any]:+ if isinstance(value, dict):+ return value+ if hasattr(value, "to_dict"):+ return value.to_dict()+ if hasattr(value, "__dict__"):+ return dict(value.__dict__)+ return {}\ No newline at end of filediff --git a/jiuwenswarm/symphony/graph/__init__.py b/jiuwenswarm/symphony/graph/__init__.pynew file mode 100644index 0000000000..2a907fb1f2--- /dev/null+++ b/jiuwenswarm/symphony/graph/__init__.py@@ -0,0 +1,51 @@+"""Offline Skill graph construction."""++from jiuwenswarm.symphony.graph.builders import ScoreLookupBuilder, SkillGraphBuilder+from jiuwenswarm.symphony.graph.candidates import CandidateGenerator+from jiuwenswarm.symphony.graph.matcher import (+ DEFAULT_THRESHOLDS,+ OntologyMatcher,+ OpenAICompatibleOntologyMatcher,+ validate_llm_matches,+)+from jiuwenswarm.symphony.graph.models import (+ ALLOWED_RELATION_TYPES,+ BuildManifest,+ GraphBuildResult,+ GraphDiagnostic,+ GraphEdge,+ GraphNode,+ LLMMatch,+ RelationCandidate,+ ScoreLookup,+ SkillGraph,+ SkillRegistry,+)+from jiuwenswarm.symphony.graph.pipeline import GraphBuilder+from jiuwenswarm.symphony.graph.registry import SkillRegistryBuilder+from jiuwenswarm.symphony.graph.writer import write_graph_build_result, write_json_file++__all__ = [+ "ALLOWED_RELATION_TYPES",+ "BuildManifest",+ "CandidateGenerator",+ "DEFAULT_THRESHOLDS",+ "GraphBuilder",+ "GraphBuildResult",+ "GraphDiagnostic",+ "GraphEdge",+ "GraphNode",+ "LLMMatch",+ "OntologyMatcher",+ "OpenAICompatibleOntologyMatcher",+ "RelationCandidate",+ "ScoreLookup",+ "ScoreLookupBuilder",+ "SkillGraph",+ "SkillGraphBuilder",+ "SkillRegistry",+ "SkillRegistryBuilder",+ "validate_llm_matches",+ "write_graph_build_result",+ "write_json_file",+]diff --git a/jiuwenswarm/symphony/graph/builders.py b/jiuwenswarm/symphony/graph/builders.pynew file mode 100644index 0000000000..5be7899dbd--- /dev/null+++ b/jiuwenswarm/symphony/graph/builders.py@@ -0,0 +1,204 @@+"""Build typed Skill graph and Score lookup artifacts."""++from __future__ import annotations++from collections import defaultdict+from typing import Dict, Iterable, List, Set++from jiuwenswarm.symphony.graph.lexicon import (+ ArtifactLexicon,+ DEFAULT_GRAPH_STOP_TERMS,+)+from jiuwenswarm.symphony.graph.models import (+ GraphEdge,+ GraphNode,+ LLMMatch,+ ScoreLookup,+ SkillGraph,+ SkillRegistry,+)+++IO_NAMES_EXCLUDED_FROM_EXACT_LOOKUP = frozenset(+ {+ "dependencies",+ "path",+ }+)+_GRAPH_TERM_LEXICON = ArtifactLexicon.create(+ stop_terms=DEFAULT_GRAPH_STOP_TERMS,+ min_token_length=3,+)+++class SkillGraphBuilder:+ """Build Skill graph nodes and accepted can_feed edges."""++ @staticmethod+ def build(+ registry: SkillRegistry,+ llm_matches: Iterable[LLMMatch],+ ) -> SkillGraph:+ nodes: Dict[str, GraphNode] = {}+ edges: Dict[str, GraphEdge] = {}++ for skill in registry.ordered_skills():+ nodes.setdefault(+ f"skill:{skill.id}",+ GraphNode(+ id=f"skill:{skill.id}",+ type="skill",+ label=skill.name or skill.id,+ properties={+ "skill_id": skill.id,+ "name": skill.name,+ "description": skill.description,+ "version": skill.version,+ "inputs": [item.to_dict() for item in skill.inputs],+ "outputs": [item.to_dict() for item in skill.outputs],+ },+ ),+ )++ for match in llm_matches:+ if not match.accepted or match.relation_type != "can_feed":+ continue+ edge = GraphEdge(+ source=f"skill:{match.source_id}",+ target=f"skill:{match.target_id}",+ type=match.relation_type,+ confidence=match.confidence,+ method=match.method,+ evidence={+ "candidate_id": match.candidate_id,+ "reasons": match.reasons,+ "supporting_fields": match.supporting_fields,+ },+ )+ edges.setdefault(edge.key, edge)++ ordered_nodes = []+ for node_id in sorted(nodes):+ node = nodes.get(node_id)+ if node is not None:+ ordered_nodes.append(node)+ return SkillGraph(+ nodes=ordered_nodes,+ edges=sorted(edges.values(), key=lambda edge: edge.key),+ )+++class ScoreLookupBuilder:+ """Build deterministic lookup tables for online Score retrieval."""++ def __init__(+ self,+ *,+ generic_io_names: Iterable[str] = IO_NAMES_EXCLUDED_FROM_EXACT_LOOKUP,+ max_io_bucket_size: int = 16,+ max_text_bucket_size: int = 24,+ ) -> None:+ self.lexicon = ArtifactLexicon.create(+ stop_terms=DEFAULT_GRAPH_STOP_TERMS,+ min_token_length=3,+ generic_io_names=generic_io_names,+ )+ self.max_io_bucket_size = max(1, max_io_bucket_size)+ self.max_text_bucket_size = max(2, max_text_bucket_size)++ def build(self, registry: SkillRegistry, graph: SkillGraph) -> ScoreLookup:+ by_output: Dict[str, Set[str]] = defaultdict(set)+ by_input: Dict[str, Set[str]] = defaultdict(set)+ by_data_type: Dict[str, Set[str]] = defaultdict(set)+ by_text_term: Dict[str, Set[str]] = defaultdict(set)++ for skill in registry.ordered_skills():+ for output in skill.outputs:+ if not self.lexicon.is_generic_io_name(output.name):+ by_output[output.name].add(skill.id)+ by_data_type[output.type].add(skill.id)+ for parameter in skill.inputs:+ if not self.lexicon.is_generic_io_name(parameter.name):+ by_input[parameter.name].add(skill.id)+ by_data_type[parameter.type].add(skill.id)+ for term in _skill_terms(skill):+ by_text_term[term].add(skill.id)++ neighbors: Dict[str, Set[str]] = defaultdict(set)+ upstream_by_input: Dict[str, Set[str]] = defaultdict(set)+ downstream_by_output: Dict[str, Set[str]] = defaultdict(set)+ skill_inputs = {+ skill.id: {parameter.name for parameter in skill.inputs}+ for skill in registry.ordered_skills()+ }+ skill_outputs = {+ skill.id: {output.name for output in skill.outputs}+ for skill in registry.ordered_skills()+ }++ for edge in graph.edges:+ if edge.source.startswith("skill:") and edge.target.startswith("skill:"):+ source_id = edge.source.removeprefix("skill:")+ target_id = edge.target.removeprefix("skill:")+ neighbors[source_id].add(target_id)+ if edge.type != "can_feed":+ continue+ shared = sorted(+ skill_outputs.get(source_id, set())+ & skill_inputs.get(target_id, set())+ )+ for name in shared:+ if self.lexicon.is_generic_io_name(name):+ continue+ upstream_by_input[name].add(source_id)+ downstream_by_output[name].add(target_id)++ return ScoreLookup(+ by_output=_freeze_lookup(+ by_output,+ max_bucket_size=self.max_io_bucket_size,+ ),+ by_input=_freeze_lookup(+ by_input,+ max_bucket_size=self.max_io_bucket_size,+ ),+ by_data_type=_freeze_lookup(by_data_type),+ neighbors=_freeze_lookup(neighbors),+ upstream_by_input=_freeze_lookup(+ upstream_by_input,+ max_bucket_size=self.max_io_bucket_size,+ ),+ downstream_by_output=_freeze_lookup(+ downstream_by_output,+ max_bucket_size=self.max_io_bucket_size,+ ),+ by_text_term=_freeze_lookup(+ by_text_term,+ max_bucket_size=self.max_text_bucket_size,+ ),+ )+++def _freeze_lookup(+ lookup: Dict[str, Set[str]],+ *,+ max_bucket_size: int | None = None,+) -> Dict[str, List[str]]:+ frozen = {}+ for key, values in sorted(lookup.items()):+ if max_bucket_size is not None and len(values) > max_bucket_size:+ continue+ frozen[key] = sorted(values)+ return frozen+++def _skill_terms(skill) -> Set[str]:+ chunks: List[str] = [skill.id, skill.name, skill.description]+ chunks.extend(item.name for item in skill.inputs)+ chunks.extend(item.description for item in skill.inputs)+ chunks.extend(item.name for item in skill.outputs)+ chunks.extend(item.description for item in skill.outputs)+ terms: Set[str] = set()+ for chunk in chunks:+ terms.update(_GRAPH_TERM_LEXICON.tokenize(chunk))+ return termsdiff --git a/jiuwenswarm/symphony/graph/candidates/__init__.py b/jiuwenswarm/symphony/graph/candidates/__init__.pynew file mode 100644index 0000000000..f517243421--- /dev/null+++ b/jiuwenswarm/symphony/graph/candidates/__init__.py@@ -0,0 +1,5 @@+"""Candidate relation generation for Skill graph."""++from jiuwenswarm.symphony.graph.candidates.generator import CandidateGenerator++__all__ = ["CandidateGenerator"]\ No newline at end of filediff --git a/jiuwenswarm/symphony/graph/candidates/generator.py b/jiuwenswarm/symphony/graph/candidates/generator.pynew file mode 100644index 0000000000..767dbf6996--- /dev/null+++ b/jiuwenswarm/symphony/graph/candidates/generator.py@@ -0,0 +1,697 @@+"""Deterministic high-recall relation candidate generation."""++from __future__ import annotations++import logging+from collections import defaultdict+from typing import Dict, Iterable, List, MutableMapping, Set, Tuple++from jiuwenswarm.symphony.fingerprint.models import (+ ArtifactSpec,+ ParameterSpec,+ SkillFingerprint,+)+from jiuwenswarm.symphony.fingerprint.normalize.data_type_vocab import (+ DataTypeVocabulary,+)+from jiuwenswarm.symphony.graph.lexicon import (+ ArtifactLexicon,+ DEFAULT_GRAPH_STOP_TERMS,+)+from jiuwenswarm.symphony.graph.models import (+ ALLOWED_RELATION_TYPES,+ RelationCandidate,+ SkillRegistry,+)+++PRIORITY_RANK = {"high": 3, "medium": 2, "low": 1}+# These names are too broad for exact-name edge generation. They are still+# available for text indexing and semantic evidence; only exact I/O matching+# treats them as generic.+IO_NAMES_EXCLUDED_FROM_EDGE_BUILDING = frozenset(+ {+ "dependencies",+ "path",+ }+)+# Textual coercion is intentionally limited to inputs whose names clearly mean+# "free-form content". This is a graph-generation heuristic, not a DataType.+GENERIC_CONTENT_INPUT_NAMES = frozenset(+ {+ "body",+ "content",+ "prompt",+ "query",+ "question",+ "text",+ "sources",+ }+)+_GRAPH_TERM_LEXICON = ArtifactLexicon.create(+ stop_terms=DEFAULT_GRAPH_STOP_TERMS,+ min_token_length=3,+)+LOGGER = logging.getLogger("jiuwenswarm.symphony.graph.candidates")+++class CandidateGenerator:+ """Generate high-recall Skill-Skill relation candidates."""++ def __init__(+ self,+ *,+ max_candidates_per_skill_relation: int = 12,+ max_port_mappings_per_candidate: int = 12,+ generic_io_names: Iterable[str] = IO_NAMES_EXCLUDED_FROM_EDGE_BUILDING,+ max_exact_io_pair_fanout: int = 64,+ ) -> None:+ self.max_candidates_per_skill_relation = max_candidates_per_skill_relation+ self.max_port_mappings_per_candidate = max(1, max_port_mappings_per_candidate)+ self.evidence_merger = CandidateEvidenceMerger(+ max_port_mappings=self.max_port_mappings_per_candidate,+ )+ self.lexicon = ArtifactLexicon.create(+ stop_terms=DEFAULT_GRAPH_STOP_TERMS,+ min_token_length=3,+ generic_io_names=generic_io_names,+ )+ self.max_exact_io_pair_fanout = max(1, max_exact_io_pair_fanout)++ def generate(self, registry: SkillRegistry) -> List[RelationCandidate]:+ skills = registry.ordered_skills()+ skill_terms = {skill.id: _skill_terms(skill) for skill in skills}+ indexes = CandidateIndexes.from_skills(skills)+ candidates: Dict[Tuple[str, str], RelationCandidate] = {}++ LOGGER.debug("candidate_generation_start skill_count=%s", len(skills))+ self._add_exact_io_candidates(indexes, candidates)+ self._add_semantic_overlap_candidates(skills, skill_terms, candidates)+ self._add_textual_coercion_candidates(skills, skill_terms, candidates)++ ordered = sorted(+ candidates.values(),+ key=lambda item: (+ item.source_id,+ -PRIORITY_RANK.get(item.priority, 0),+ item.target_id,+ ",".join(item.relation_hints),+ ),+ )+ limited = self._limit_per_skill_relation(ordered)+ LOGGER.debug(+ "candidate_generation_done generated_count=%s emitted_count=%s",+ len(ordered),+ len(limited),+ )+ return limited++ def _add_exact_io_candidates(+ self,+ indexes: "CandidateIndexes",+ candidates: MutableMapping[Tuple[str, str], RelationCandidate],+ ) -> None:+ for name in sorted(set(indexes.by_output_name) & set(indexes.by_input_name)):+ if self.lexicon.is_generic_io_name(name):+ LOGGER.debug(+ "candidate_skipped reason=generic_io_name "+ "method=exact_io_match name=%s output_skills=%s input_skills=%s",+ name,+ ",".join(sorted(indexes.by_output_name[name])),+ ",".join(sorted(indexes.by_input_name[name])),+ )+ continue+ pair_fanout = (+ len(indexes.by_output_name[name]) * len(indexes.by_input_name[name])+ )+ if pair_fanout > self.max_exact_io_pair_fanout:+ LOGGER.debug(+ "candidate_skipped reason=max_exact_io_pair_fanout "+ "method=exact_io_match name=%s fanout=%s limit=%s "+ "output_skills=%s input_skills=%s",+ name,+ pair_fanout,+ self.max_exact_io_pair_fanout,+ ",".join(sorted(indexes.by_output_name[name])),+ ",".join(sorted(indexes.by_input_name[name])),+ )+ continue+ for source_id in sorted(indexes.by_output_name[name]):+ for target_id in sorted(indexes.by_input_name[name]):+ if source_id == target_id:+ continue+ source_outputs = indexes.outputs_by_skill_name[(source_id, name)]+ target_inputs = indexes.inputs_by_skill_name[(target_id, name)]+ port_mappings = []+ for output in source_outputs:+ for parameter in target_inputs:+ if not _can_feed_by_exact_or_subtype(+ output.type,+ parameter.type,+ ):+ continue+ port_mappings.append(+ _port_mapping(+ output,+ parameter,+ match_method="exact_io_match",+ match_reason=_match_reason_exact_io(+ output.type,+ parameter.type,+ ),+ )+ )+ if not port_mappings:+ continue+ self._merge_candidate(+ candidates,+ RelationCandidate(+ source_id=source_id,+ target_id=target_id,+ relation_hints=["can_feed"],+ candidate_methods=["exact_io_match"],+ priority="high",+ evidence={+ "matched_terms": [name],+ "source_outputs": [+ item.to_dict() for item in source_outputs+ ],+ "target_inputs": [+ item.to_dict() for item in target_inputs+ ],+ "port_mappings": port_mappings,+ },+ ),+ )++ def _add_semantic_overlap_candidates(+ self,+ skills: List[SkillFingerprint],+ skill_terms: Dict[str, Set[str]],+ candidates: MutableMapping[Tuple[str, str], RelationCandidate],+ ) -> None:+ for source in skills:+ source_terms = skill_terms[source.id]+ for target in skills:+ if source.id == target.id:+ continue+ target_terms = skill_terms[target.id]+ shared_terms = sorted(source_terms & target_terms)+ for output in source.outputs:+ for parameter in target.inputs:+ if (+ output.name == parameter.name+ and self.lexicon.is_generic_io_name(output.name)+ ):+ continue+ uses_remote_reference = _can_feed_by_remote_reference(+ output,+ parameter,+ )+ if not uses_remote_reference:+ if not _can_feed_by_type(output.type, parameter.type):+ continue+ if not _has_semantic_overlap(output, parameter):+ continue+ mapping = _port_mapping(+ output,+ parameter,+ match_method="semantic_overlap_match",+ match_reason=(+ _match_reason_remote_reference(output, parameter)+ if uses_remote_reference+ else _match_reason_semantic_overlap(output, parameter)+ ),+ )+ self._merge_candidate(+ candidates,+ RelationCandidate(+ source_id=source.id,+ target_id=target.id,+ relation_hints=["can_feed"],+ candidate_methods=["semantic_overlap_match"],+ priority="medium",+ evidence={+ "matched_terms": shared_terms,+ "source_outputs": [output.to_dict()],+ "target_inputs": [parameter.to_dict()],+ "port_mappings": [mapping],+ "matched_types": [+ f"{output.type}->{parameter.type}"+ ],+ },+ ),+ )++ def _add_textual_coercion_candidates(+ self,+ skills: List[SkillFingerprint],+ skill_terms: Dict[str, Set[str]],+ candidates: MutableMapping[Tuple[str, str], RelationCandidate],+ ) -> None:+ for source in skills:+ source_terms = skill_terms[source.id]+ for target in skills:+ if source.id == target.id:+ continue+ target_terms = skill_terms[target.id]+ shared_terms = sorted(source_terms & target_terms)+ for output in source.outputs:+ for parameter in target.inputs:+ if not _can_feed_by_type(output.type, parameter.type):+ continue+ input_terms = _tokenize(+ f"{parameter.name} {parameter.description}"+ )+ if not _can_feed_via_textual_coercion(+ output,+ parameter,+ input_terms,+ ):+ continue+ mapping = _port_mapping(+ output,+ parameter,+ match_method="textual_coercion_match",+ match_reason=_match_reason_textual_coercion(+ output,+ parameter,+ ),+ )+ self._merge_candidate(+ candidates,+ RelationCandidate(+ source_id=source.id,+ target_id=target.id,+ relation_hints=["can_feed"],+ candidate_methods=["textual_coercion_match"],+ priority="low",+ evidence={+ "matched_terms": shared_terms,+ "source_outputs": [output.to_dict()],+ "target_inputs": [parameter.to_dict()],+ "port_mappings": [mapping],+ "matched_types": [+ f"{output.type}->{parameter.type}"+ ],+ },+ ),+ )++ def _merge_candidate(+ self,+ candidates: MutableMapping[Tuple[str, str], RelationCandidate],+ candidate: RelationCandidate,+ ) -> None:+ relation_hints = [+ hint for hint in candidate.relation_hints if hint in ALLOWED_RELATION_TYPES+ ]+ if not relation_hints:+ return+ _debug_candidate_generated(candidate, relation_hints)+ key = (candidate.source_id, candidate.target_id)+ existing = candidates.get(key)+ if existing is None:+ candidates[key] = self.evidence_merger.create(candidate, relation_hints)+ return++ candidates[key] = self.evidence_merger.merge(existing, candidate, relation_hints)++ def _limit_per_skill_relation(+ self, candidates: List[RelationCandidate]+ ) -> List[RelationCandidate]:+ buckets: Dict[str, List[RelationCandidate]] = defaultdict(list)+ for candidate in candidates:+ buckets[candidate.source_id].append(candidate)++ limited: List[RelationCandidate] = []+ for key in sorted(buckets):+ ordered_bucket = sorted(+ buckets[key],+ key=lambda item: (+ -PRIORITY_RANK.get(item.priority, 0),+ item.target_id,+ ",".join(item.relation_hints),+ ),+ )+ kept = ordered_bucket[: self.max_candidates_per_skill_relation]+ dropped = ordered_bucket[self.max_candidates_per_skill_relation:]+ limited.extend(kept)+ for candidate in dropped:+ LOGGER.debug(+ "candidate_skipped reason=max_candidates_per_skill_relation "+ "source=%s target=%s priority=%s methods=%s "+ "relation_hints=%s limit=%s",+ candidate.source_id,+ candidate.target_id,+ candidate.priority,+ ",".join(candidate.candidate_methods),+ ",".join(candidate.relation_hints),+ self.max_candidates_per_skill_relation,+ )+ return sorted(+ limited,+ key=lambda item: (+ item.source_id,+ -PRIORITY_RANK.get(item.priority, 0),+ item.target_id,+ ",".join(item.relation_hints),+ ),+ )+++class CandidateIndexes:+ def __init__(self) -> None:+ self.by_output_name: Dict[str, Set[str]] = defaultdict(set)+ self.by_input_name: Dict[str, Set[str]] = defaultdict(set)+ self.outputs_by_skill_name: Dict[Tuple[str, str], List[ArtifactSpec]] = (+ defaultdict(list)+ )+ self.inputs_by_skill_name: Dict[Tuple[str, str], List[ParameterSpec]] = (+ defaultdict(list)+ )++ @classmethod+ def from_skills(cls, skills: Iterable[SkillFingerprint]) -> "CandidateIndexes":+ indexes = cls()+ for skill in skills:+ for output in skill.outputs:+ indexes.by_output_name[output.name].add(skill.id)+ indexes.outputs_by_skill_name[(skill.id, output.name)].append(output)+ for parameter in skill.inputs:+ indexes.by_input_name[parameter.name].add(skill.id)+ indexes.inputs_by_skill_name[(skill.id, parameter.name)].append(+ parameter+ )+ return indexes+++class CandidateEvidenceMerger:+ """Merge directional evidence for repeated source-target candidates."""++ def __init__(self, *, max_port_mappings: int) -> None:+ self.max_port_mappings = max(1, max_port_mappings)++ def create(+ self,+ candidate: RelationCandidate,+ relation_hints: List[str],+ ) -> RelationCandidate:+ return self._limit_port_mappings(+ RelationCandidate(+ source_id=candidate.source_id,+ target_id=candidate.target_id,+ relation_hints=sorted(set(relation_hints)),+ candidate_methods=sorted(set(candidate.candidate_methods)),+ priority=candidate.priority,+ evidence=self._directional_evidence(candidate),+ )+ )++ def merge(+ self,+ existing: RelationCandidate,+ candidate: RelationCandidate,+ relation_hints: List[str],+ ) -> RelationCandidate:+ priority = (+ candidate.priority+ if PRIORITY_RANK.get(candidate.priority, 0)+ > PRIORITY_RANK.get(existing.priority, 0)+ else existing.priority+ )+ evidence = _merge_directional_evidence(+ existing.evidence,+ self._directional_evidence(candidate),+ )+ return self._limit_port_mappings(+ RelationCandidate(+ source_id=existing.source_id,+ target_id=existing.target_id,+ relation_hints=sorted(set(existing.relation_hints) | set(relation_hints)),+ candidate_methods=sorted(+ set(existing.candidate_methods) | set(candidate.candidate_methods)+ ),+ priority=priority,+ evidence=evidence,+ )+ )++ @staticmethod+ def _directional_evidence(candidate: RelationCandidate) -> Dict[str, object]:+ direction_key = f"{candidate.source_id}->{candidate.target_id}"+ return {"directions": {direction_key: candidate.evidence}}++ def _limit_port_mappings(self, candidate: RelationCandidate) -> RelationCandidate:+ return _limit_port_mappings_for_candidate(candidate, self.max_port_mappings)+++def _merge_evidence(+ left: Dict[str, object],+ right: Dict[str, object],+) -> Dict[str, object]:+ merged = dict(left)+ for key, value in right.items():+ if key not in merged:+ merged[key] = value+ continue+ if isinstance(merged[key], list) and isinstance(value, list):+ merged_value = _dedupe_list(merged[key] + value)+ if key == "matched_types":+ merged[key] = sorted(str(item) for item in merged_value)+ else:+ merged[key] = merged_value+ return merged+++def _merge_directional_evidence(+ left: Dict[str, object],+ right: Dict[str, object],+) -> Dict[str, object]:+ merged = dict(left)+ directions = dict(merged.get("directions", {}))+ for direction, evidence in dict(right.get("directions", {})).items():+ if (+ direction in directions+ and isinstance(directions[direction], dict)+ and isinstance(evidence, dict)+ ):+ directions[direction] = _merge_evidence(directions[direction], evidence)+ else:+ directions[direction] = evidence+ merged["directions"] = directions+ return merged+++def _limit_port_mappings_for_candidate(+ candidate: RelationCandidate,+ max_port_mappings: int,+) -> RelationCandidate:+ directions = {}+ for direction, evidence in dict(candidate.evidence.get("directions", {})).items():+ if not isinstance(evidence, dict):+ directions[direction] = evidence+ continue+ limited_evidence = dict(evidence)+ mappings = [+ mapping+ for mapping in limited_evidence.get("port_mappings", [])+ if isinstance(mapping, dict)+ ]+ limited_evidence["port_mappings"] = _dedupe_port_mappings(+ sorted(mappings, key=_port_mapping_sort_key)+ )[:max_port_mappings]+ directions[direction] = limited_evidence+ return RelationCandidate(+ source_id=candidate.source_id,+ target_id=candidate.target_id,+ relation_hints=candidate.relation_hints,+ candidate_methods=candidate.candidate_methods,+ priority=candidate.priority,+ evidence={**candidate.evidence, "directions": directions},+ )+++def _dedupe_port_mappings(values: List[dict]) -> List[dict]:+ seen = set()+ result = []+ for value in values:+ marker = (+ value.get("source_output"),+ value.get("source_type"),+ value.get("target_input"),+ value.get("target_type"),+ )+ if marker in seen:+ continue+ seen.add(marker)+ result.append(value)+ return result+++def _port_mapping_sort_key(mapping: dict) -> tuple[int, str, str]:+ method_rank = 0 if mapping.get("match_method") == "exact_io_match" else 1+ return (+ method_rank,+ str(mapping.get("source_output") or ""),+ str(mapping.get("target_input") or ""),+ )+++def _dedupe_list(values: List[object]) -> List[object]:+ seen = set()+ result = []+ for value in values:+ marker = repr(value)+ if marker in seen:+ continue+ seen.add(marker)+ result.append(value)+ return result+++def _debug_candidate_generated(+ candidate: RelationCandidate,+ relation_hints: List[str],+) -> None:+ if not LOGGER.isEnabledFor(logging.DEBUG):+ return+ evidence = candidate.evidence+ LOGGER.debug(+ "candidate_generated source=%s target=%s priority=%s methods=%s "+ "relation_hints=%s matched_terms=%s matched_types=%s",+ candidate.source_id,+ candidate.target_id,+ candidate.priority,+ ",".join(candidate.candidate_methods),+ ",".join(relation_hints),+ ",".join(str(item) for item in evidence.get("matched_terms", [])),+ ",".join(str(item) for item in evidence.get("matched_types", [])),+ )+++_DATA_TYPE_VOCAB = DataTypeVocabulary.default()+++def _skill_terms(skill: SkillFingerprint) -> Set[str]:+ terms: Set[str] = set()+ chunks = [skill.id, skill.name, skill.description]+ chunks.extend(item.name for item in skill.inputs)+ chunks.extend(item.description for item in skill.inputs)+ chunks.extend(item.name for item in skill.outputs)+ chunks.extend(item.description for item in skill.outputs)+ for chunk in chunks:+ terms.update(_tokenize(chunk))+ return terms+++def _has_semantic_overlap(+ output: ArtifactSpec,+ parameter: ParameterSpec,+) -> bool:+ if output.name == parameter.name:+ return True+ output_terms = _tokenize(f"{output.name} {output.description}")+ input_terms = _tokenize(f"{parameter.name} {parameter.description}")+ return bool(output_terms & input_terms)+++def _can_feed_by_type(output_type: str, input_type: str) -> bool:+ return _DATA_TYPE_VOCAB.can_feed_by_type(output_type, input_type)+++def _can_feed_by_remote_reference(output: ArtifactSpec, parameter: ParameterSpec) -> bool:+ if output.type != "url":+ return False+ if parameter.type not in {"file", "image"}:+ return False+ return _accepts_remote_reference(parameter)+++def _accepts_remote_reference(parameter: ParameterSpec) -> bool:+ inference = _DATA_TYPE_VOCAB.infer_from_io_semantics(+ parameter.name,+ parameter.description,+ )+ return inference is not None and inference.data_type == "url"+++def _can_feed_by_exact_or_subtype(output_type: str, input_type: str) -> bool:+ if output_type == input_type:+ return True+ return _DATA_TYPE_VOCAB.is_subtype(output_type, input_type)+++def _can_feed_via_textual_coercion(+ output: ArtifactSpec,+ parameter: ParameterSpec,+ input_terms: Set[str],+) -> bool:+ if output.type not in _DATA_TYPE_VOCAB.CONTENT_CARRIER_TYPES:+ return False+ if parameter.type not in _DATA_TYPE_VOCAB.CONTENT_CARRIER_TYPES:+ return False+ if not _is_generic_content_input(parameter, input_terms):+ return False+ return True+++def _is_generic_content_input(parameter: ParameterSpec, input_terms: Set[str]) -> bool:+ return parameter.name in GENERIC_CONTENT_INPUT_NAMES or bool(+ input_terms & GENERIC_CONTENT_INPUT_NAMES+ )+++def _port_mapping(+ output: ArtifactSpec,+ parameter: ParameterSpec,+ *,+ match_method: str,+ match_reason: str,+) -> dict:+ return {+ "source_output": output.name,+ "source_type": output.type,+ "target_input": parameter.name,+ "target_type": parameter.type,+ "match_reason": match_reason,+ "match_method": match_method,+ }+++def _match_reason_exact_io(output_type: str, input_type: str) -> str:+ if output_type == input_type:+ return "source output and target input share the same normalized name and type"+ return (+ f"source output type '{output_type}' is a subtype of "+ f"target input type '{input_type}'"+ )+++def _match_reason_semantic_overlap(+ output: ArtifactSpec,+ parameter: ParameterSpec,+) -> str:+ if output.name == parameter.name:+ return "source output and target input share the same normalized name"+ return "source output and target input share semantic terms"+++def _match_reason_remote_reference(+ output: ArtifactSpec,+ parameter: ParameterSpec,+) -> str:+ del output, parameter+ return "source output URL can satisfy target file-like input that accepts remote references"+++def _match_reason_textual_coercion(+ output: ArtifactSpec,+ parameter: ParameterSpec,+) -> str:+ del output, parameter+ return "textual output can be coerced to generic content input"+++def _tokenize(text: str) -> Set[str]:+ return _GRAPH_TERM_LEXICON.tokenize(text)diff --git a/jiuwenswarm/symphony/graph/lexicon.py b/jiuwenswarm/symphony/graph/lexicon.pynew file mode 100644index 0000000000..0f8655ed20--- /dev/null+++ b/jiuwenswarm/symphony/graph/lexicon.py@@ -0,0 +1,103 @@+"""Shared lexical helpers for Skill graph candidate generation and indexing."""++from __future__ import annotations++import re+import unicodedata+from dataclasses import dataclass+from typing import Iterable++DEFAULT_GRAPH_STOP_TERMS = frozenset(+ {+ "and",+ "are",+ "for",+ "from",+ "into",+ "the",+ "this",+ "that",+ "with",+ }+)++DEFAULT_PLANNING_STOP_TERMS = frozenset(+ {+ "a",+ "an",+ "and",+ "are",+ "for",+ "from",+ "in",+ "into",+ "of",+ "on",+ "the",+ "this",+ "that",+ "to",+ "with",+ }+)++_ASCII_TOKEN_RE = re.compile(r"[a-z0-9]+")+_CJK_CHUNK_RE = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff]+")+++@dataclass(frozen=True)+class ArtifactLexicon:+ """Tokenization and generic-name rules for one graph lexical profile."""++ stop_terms: frozenset[str]+ min_token_length: int+ generic_io_names: frozenset[str] = frozenset()++ @classmethod+ def create(+ cls,+ *,+ stop_terms: Iterable[str],+ min_token_length: int,+ generic_io_names: Iterable[str] = (),+ ) -> "ArtifactLexicon":+ return cls(+ stop_terms=frozenset(normalize_text(term) for term in stop_terms),+ min_token_length=max(1, int(min_token_length)),+ generic_io_names=normalize_terms(generic_io_names),+ )++ def tokenize(self, text: str) -> set[str]:+ normalized = normalize_text(text)+ tokens = set()++ for token in _ASCII_TOKEN_RE.findall(normalized):+ if len(token) >= self.min_token_length and token not in self.stop_terms:+ tokens.add(token)++ for chunk in _CJK_CHUNK_RE.findall(normalized):+ if len(chunk) < 2:+ continue+ tokens.update(_cjk_terms(chunk))++ return tokens++ def is_generic_io_name(self, name: object) -> bool:+ return normalize_text(name) in self.generic_io_names+++def normalize_text(text: object) -> str:+ return unicodedata.normalize("NFKC", str(text)).lower()+++def normalize_terms(terms: Iterable[str]) -> frozenset[str]:+ return frozenset(normalize_text(term) for term in terms)+++def _cjk_terms(chunk: str) -> set[str]:+ terms = {chunk}+ if len(chunk) == 2:+ return terms+ for index in range(len(chunk) - 1):+ terms.add(chunk[index: index + 2])+ return termsdiff --git a/jiuwenswarm/symphony/graph/matcher/__init__.py b/jiuwenswarm/symphony/graph/matcher/__init__.pynew file mode 100644index 0000000000..1a9ba5e115--- /dev/null+++ b/jiuwenswarm/symphony/graph/matcher/__init__.py@@ -0,0 +1,15 @@+"""LLM-backed relation matching for Skill graph."""++from jiuwenswarm.symphony.graph.matcher.matcher import (+ DEFAULT_THRESHOLDS,+ OntologyMatcher,+ OpenAICompatibleOntologyMatcher,+ validate_llm_matches,+)++__all__ = [+ "DEFAULT_THRESHOLDS",+ "OntologyMatcher",+ "OpenAICompatibleOntologyMatcher",+ "validate_llm_matches",+]diff --git a/jiuwenswarm/symphony/graph/matcher/consensus.py b/jiuwenswarm/symphony/graph/matcher/consensus.pynew file mode 100644index 0000000000..05a6ad9a33--- /dev/null+++ b/jiuwenswarm/symphony/graph/matcher/consensus.py@@ -0,0 +1,180 @@+"""Consensus merging for order-swapped LLM relation matching."""++from __future__ import annotations++from typing import Any, Dict, List, Optional++from jiuwenswarm.symphony.graph.models import GraphDiagnostic, LLMMatch+++def consensus_matches(+ first_matches: List[LLMMatch],+ second_matches: List[LLMMatch],+) -> tuple[List[LLMMatch], List[GraphDiagnostic]]:+ first_by_key = {+ _match_key(match): match for match in first_matches if match.accepted+ }+ second_by_key = {+ _match_key(match): match for match in second_matches if match.accepted+ }+ first_all_by_key = _matches_by_key(first_matches)+ second_all_by_key = _matches_by_key(second_matches)+ first_by_candidate = _matches_by_candidate(first_matches)+ second_by_candidate = _matches_by_candidate(second_matches)+ shared_keys = sorted(set(first_by_key) & set(second_by_key))+ consensus: List[LLMMatch] = []+ diagnostics: List[GraphDiagnostic] = []++ for key in shared_keys:+ first = first_by_key[key]+ second = second_by_key[key]+ consensus.append(+ LLMMatch(+ source_id=first.source_id,+ target_id=first.target_id,+ relation_type=first.relation_type,+ confidence=min(first.confidence, second.confidence),+ method="llm_consensus_match",+ reasons=_dedupe_strings(first.reasons + second.reasons),+ supporting_fields=_merge_supporting_fields(+ first.supporting_fields,+ second.supporting_fields,+ ),+ candidate_id=first.candidate_id,+ accepted=True,+ raw={+ "first": first.raw,+ "second": second.raw,+ "first_confidence": first.confidence,+ "second_confidence": second.confidence,+ },+ )+ )++ for key in sorted(set(first_by_key) ^ set(second_by_key)):+ match = first_by_key.get(key) or second_by_key[key]+ present_in = "first_run" if key in first_by_key else "second_run"+ missing_from = "second_run" if present_in == "first_run" else "first_run"+ diagnostics.append(+ GraphDiagnostic(+ stage="llm_match",+ severity="info",+ code="no_consensus_match",+ message="LLM match did not appear in both order-swapped runs.",+ skill_id=match.source_id,+ details={+ "candidate_id": match.candidate_id,+ "source_id": match.source_id,+ "target_id": match.target_id,+ "relation_type": match.relation_type,+ "present_in": present_in,+ "missing_consensus_from": missing_from,+ "consensus_key": _match_key_details(key),+ "first_run": _consensus_run_details(+ accepted_match=first_by_key.get(key),+ same_key_matches=first_all_by_key.get(key, []),+ same_candidate_matches=first_by_candidate.get(+ match.candidate_id, []+ ),+ ),+ "second_run": _consensus_run_details(+ accepted_match=second_by_key.get(key),+ same_key_matches=second_all_by_key.get(key, []),+ same_candidate_matches=second_by_candidate.get(+ match.candidate_id, []+ ),+ ),+ "match": match.to_dict(),+ },+ )+ )++ return consensus, diagnostics+++def _matches_by_key(+ matches: List[LLMMatch],+) -> Dict[tuple[str, str, str, Optional[str]], List[LLMMatch]]:+ grouped: Dict[tuple[str, str, str, Optional[str]], List[LLMMatch]] = {}+ for match in matches:+ grouped.setdefault(_match_key(match), []).append(match)+ return grouped+++def _matches_by_candidate(+ matches: List[LLMMatch],+) -> Dict[Optional[str], List[LLMMatch]]:+ grouped: Dict[Optional[str], List[LLMMatch]] = {}+ for match in matches:+ grouped.setdefault(match.candidate_id, []).append(match)+ return grouped+++def _consensus_run_details(+ *,+ accepted_match: Optional[LLMMatch],+ same_key_matches: List[LLMMatch],+ same_candidate_matches: List[LLMMatch],+) -> Dict[str, Any]:+ if accepted_match is not None:+ status = "accepted"+ elif same_key_matches:+ status = "same_key_not_accepted"+ elif same_candidate_matches:+ status = "same_candidate_different_match"+ else:+ status = "not_returned"++ return {+ "status": status,+ "accepted_match": (+ accepted_match.to_dict() if accepted_match is not None else None+ ),+ "same_key_matches": [match.to_dict() for match in same_key_matches],+ "same_candidate_matches": [+ match.to_dict() for match in same_candidate_matches+ ],+ }+++def _match_key(match: LLMMatch) -> tuple[str, str, str, Optional[str]]:+ return (+ match.source_id,+ match.target_id,+ match.relation_type,+ match.candidate_id,+ )+++def _match_key_details(+ key: tuple[str, str, str, Optional[str]]+) -> Dict[str, Optional[str]]:+ source_id, target_id, relation_type, candidate_id = key+ return {+ "source_id": source_id,+ "target_id": target_id,+ "relation_type": relation_type,+ "candidate_id": candidate_id,+ }+++def _dedupe_strings(values: List[str]) -> List[str]:+ seen = set()+ result = []+ for value in values:+ if value in seen:+ continue+ seen.add(value)+ result.append(value)+ return result+++def _merge_supporting_fields(left: Dict[str, Any], right: Dict[str, Any]) -> Dict[str, Any]:+ merged = dict(left)+ for key, value in right.items():+ if key not in merged:+ merged[key] = value+ continue+ if isinstance(merged[key], list) and isinstance(value, list):+ merged[key] = _dedupe_strings([str(item) for item in merged[key] + value])+ return mergeddiff --git a/jiuwenswarm/symphony/graph/matcher/constants.py b/jiuwenswarm/symphony/graph/matcher/constants.pynew file mode 100644index 0000000000..ea3c923a2f--- /dev/null+++ b/jiuwenswarm/symphony/graph/matcher/constants.py@@ -0,0 +1,5 @@+"""Shared matcher constants."""++DEFAULT_THRESHOLDS = {+ "can_feed": 0.7,+}diff --git a/jiuwenswarm/symphony/graph/matcher/matcher.py b/jiuwenswarm/symphony/graph/matcher/matcher.pynew file mode 100644index 0000000000..bd557ec553--- /dev/null+++ b/jiuwenswarm/symphony/graph/matcher/matcher.py@@ -0,0 +1,17 @@+"""LLM-backed ontology relation matching."""++from jiuwenswarm.symphony.graph.matcher.openai import (+ DEFAULT_THRESHOLDS,+ MatchProgress,+ OntologyMatcher,+ OpenAICompatibleOntologyMatcher,+)+from jiuwenswarm.symphony.graph.matcher.validation import validate_llm_matches++__all__ = [+ "DEFAULT_THRESHOLDS",+ "MatchProgress",+ "OntologyMatcher",+ "OpenAICompatibleOntologyMatcher",+ "validate_llm_matches",+]diff --git a/jiuwenswarm/symphony/graph/matcher/openai.py b/jiuwenswarm/symphony/graph/matcher/openai.pynew file mode 100644index 0000000000..9436b4c53e--- /dev/null+++ b/jiuwenswarm/symphony/graph/matcher/openai.py@@ -0,0 +1,248 @@+"""OpenAI-compatible ontology relation matcher."""++from __future__ import annotations++import asyncio+import json+from typing import Any, Dict, Iterable, List, Optional, Protocol++from jiuwenswarm.symphony.graph.matcher.constants import DEFAULT_THRESHOLDS+from jiuwenswarm.symphony.graph.matcher.consensus import consensus_matches+from jiuwenswarm.symphony.graph.matcher.prompt import SYSTEM_PROMPT, build_llm_context+from jiuwenswarm.symphony.graph.matcher.validation import validate_llm_matches+from jiuwenswarm.symphony.graph.models import GraphDiagnostic, LLMMatch, RelationCandidate, SkillRegistry+from jiuwenswarm.symphony.llm import LLMConfig, create_llm_client, llm_usage_context++_LOW_REASONING_REQUEST_OVERRIDES = {+ "extra_body": {"thinking": {"type": "disabled"}},+}+++class OntologyMatcher(Protocol):+ """Protocol for relation candidate matchers."""++ async def match(+ self,+ registry: SkillRegistry,+ candidates: Iterable[RelationCandidate],+ ) -> List[LLMMatch]:+ ...+++class MatchProgress(Protocol):+ """Progress callback for LLM candidate matching."""++ def __call__(self, event: str, current: int, total: int, details: Dict[str, Any]) -> None:+ ...+++class OpenAICompatibleOntologyMatcher:+ """Validate relation candidates through an OpenAI-compatible chat endpoint."""++ def __init__(+ self,+ config: LLMConfig,+ *,+ batch_size: int = 12,+ max_workers: int = 1,+ require_consensus: bool = True,+ prompt_version: str = "Orchestration-graph-match-v1",+ thresholds: Optional[Dict[str, float]] = None,+ progress: Optional[MatchProgress] = None,+ ) -> None:+ self.config = config+ self.batch_size = batch_size+ self.max_workers = max(1, max_workers)+ self.require_consensus = require_consensus+ self.prompt_version = prompt_version+ self.thresholds = thresholds if thresholds is not None else DEFAULT_THRESHOLDS+ self.progress = progress+ self.client = create_llm_client(config)+ self.diagnostics: List[GraphDiagnostic] = []++ async def match(+ self,+ registry: SkillRegistry,+ candidates: Iterable[RelationCandidate],+ ) -> List[LLMMatch]:+ candidate_list = list(candidates)+ matches: List[LLMMatch] = []+ self.diagnostics = []+ total_batches = (+ (len(candidate_list) + self.batch_size - 1) // self.batch_size+ if candidate_list+ else 0+ )+ self._emit_progress(+ "matching_start",+ 0,+ total_batches,+ {+ "candidate_count": len(candidate_list),+ "batch_size": self.batch_size,+ "max_workers": self.max_workers,+ "consensus_runs": 2 if self.require_consensus else 1,+ },+ )+ batches = []+ for batch_index, start in enumerate(+ range(0, len(candidate_list), self.batch_size),+ start=1,+ ):+ batches.append(+ (batch_index, candidate_list[start: start + self.batch_size])+ )+ batch_sizes = {batch_index: len(batch) for batch_index, batch in batches}+ semaphore = asyncio.Semaphore(self.max_workers)++ async def match_with_limit(+ batch_index: int,+ batch: List[RelationCandidate],+ ) -> tuple[int, List[LLMMatch], List[GraphDiagnostic]]:+ async with semaphore:+ return await self._match_batch(registry, batch, batch_index, total_batches)++ results = await asyncio.gather(+ *(match_with_limit(batch_index, batch) for batch_index, batch in batches)+ )++ for batch_index, batch_matches, batch_diagnostics in sorted(+ results,+ key=lambda item: item[0],+ ):+ self.diagnostics.extend(batch_diagnostics)+ matches.extend(batch_matches)+ self._emit_progress(+ "batch_done",+ batch_index,+ total_batches,+ {+ "candidate_count": batch_sizes[batch_index],+ "match_count": len(batch_matches),+ "accepted_count": len(+ [match for match in batch_matches if match.accepted]+ ),+ "diagnostics_count": len(batch_diagnostics),+ },+ )+ self._emit_progress(+ "matching_done",+ total_batches,+ total_batches,+ {+ "match_count": len(matches),+ "accepted_count": len([match for match in matches if match.accepted]),+ "diagnostics_count": len(self.diagnostics),+ },+ )+ return matches++ def manifest_metadata(self) -> Dict[str, Any]:+ return {+ "model": self.config.model,+ "backend": self.config.backend,+ "base_url": self.config.base_url,+ "temperature": self.config.temperature,+ "prompt_version": self.prompt_version,+ "batch_size": self.batch_size,+ "max_workers": self.max_workers,+ "require_consensus": self.require_consensus,+ "consensus_runs": 2 if self.require_consensus else 1,+ }++ async def _match_batch(+ self,+ registry: SkillRegistry,+ batch: List[RelationCandidate],+ batch_index: int,+ total_batches: int,+ ) -> tuple[int, List[LLMMatch], List[GraphDiagnostic]]:+ payload = build_llm_context(registry, batch)+ self._emit_progress(+ "batch_start",+ batch_index,+ total_batches,+ {+ "candidate_count": len(batch),+ "input_sha256": payload["input_sha256"],+ "candidate_ids": [candidate.key for candidate in batch],+ "consensus_runs": 2 if self.require_consensus else 1,+ },+ )+ first_matches, first_diagnostics = await self._request_and_validate_batch(+ registry,+ batch,+ reverse_skill_order=False,+ )+ if not self.require_consensus:+ return batch_index, first_matches, first_diagnostics++ second_matches, second_diagnostics = await self._request_and_validate_batch(+ registry,+ batch,+ reverse_skill_order=True,+ )+ agreed_matches, consensus_diagnostics = consensus_matches(+ first_matches,+ second_matches,+ )+ return (+ batch_index,+ agreed_matches,+ first_diagnostics + second_diagnostics + consensus_diagnostics,+ )++ async def _request_and_validate_batch(+ self,+ registry: SkillRegistry,+ batch: List[RelationCandidate],+ *,+ reverse_skill_order: bool,+ ) -> tuple[List[LLMMatch], List[GraphDiagnostic]]:+ payload = build_llm_context(+ registry,+ batch,+ reverse_skill_order=reverse_skill_order,+ )+ operation = (+ "ontology_matching_reverse"+ if reverse_skill_order+ else "ontology_matching_forward"+ )+ with llm_usage_context("graph_construction", operation):+ content = await self.client.complete_json_async(+ system_prompt=SYSTEM_PROMPT,+ user_content=json.dumps(+ payload,+ ensure_ascii=False,+ indent=2,+ ),+ timeout=200,+ error_context="LLM graph matching",+ request_overrides=_LOW_REASONING_REQUEST_OVERRIDES,+ )+ try:+ raw_payload = json.loads(content)+ except json.JSONDecodeError as exc:+ raise RuntimeError(+ "LLM graph matching response is not valid JSON. "+ f"content_prefix={content[:1000]!r}"+ ) from exc+ batch_matches, batch_diagnostics = validate_llm_matches(+ raw_payload,+ registry,+ batch,+ thresholds=self.thresholds,+ )+ return batch_matches, batch_diagnostics++ def _emit_progress(+ self,+ event: str,+ current: int,+ total: int,+ details: Dict[str, Any],+ ) -> None:+ if self.progress is None:+ return+ self.progress(event, current, total, details)diff --git a/jiuwenswarm/symphony/graph/matcher/prompt.py b/jiuwenswarm/symphony/graph/matcher/prompt.pynew file mode 100644index 0000000000..f4773c0085--- /dev/null+++ b/jiuwenswarm/symphony/graph/matcher/prompt.py@@ -0,0 +1,110 @@+"""Prompt and context construction for LLM relation matching."""++from __future__ import annotations++import hashlib+import json+from typing import Any, Dict, List++from jiuwenswarm.symphony.fingerprint.models import SkillFingerprint+from jiuwenswarm.symphony.graph.models import (+ ALLOWED_RELATION_TYPES,+ RelationCandidate,+ SkillRegistry,+)+++def build_llm_context(+ registry: SkillRegistry,+ candidates: List[RelationCandidate],+ *,+ reverse_skill_order: bool = False,+) -> Dict[str, Any]:+ skill_ids = _ordered_skill_ids_for_candidates(+ candidates,+ reverse_skill_order=reverse_skill_order,+ )+ skills = [registry.skills[skill_id] for skill_id in skill_ids]+ candidate_payload = [candidate.to_dict() for candidate in candidates]+ return {+ "allowed_relation_types": sorted(ALLOWED_RELATION_TYPES),+ "skills": [_skill_context(skill) for skill in skills],+ "candidates": candidate_payload,+ "input_sha256": hashlib.sha256(+ json.dumps(candidate_payload, sort_keys=True, ensure_ascii=False).encode(+ "utf-8"+ )+ ).hexdigest(),+ }+++def _ordered_skill_ids_for_candidates(+ candidates: List[RelationCandidate],+ *,+ reverse_skill_order: bool,+) -> List[str]:+ ordered: List[str] = []+ for candidate in candidates:+ pair = (+ [candidate.target_id, candidate.source_id]+ if reverse_skill_order+ else [candidate.source_id, candidate.target_id]+ )+ for skill_id in pair:+ if skill_id not in ordered:+ ordered.append(skill_id)+ return ordered+++def _skill_context(skill: SkillFingerprint) -> Dict[str, Any]:+ return {+ "id": skill.id,+ "name": skill.name,+ "description": skill.description,+ "inputs": [item.to_dict() for item in skill.inputs],+ "outputs": [item.to_dict() for item in skill.outputs],+ }+++SYSTEM_PROMPT = """You validate Skill relation candidates for a Skill graph.++Return only a valid JSON object. Do not include markdown fences, explanations,+analysis, or reasoning text.++Input contains:+- skills: normalized Skill fingerprints.+- candidates: deterministic relation candidates.+- allowed_relation_types.++For each candidate pair, decide whether the suggested can_feed relation is+valid. Do not invent new skills, relation types, or candidate pairs.+If a candidate direction is wrong, omit it or return it with low confidence+and a reason.++Return:+{+ "matches": [+ {+ "candidate_id": "skill_a<->skill_b",+ "source_id": "directed source skill id",+ "target_id": "directed target skill id",+ "relation_type": "can_feed",+ "confidence": 0.0-1.0,+ "method": "llm_ontology_match",+ "reasons": ["short evidence-based reason"],+ "supporting_fields": {+ "port_mappings": [+ {"source_output": "output_name", "target_input": "input_name"}+ ],+ "source_outputs": ["..."],+ "target_inputs": ["..."]+ }+ }+ ]+}++Relation meanings:+- can_feed: source output can satisfy target input.+Choose port_mappings only from the candidate evidence. Prefer content inputs+such as body/query/text/sources over control inputs such as command/format.+"""diff --git a/jiuwenswarm/symphony/graph/matcher/validation.py b/jiuwenswarm/symphony/graph/matcher/validation.pynew file mode 100644index 0000000000..41354ee269--- /dev/null+++ b/jiuwenswarm/symphony/graph/matcher/validation.py@@ -0,0 +1,251 @@+"""Validate raw LLM relation match payloads."""++from __future__ import annotations++from typing import Any, Dict, Iterable, List, Optional++from jiuwenswarm.symphony.graph.matcher.constants import DEFAULT_THRESHOLDS+from jiuwenswarm.symphony.graph.models import (+ ALLOWED_RELATION_TYPES,+ GraphDiagnostic,+ LLMMatch,+ RelationCandidate,+ SkillRegistry,+)+++def validate_llm_matches(+ payload: Dict[str, Any],+ registry: SkillRegistry,+ candidates: Iterable[RelationCandidate],+ *,+ thresholds: Optional[Dict[str, float]] = None,+) -> tuple[List[LLMMatch], List[GraphDiagnostic]]:+ """Normalize and validate raw LLM matches."""++ thresholds = thresholds if thresholds is not None else DEFAULT_THRESHOLDS+ candidate_by_key = {candidate.key: candidate for candidate in candidates}+ candidates_by_pair = {}+ for candidate in candidates:+ candidates_by_pair[(candidate.source_id, candidate.target_id)] = candidate+ candidates_by_pair[(candidate.target_id, candidate.source_id)] = candidate+ matches: List[LLMMatch] = []+ diagnostics: List[GraphDiagnostic] = []++ raw_matches = payload.get("matches", [])+ if not isinstance(raw_matches, list):+ return [], [+ GraphDiagnostic(+ stage="llm_match",+ severity="error",+ code="invalid_matches_payload",+ message="LLM payload field 'matches' must be a list.",+ )+ ]++ for index, raw in enumerate(raw_matches):+ if not isinstance(raw, dict):+ diagnostics.append(+ GraphDiagnostic(+ stage="llm_match",+ severity="warning",+ code="invalid_match_item",+ message="LLM match item is not an object.",+ details={"index": index, "item": raw},+ )+ )+ continue++ match, item_diagnostics = _normalize_match(+ raw, registry, candidate_by_key, candidates_by_pair, thresholds+ )+ diagnostics.extend(item_diagnostics)+ if match is not None:+ matches.append(match)++ return matches, diagnostics+++def _normalize_match(+ raw: Dict[str, Any],+ registry: SkillRegistry,+ candidate_by_key: Dict[str, RelationCandidate],+ candidates_by_pair: Dict[tuple[str, str], RelationCandidate],+ thresholds: Dict[str, float],+) -> tuple[Optional[LLMMatch], List[GraphDiagnostic]]:+ diagnostics: List[GraphDiagnostic] = []+ source_id = str(raw.get("source_id") or "")+ target_id = str(raw.get("target_id") or "")+ relation_type = str(raw.get("relation_type") or "")+ candidate_id = raw.get("candidate_id")+ candidate_id = str(candidate_id) if candidate_id else None++ errors: List[str] = []+ if source_id not in registry.skills:+ errors.append("source_id does not exist")+ if target_id not in registry.skills:+ errors.append("target_id does not exist")+ if relation_type not in ALLOWED_RELATION_TYPES:+ errors.append("relation_type is not allowed")++ candidate = None+ if candidate_id:+ candidate = candidate_by_key.get(candidate_id)+ if candidate is None:+ candidate = candidates_by_pair.get((source_id, target_id))+ if candidate is None:+ errors.append("match does not correspond to an input candidate")+ elif relation_type not in candidate.relation_hints:+ errors.append("relation_type is not allowed for the input candidate")++ try:+ confidence = float(raw.get("confidence", 0))+ except (TypeError, ValueError):+ confidence = 0+ errors.append("confidence is not numeric")+ if confidence < 0 or confidence > 1:+ errors.append("confidence must be between 0 and 1")+ confidence = max(0, min(1, confidence))++ reasons = [str(item) for item in raw.get("reasons", []) if str(item).strip()]+ supporting_fields = raw.get("supporting_fields")+ if not isinstance(supporting_fields, dict):+ supporting_fields = {}++ if relation_type == "can_feed" and candidate is not None:+ source_outputs = set(_field_names(supporting_fields.get("source_outputs", [])))+ target_inputs = set(_field_names(supporting_fields.get("target_inputs", [])))+ requested_port_mappings = _port_mapping_pairs(+ supporting_fields.get("port_mappings", [])+ )+ directional_evidence = _directional_evidence(+ candidate,+ source_id,+ target_id,+ )+ evidence_port_mappings = _port_mapping_pairs(+ directional_evidence.get("port_mappings", [])+ )+ evidence_outputs = {+ item.get("name")+ for item in directional_evidence.get("source_outputs", [])+ if isinstance(item, dict)+ }+ evidence_inputs = {+ item.get("name")+ for item in directional_evidence.get("target_inputs", [])+ if isinstance(item, dict)+ }+ if requested_port_mappings:+ if not requested_port_mappings <= evidence_port_mappings:+ errors.append("port_mappings do not match candidate evidence")+ supporting_fields = _complete_supporting_fields_from_port_mappings(+ supporting_fields,+ requested_port_mappings,+ )+ elif source_outputs and target_inputs:+ if not (source_outputs & evidence_outputs and target_inputs & evidence_inputs):+ errors.append("supporting_fields do not match candidate evidence")+ elif not ((evidence_outputs and evidence_inputs) or evidence_port_mappings):+ errors.append("can_feed has no supported output/input pair")++ accepted = not errors and confidence >= thresholds.get(relation_type, 1.0)+ match = LLMMatch(+ source_id=source_id,+ target_id=target_id,+ relation_type=relation_type,+ confidence=confidence,+ method=str(raw.get("method") or "llm_ontology_match"),+ reasons=reasons,+ supporting_fields=supporting_fields,+ candidate_id=candidate.key if candidate is not None else candidate_id,+ accepted=accepted,+ diagnostics=errors,+ raw=raw,+ )++ if errors:+ diagnostics.append(+ GraphDiagnostic(+ stage="llm_match",+ severity="warning",+ code="rejected_llm_match",+ message="LLM match failed validation.",+ skill_id=source_id or None,+ details={"errors": errors, "match": raw},+ )+ )+ elif not accepted:+ diagnostics.append(+ GraphDiagnostic(+ stage="llm_match",+ severity="info",+ code="low_confidence_llm_match",+ message="LLM match is below the relation threshold.",+ skill_id=source_id,+ details={+ "threshold": thresholds.get(relation_type),+ "match": match.to_dict(),+ },+ )+ )++ return match, diagnostics+++def _field_names(values: Any) -> List[str]:+ if not isinstance(values, list):+ return []+ names = []+ for value in values:+ if isinstance(value, str):+ names.append(_field_name_from_string(value))+ elif isinstance(value, dict) and value.get("name"):+ names.append(str(value["name"]))+ return [name for name in names if name]+++def _field_name_from_string(value: str) -> str:+ text = str(value).strip()+ if not text:+ return ""+ head = text.split(":", 1)[0].strip()+ head = head.split("(", 1)[0].strip()+ return head+++def _port_mapping_pairs(values: Any) -> set[tuple[str, str]]:+ if not isinstance(values, list):+ return set()+ pairs = set()+ for value in values:+ if not isinstance(value, dict):+ continue+ source_output = str(value.get("source_output") or "").strip()+ target_input = str(value.get("target_input") or "").strip()+ if source_output and target_input:+ pairs.add((source_output, target_input))+ return pairs+++def _complete_supporting_fields_from_port_mappings(+ supporting_fields: Dict[str, Any],+ pairs: set[tuple[str, str]],+) -> Dict[str, Any]:+ completed = dict(supporting_fields)+ completed.setdefault("source_outputs", sorted({source for source, _ in pairs}))+ completed.setdefault("target_inputs", sorted({target for _, target in pairs}))+ return completed+++def _directional_evidence(+ candidate: RelationCandidate,+ source_id: str,+ target_id: str,+) -> Dict[str, Any]:+ directions = candidate.evidence.get("directions", {})+ if isinstance(directions, dict):+ evidence = directions.get(f"{source_id}->{target_id}")+ if isinstance(evidence, dict):+ return evidence+ return candidate.evidencediff --git a/jiuwenswarm/symphony/graph/models.py b/jiuwenswarm/symphony/graph/models.pynew file mode 100644index 0000000000..dca3c586ae--- /dev/null+++ b/jiuwenswarm/symphony/graph/models.py@@ -0,0 +1,253 @@+"""Data contracts for offline Skill graph construction."""++from __future__ import annotations++from dataclasses import dataclass, field+from datetime import datetime, timezone+from typing import Any, Dict, List, Optional++from jiuwenswarm.symphony.fingerprint.models import SkillFingerprint+++ALLOWED_RELATION_TYPES = frozenset(+ {+ "can_feed",+ }+)+++@dataclass(frozen=True)+class GraphDiagnostic:+ """Structured diagnostic emitted during graph construction."""++ stage: str+ severity: str+ code: str+ message: str+ skill_id: Optional[str] = None+ details: Dict[str, Any] = field(default_factory=dict)++ def to_dict(self) -> Dict[str, Any]:+ return {+ "skill_id": self.skill_id,+ "stage": self.stage,+ "severity": self.severity,+ "code": self.code,+ "message": self.message,+ "details": self.details,+ }+++@dataclass(frozen=True)+class SkillRegistry:+ """Validated Skill registry keyed by Skill ID."""++ skills: Dict[str, SkillFingerprint]+ diagnostics: List[GraphDiagnostic] = field(default_factory=list)++ def ordered_skills(self) -> List[SkillFingerprint]:+ return [self.skills[skill_id] for skill_id in sorted(self.skills)]+++@dataclass(frozen=True)+class RelationCandidate:+ """A cheap, deterministic Skill pair candidate for LLM review."""++ source_id: str+ target_id: str+ relation_hints: List[str]+ candidate_methods: List[str]+ priority: str+ evidence: Dict[str, Any] = field(default_factory=dict)++ @property+ def key(self) -> str:+ return f"{self.source_id}->{self.target_id}"++ def to_dict(self) -> Dict[str, Any]:+ return {+ "candidate_id": self.key,+ "source_id": self.source_id,+ "target_id": self.target_id,+ "relation_hints": list(self.relation_hints),+ "candidate_methods": list(self.candidate_methods),+ "priority": self.priority,+ "evidence": self.evidence,+ }+++@dataclass(frozen=True)+class LLMMatch:+ """LLM relation judgment, after schema-level normalization."""++ source_id: str+ target_id: str+ relation_type: str+ confidence: float+ method: str = "llm_ontology_match"+ reasons: List[str] = field(default_factory=list)+ supporting_fields: Dict[str, Any] = field(default_factory=dict)+ candidate_id: Optional[str] = None+ accepted: bool = False+ diagnostics: List[str] = field(default_factory=list)+ raw: Dict[str, Any] = field(default_factory=dict)++ def to_dict(self) -> Dict[str, Any]:+ return {+ "candidate_id": self.candidate_id,+ "source_id": self.source_id,+ "target_id": self.target_id,+ "relation_type": self.relation_type,+ "confidence": self.confidence,+ "method": self.method,+ "reasons": list(self.reasons),+ "supporting_fields": self.supporting_fields,+ "accepted": self.accepted,+ "diagnostics": list(self.diagnostics),+ "raw": self.raw,+ }+++@dataclass(frozen=True)+class GraphNode:+ """A typed graph node."""++ id: str+ type: str+ label: str+ properties: Dict[str, Any] = field(default_factory=dict)++ def to_dict(self) -> Dict[str, Any]:+ return {+ "id": self.id,+ "type": self.type,+ "label": self.label,+ "properties": self.properties,+ }+++@dataclass(frozen=True)+class GraphEdge:+ """A typed graph edge."""++ source: str+ target: str+ type: str+ confidence: float = 1.0+ method: str = "deterministic"+ evidence: Dict[str, Any] = field(default_factory=dict)++ @property+ def key(self) -> str:+ return f"{self.source}->{self.target}:{self.type}"++ def to_dict(self) -> Dict[str, Any]:+ return {+ "source": self.source,+ "target": self.target,+ "type": self.type,+ "confidence": self.confidence,+ "method": self.method,+ "evidence": self.evidence,+ }+++@dataclass(frozen=True)+class SkillGraph:+ """Skill graph nodes and typed edges."""++ nodes: List[GraphNode]+ edges: List[GraphEdge]++ def to_dict(self) -> Dict[str, Any]:+ return {+ "nodes": [node.to_dict() for node in self.nodes],+ "edges": [edge.to_dict() for edge in self.edges],+ }+++@dataclass(frozen=True)+class ScoreLookup:+ """Lookup tables used by online Score retrieval and planning."""++ by_output: Dict[str, List[str]]+ by_input: Dict[str, List[str]]+ by_data_type: Dict[str, List[str]]+ neighbors: Dict[str, List[str]]+ upstream_by_input: Dict[str, List[str]]+ downstream_by_output: Dict[str, List[str]]+ by_text_term: Dict[str, List[str]]++ def to_dict(self) -> Dict[str, Any]:+ return {+ "by_output": self.by_output,+ "by_input": self.by_input,+ "by_data_type": self.by_data_type,+ "neighbors": self.neighbors,+ "upstream_by_input": self.upstream_by_input,+ "downstream_by_output": self.downstream_by_output,+ "by_text_term": self.by_text_term,+ }+++@dataclass(frozen=True)+class BuildManifest:+ """Manifest used as the online loading entrypoint."""++ schema_version: str = "Orchestration-score-v1"+ artifacts: Dict[str, str] = field(+ default_factory=lambda: {+ "skills": "skills.json",+ "graph": "skill_graph.json",+ "score_lookup": "score_lookup.json",+ "llm_matches": "llm_matches.json",+ "diagnostics": "diagnostics.json",+ "io_name_vocab": "io_name_vocab.json",+ }+ )+ thresholds: Dict[str, float] = field(+ default_factory=lambda: {+ "can_feed": 0.7,+ }+ )+ planning_defaults: Dict[str, Any] = field(+ default_factory=lambda: {+ "min_edge_confidence": 0.7,+ "max_depth": 4,+ "max_plans": 20,+ "max_branch": 8,+ "max_entry_skills": 40,+ "top_m": 12,+ "top_k": 3,+ "include_candidates": True,+ "conservative_reject": True,+ "enable_backward_search": True,+ }+ )+ llm: Dict[str, Any] = field(default_factory=dict)+ created_at: str = field(+ default_factory=lambda: datetime.now(timezone.utc).isoformat()+ )++ def to_dict(self) -> Dict[str, Any]:+ return {+ "schema_version": self.schema_version,+ "artifacts": self.artifacts,+ "thresholds": self.thresholds,+ "planning_defaults": self.planning_defaults,+ "llm": self.llm,+ "created_at": self.created_at,+ }+++@dataclass(frozen=True)+class GraphBuildResult:+ """Complete graph build result."""++ manifest: BuildManifest+ skills: List[SkillFingerprint]+ candidates: List[RelationCandidate]+ llm_matches: List[LLMMatch]+ graph: SkillGraph+ lookup: ScoreLookup+ diagnostics: List[GraphDiagnostic] = field(default_factory=list)diff --git a/jiuwenswarm/symphony/graph/pipeline.py b/jiuwenswarm/symphony/graph/pipeline.pynew file mode 100644index 0000000000..ffdb059c0d--- /dev/null+++ b/jiuwenswarm/symphony/graph/pipeline.py@@ -0,0 +1,155 @@+"""Offline graph construction orchestration."""++from __future__ import annotations++from typing import Any, Callable, Iterable, Optional++from jiuwenswarm.symphony.llm import get_llm_token_usage_summary+from jiuwenswarm.symphony.graph.builders import ScoreLookupBuilder, SkillGraphBuilder+from jiuwenswarm.symphony.graph.candidates import CandidateGenerator+from jiuwenswarm.symphony.graph.matcher import (+ DEFAULT_THRESHOLDS,+ OntologyMatcher,+)+from jiuwenswarm.symphony.graph.models import BuildManifest, GraphBuildResult, GraphDiagnostic+from jiuwenswarm.symphony.graph.registry import SkillRegistryBuilder+from jiuwenswarm.symphony.fingerprint.models import SkillFingerprint++GraphProgress = Callable[..., None]+++class GraphBuilder:+ """Build Skill graph artifacts from normalized Skill fingerprints."""++ def __init__(+ self,+ *,+ matcher: OntologyMatcher,+ registry_builder: Optional[SkillRegistryBuilder] = None,+ candidate_generator: Optional[CandidateGenerator] = None,+ graph_builder: Optional[SkillGraphBuilder] = None,+ lookup_builder: Optional[ScoreLookupBuilder] = None,+ ) -> None:+ self.matcher = matcher+ self.registry_builder = registry_builder or SkillRegistryBuilder()+ self.candidate_generator = candidate_generator or CandidateGenerator()+ self.graph_builder = graph_builder or SkillGraphBuilder()+ self.lookup_builder = lookup_builder or ScoreLookupBuilder()++ async def __call__(+ self,+ fingerprints: Iterable[SkillFingerprint],+ *,+ progress: GraphProgress | None = None,+ ) -> GraphBuildResult:+ return await self.build(fingerprints, progress=progress)++ async def build(+ self,+ fingerprints: Iterable[SkillFingerprint],+ *,+ progress: GraphProgress | None = None,+ ) -> GraphBuildResult:+ fingerprints = list(fingerprints)+ diagnostics: list[GraphDiagnostic] = []+ _emit_progress(progress, "graph.registry.start", fingerprint_count=len(fingerprints))+ registry = self.registry_builder.register(fingerprints)+ diagnostics.extend(registry.diagnostics)+ _emit_progress(+ progress,+ "graph.registry.done",+ skill_count=len(registry.skills),+ diagnostics_count=len(registry.diagnostics),+ )++ _emit_progress(progress, "graph.candidates.start", skill_count=len(registry.skills))+ candidates = self.candidate_generator.generate(registry)+ _emit_progress(progress, "graph.candidates.done", candidate_count=len(candidates))++ _emit_progress(progress, "graph.resolve.start", candidate_count=len(candidates))+ llm_matches = await self.matcher.match(registry, candidates)+ relation_diagnostics = self._relation_diagnostics(llm_matches)+ diagnostics.extend(relation_diagnostics)+ _emit_progress(+ progress,+ "graph.resolve.done",+ candidate_count=len(candidates),+ match_count=len(llm_matches),+ accepted_match_count=sum(1 for match in llm_matches if match.accepted),+ diagnostics_count=len(relation_diagnostics),+ )++ _emit_progress(progress, "graph.materialize.start", match_count=len(llm_matches))+ graph = self.graph_builder.build(registry, llm_matches)+ _emit_progress(+ progress,+ "graph.materialize.done",+ node_count=len(graph.nodes),+ edge_count=len(graph.edges),+ )++ _emit_progress(+ progress,+ "graph.score.start",+ node_count=len(graph.nodes),+ edge_count=len(graph.edges),+ )+ lookup = self.lookup_builder.build(registry, graph)+ _emit_progress(progress, "graph.score.done")++ llm_metadata = _matcher_metadata(self.matcher)+ llm_metadata["token_usage"] = get_llm_token_usage_summary()+ manifest = BuildManifest(+ thresholds=_matcher_thresholds(self.matcher),+ llm=llm_metadata,+ )++ return GraphBuildResult(+ manifest=manifest,+ skills=registry.ordered_skills(),+ candidates=candidates,+ llm_matches=llm_matches,+ graph=graph,+ lookup=lookup,+ diagnostics=diagnostics,+ )++ def _relation_diagnostics(self, llm_matches: list) -> list[GraphDiagnostic]:+ diagnostics: list[GraphDiagnostic] = []+ matcher_diagnostics = []+ if hasattr(self.matcher, "diagnostics"):+ matcher_diagnostics = list(self.matcher.diagnostics)+ diagnostics.extend(matcher_diagnostics)++ for match in llm_matches:+ if matcher_diagnostics:+ continue+ for message in match.diagnostics:+ diagnostics.append(+ GraphDiagnostic(+ stage="llm_match",+ severity="warning",+ code="match_diagnostic",+ message=message,+ skill_id=match.source_id,+ details={"match": match.to_dict()},+ )+ )+ return diagnostics+++def _emit_progress(progress: GraphProgress | None, stage: str, **details: Any) -> None:+ if progress is not None:+ progress(stage, **details)+++def _matcher_metadata(matcher: OntologyMatcher) -> dict:+ if hasattr(matcher, "manifest_metadata"):+ return matcher.manifest_metadata()+ return {"matcher": matcher.__class__.__name__}+++def _matcher_thresholds(matcher: OntologyMatcher) -> dict:+ if hasattr(matcher, "thresholds"):+ return dict(matcher.thresholds)+ return dict(DEFAULT_THRESHOLDS)diff --git a/jiuwenswarm/symphony/graph/registry.py b/jiuwenswarm/symphony/graph/registry.pynew file mode 100644index 0000000000..b303f59606--- /dev/null+++ b/jiuwenswarm/symphony/graph/registry.py@@ -0,0 +1,57 @@+"""Skill registry validation for graph construction."""++from __future__ import annotations++from typing import Iterable, List++from jiuwenswarm.symphony.graph.models import GraphDiagnostic, SkillRegistry+from jiuwenswarm.symphony.fingerprint.models import SkillFingerprint+++class SkillRegistryBuilder:+ """Register normalized Skill fingerprints by stable ID."""++ @staticmethod+ def register(fingerprints: Iterable[SkillFingerprint]) -> SkillRegistry:+ skills = {}+ diagnostics: List[GraphDiagnostic] = []++ for fingerprint in sorted(fingerprints, key=lambda item: item.id):+ if not fingerprint.id:+ diagnostics.append(+ GraphDiagnostic(+ stage="registry",+ severity="error",+ code="missing_skill_id",+ message="Skill fingerprint is missing an id.",+ details={"skill": fingerprint.to_dict()},+ )+ )+ continue++ if fingerprint.id in skills:+ diagnostics.append(+ GraphDiagnostic(+ stage="registry",+ severity="error",+ code="duplicate_skill_id",+ message=f"Duplicate Skill id: {fingerprint.id}",+ skill_id=fingerprint.id,+ )+ )+ continue++ if not fingerprint.outputs:+ diagnostics.append(+ GraphDiagnostic(+ stage="registry",+ severity="warning",+ code="missing_outputs",+ message="Skill has no declared outputs.",+ skill_id=fingerprint.id,+ )+ )++ skills[fingerprint.id] = fingerprint++ return SkillRegistry(skills=skills, diagnostics=diagnostics)diff --git a/jiuwenswarm/symphony/graph/writer.py b/jiuwenswarm/symphony/graph/writer.pynew file mode 100644index 0000000000..c2a1b93904--- /dev/null+++ b/jiuwenswarm/symphony/graph/writer.py@@ -0,0 +1,47 @@+"""Write graph build artifacts to disk."""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any, Dict, Union++from jiuwenswarm.symphony.graph.models import GraphBuildResult+++def write_json_file(path: Path, data: Dict[str, Any]) -> None:+ """Write JSON with stable formatting."""++ path.write_text(+ json.dumps(data, ensure_ascii=False, indent=2),+ encoding="utf-8",+ )+++def write_graph_build_result(+ result: GraphBuildResult,+ out_dir: Union[Path, str],+) -> None:+ """Write all graph build artifacts to an output directory."""++ output_path = Path(out_dir)+ output_path.mkdir(parents=True, exist_ok=True)++ write_json_file(output_path / "score_manifest.json", result.manifest.to_dict())+ write_json_file(+ output_path / "skills.json",+ {"skills": [skill.to_dict() for skill in result.skills]},+ )+ write_json_file(output_path / "skill_graph.json", result.graph.to_dict())+ write_json_file(output_path / "score_lookup.json", result.lookup.to_dict())+ write_json_file(+ output_path / "llm_matches.json",+ {+ "candidates": [candidate.to_dict() for candidate in result.candidates],+ "matches": [match.to_dict() for match in result.llm_matches],+ },+ )+ write_json_file(+ output_path / "diagnostics.json",+ {"diagnostics": [diagnostic.to_dict() for diagnostic in result.diagnostics]},+ )diff --git a/jiuwenswarm/symphony/llm.py b/jiuwenswarm/symphony/llm.pynew file mode 100644index 0000000000..ba8ef3a88f--- /dev/null+++ b/jiuwenswarm/symphony/llm.py@@ -0,0 +1,426 @@+"""LLM helpers backed by JiuwenSwarm's configured model stack."""++from __future__ import annotations++import json+from collections import defaultdict+from contextlib import contextmanager+from contextvars import ContextVar+from dataclasses import dataclass+from threading import Lock+from typing import Any, Dict, Iterator, List, Optional++from json_repair import repair_json+++@dataclass(frozen=True)+class LLMConfig:+ """LLM chat configuration resolved from JiuwenSwarm model settings."""++ model: str = ""+ model_client_config: Dict[str, Any] | None = None+ model_config_obj: Dict[str, Any] | None = None+ temperature: float = 0.0+ top_p: float = 1.0++ @classmethod+ def from_default_model(cls) -> "LLMConfig":+ """Resolve the default JiuwenSwarm model declared in config.yaml."""++ from jiuwenswarm.common.config import get_config, get_default_models++ config = get_config()+ models = config.get("models") or {}+ if not isinstance(models, dict):+ models = {}+ default_models = models.get("defaults")+ has_default_model = (+ isinstance(default_models, list)+ and bool(default_models)+ ) or isinstance(models.get("default"), dict)+ if not has_default_model:+ raise RuntimeError("No JiuwenSwarm default model is configured in config.yaml.")++ defaults = get_default_models(config)+ if not defaults:+ raise RuntimeError("No JiuwenSwarm default model is configured in config.yaml.")+ entry = next((item for item in defaults if item.get("is_default") is True), defaults[0])+ return cls.from_model_entry(entry or {})++ @classmethod+ def from_model_entry(cls, entry: Dict[str, Any]) -> "LLMConfig":+ """Build orchestration config from one resolved Jiuwen model entry."""++ client_config = entry.get("model_client_config") or {}+ request_config = entry.get("model_config_obj") or {}+ if not isinstance(client_config, dict):+ client_config = {}+ if not isinstance(request_config, dict):+ request_config = {}+ client_config = dict(client_config)+ request_config = dict(request_config)+ model = str(+ request_config.get("model")+ or client_config.get("model_name")+ or client_config.get("model")+ or ""+ ).strip()+ if not model:+ raise RuntimeError("JiuwenSwarm default model is missing model_name.")+ if not str(client_config.get("api_base") or "").strip():+ raise RuntimeError("JiuwenSwarm default model is missing api_base.")+ if not str(client_config.get("api_key") or "").strip():+ raise RuntimeError("JiuwenSwarm default model is missing api_key.")+ if not str(client_config.get("client_provider") or "").strip():+ raise RuntimeError("JiuwenSwarm default model is missing client_provider.")+ request_config["model"] = model+ return cls(+ model=model,+ model_client_config=client_config,+ model_config_obj=request_config,+ )++ @property+ def backend(self) -> str:+ return "jiuwenswarm"++ @property+ def base_url(self) -> str:+ client_config = self.model_client_config or {}+ return str(client_config.get("api_base") or "").strip().rstrip("/")++ def model_client_kwargs(self) -> Dict[str, Any]:+ client_config = dict(self.model_client_config or {})+ if self.base_url:+ client_config["api_base"] = self.base_url+ return client_config++ def model_request_kwargs(self) -> Dict[str, Any]:+ request_config = dict(self.model_config_obj or {})+ request_config["model"] = self.model+ request_config["temperature"] = self.temperature+ request_config["top_p"] = self.top_p+ return request_config+++@dataclass(frozen=True)+class LLMTokenUsageRecord:+ """Token usage from one LLM request."""++ stage: str+ operation: str+ backend: str+ model: str+ prompt_tokens: int+ completion_tokens: int+ total_tokens: int+ source: str = "provider"++ def to_dict(self) -> Dict[str, Any]:+ return {+ "stage": self.stage,+ "operation": self.operation,+ "backend": self.backend,+ "model": self.model,+ "prompt_tokens": self.prompt_tokens,+ "completion_tokens": self.completion_tokens,+ "total_tokens": self.total_tokens,+ "source": self.source,+ }+++class LLMTokenUsageTracker:+ """Thread-safe accumulator for LLM token usage."""++ def __init__(self) -> None:+ self._records: List[LLMTokenUsageRecord] = []+ self._lock = Lock()++ def add(self, record: LLMTokenUsageRecord) -> None:+ with self._lock:+ self._records.append(record)++ def reset(self) -> None:+ with self._lock:+ self._records.clear()++ def records(self) -> List[LLMTokenUsageRecord]:+ with self._lock:+ return list(self._records)++ def summary(self) -> Dict[str, Any]:+ records = self.records()+ totals = _empty_usage_totals()+ by_stage: Dict[str, Dict[str, Any]] = defaultdict(_empty_usage_totals)+ by_operation: Dict[str, Dict[str, Any]] = defaultdict(_empty_usage_totals)+ for record in records:+ for bucket in (+ totals,+ by_stage[record.stage],+ by_operation[f"{record.stage}.{record.operation}"],+ ):+ bucket["request_count"] += 1+ bucket["prompt_tokens"] += record.prompt_tokens+ bucket["completion_tokens"] += record.completion_tokens+ bucket["total_tokens"] += record.total_tokens+ return {+ "total": totals,+ "by_stage": dict(sorted(by_stage.items())),+ "by_operation": dict(sorted(by_operation.items())),+ "records": [record.to_dict() for record in records],+ }+++def _empty_usage_totals() -> Dict[str, int]:+ return {+ "request_count": 0,+ "prompt_tokens": 0,+ "completion_tokens": 0,+ "total_tokens": 0,+ }+++_TOKEN_USAGE_TRACKER = LLMTokenUsageTracker()+_USAGE_STAGE: ContextVar[str] = ContextVar(+ "orchestration_llm_usage_stage",+ default="unknown",+)+_USAGE_OPERATION: ContextVar[Optional[str]] = ContextVar(+ "orchestration_llm_usage_operation",+ default=None,+)+++@contextmanager+def llm_usage_context(stage: str, operation: Optional[str] = None) -> Iterator[None]:+ """Tag LLM calls made inside the context for usage aggregation."""++ stage_token = _USAGE_STAGE.set(stage)+ operation_token = _USAGE_OPERATION.set(operation)+ try:+ yield+ finally:+ _USAGE_OPERATION.reset(operation_token)+ _USAGE_STAGE.reset(stage_token)+++def reset_llm_token_usage() -> None:+ _TOKEN_USAGE_TRACKER.reset()+++def get_llm_token_usage_summary() -> Dict[str, Any]:+ return _TOKEN_USAGE_TRACKER.summary()+++def create_llm_client(config: LLMConfig) -> "JiuwenSwarmChatClient":+ if config is None:+ raise ValueError("create_llm_client requires LLMConfig.")+ return JiuwenSwarmChatClient(config)+++class JiuwenSwarmChatClient:+ """Adapter over openjiuwen's async model invocation."""++ def __init__(self, config: LLMConfig) -> None:+ self.config = config+ self._model = None++ async def complete_json_async(+ self,+ *,+ system_prompt: str,+ user_content: str,+ timeout: Optional[int] = None,+ error_context: str = "LLM",+ request_overrides: Optional[Dict[str, Any]] = None,+ ) -> str:+ try:+ response = await self._invoke(+ system_prompt=system_prompt,+ user_content=user_content,+ timeout=timeout,+ request_overrides=request_overrides,+ )+ except Exception as exc:+ raise RuntimeError(f"{error_context} request failed: {exc}") from exc++ return self._json_content_from_response(response, error_context)++ async def complete_json_many_async(+ self,+ requests: List[Dict[str, str]],+ *,+ timeout: Optional[int] = None,+ error_context: str = "LLM",+ request_overrides: Optional[Dict[str, Any]] = None,+ ) -> List[str]:+ return [+ await self.complete_json_async(+ system_prompt=request["system_prompt"],+ user_content=request["user_content"],+ timeout=timeout,+ error_context=f"{error_context} item {index}",+ request_overrides=request_overrides,+ )+ for index, request in enumerate(requests, start=1)+ ]++ def _json_content_from_response(self, response: Any, error_context: str) -> str:+ content = extract_message_content(response)+ if not content:+ raise RuntimeError(f"{error_context} response content is empty.")+ _record_usage_from_response(+ config=self.config,+ response=response,+ operation=error_context,+ )+ return repair_json(content, return_objects=False)++ async def _invoke(+ self,+ *,+ system_prompt: str,+ user_content: str,+ timeout: Optional[int],+ request_overrides: Optional[Dict[str, Any]],+ ) -> Any:+ from openjiuwen.core.foundation.llm import (+ Model,+ ModelClientConfig,+ ModelRequestConfig,+ )++ if self._model is None:+ self._model = Model(+ model_client_config=ModelClientConfig(+ **self.config.model_client_kwargs()+ ),+ model_config=ModelRequestConfig(**self.config.model_request_kwargs()),+ )++ invoke_kwargs: Dict[str, Any] = {}+ if timeout is not None:+ invoke_kwargs["timeout"] = timeout+ invoke_kwargs["temperature"] = self.config.temperature+ invoke_kwargs["top_p"] = self.config.top_p+ if request_overrides:+ invoke_kwargs.update(request_overrides)++ return await self._model.invoke(+ messages=[+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": user_content},+ ],+ **invoke_kwargs,+ )+++def _record_usage_from_response(+ *,+ config: LLMConfig,+ response: Any,+ operation: str,+) -> None:+ usage = getattr(response, "usage", None)+ if usage is None and hasattr(response, "raw"):+ usage = getattr(response.raw, "usage", None)+ source = "provider"+ if usage is None:+ usage = getattr(response, "usage_metadata", None)+ if usage is not None:+ source = "usage_metadata"+ prompt_tokens = _usage_int(usage, "prompt_tokens", "input_tokens")+ completion_tokens = _usage_int(usage, "completion_tokens", "output_tokens")+ total_tokens = _usage_int(usage, "total_tokens")+ if total_tokens == 0:+ total_tokens = prompt_tokens + completion_tokens+ _record_token_usage(+ config=config,+ operation=operation,+ prompt_tokens=prompt_tokens,+ completion_tokens=completion_tokens,+ total_tokens=total_tokens,+ source=source if usage is not None else "provider_missing_usage",+ )+++def _record_token_usage(+ *,+ config: LLMConfig,+ operation: str,+ prompt_tokens: int,+ completion_tokens: int,+ total_tokens: int,+ source: str,+) -> None:+ operation_override = _USAGE_OPERATION.get()+ _TOKEN_USAGE_TRACKER.add(+ LLMTokenUsageRecord(+ stage=_USAGE_STAGE.get(),+ operation=operation_override or operation,+ backend=config.backend,+ model=config.model,+ prompt_tokens=max(0, prompt_tokens),+ completion_tokens=max(0, completion_tokens),+ total_tokens=max(0, total_tokens),+ source=source,+ )+ )+++def _usage_int(usage: Any, *names: str) -> int:+ if usage is None:+ return 0+ for name in names:+ if isinstance(usage, dict):+ value = usage.get(name)+ else:+ value = getattr(usage, name, None)+ try:+ return int(value)+ except (TypeError, ValueError):+ continue+ return 0+++def extract_message_content(message: Any) -> str:+ """Extract text from common openjiuwen/OpenAI-compatible response shapes."""++ content = getattr(message, "content", None)+ if isinstance(content, str):+ return content.strip()+ if isinstance(content, list):+ return "".join(_content_part_text(item) for item in content).strip()++ choices = getattr(message, "choices", None)+ if choices:+ first = choices[0]+ choice_message = getattr(first, "message", None)+ if choice_message is not None:+ return extract_message_content(choice_message)++ for attr in ("parsed", "json", "output_text", "text"):+ value = getattr(message, attr, None)+ if isinstance(value, str) and value.strip():+ return value.strip()+ if isinstance(value, dict):+ return json.dumps(value, ensure_ascii=False)++ if isinstance(message, dict):+ for key in ("content", "output_text", "text"):+ value = message.get(key)+ if isinstance(value, str) and value.strip():+ return value.strip()+ if isinstance(value, dict):+ return json.dumps(value, ensure_ascii=False)+ return ""+++def _content_part_text(item: Any) -> str:+ if isinstance(item, str):+ return item+ if isinstance(item, dict):+ value = item.get("text") or item.get("content") or ""+ return value if isinstance(value, str) else ""+ value = getattr(item, "text", None) or getattr(item, "content", None)+ return value if isinstance(value, str) else ""diff --git a/jiuwenswarm/symphony/orchestration/__init__.py b/jiuwenswarm/symphony/orchestration/__init__.pynew file mode 100644index 0000000000..a1ecd2f481--- /dev/null+++ b/jiuwenswarm/symphony/orchestration/__init__.py@@ -0,0 +1,23 @@+"""Skill orchestration from offline graph build artifacts."""++from jiuwenswarm.symphony.orchestration.artifacts import (+ ScoreArtifacts,+ load_score_artifacts,+)+from jiuwenswarm.symphony.orchestration.planning.models import (+ ArtifactRef,+ GroundedQuery,+ InferredInput,+ OrchestrationPlan,+ PlanStep,+)++__all__ = [+ "ArtifactRef",+ "ScoreArtifacts",+ "GroundedQuery",+ "InferredInput",+ "OrchestrationPlan",+ "PlanStep",+ "load_score_artifacts",+]diff --git a/jiuwenswarm/symphony/orchestration/artifacts.py b/jiuwenswarm/symphony/orchestration/artifacts.pynew file mode 100644index 0000000000..b3d5670e6c--- /dev/null+++ b/jiuwenswarm/symphony/orchestration/artifacts.py@@ -0,0 +1,56 @@+"""Load Score artifacts for Skill orchestration."""++from __future__ import annotations++import json+from dataclasses import dataclass+from pathlib import Path+from typing import Any+++@dataclass(frozen=True)+class ScoreArtifacts:+ """Offline Score artifacts needed by orchestration."""++ score_dir: Path+ manifest: dict[str, Any]+ skills: list[dict[str, Any]]+ graph: dict[str, Any]+ lookup: dict[str, Any]+ io_name_vocab: dict[str, Any] | None = None++ @property+ def skill_by_id(self) -> dict[str, dict[str, Any]]:+ return {skill["id"]: skill for skill in self.skills if skill.get("id")}+++def load_score_artifacts(score_dir: str | Path) -> ScoreArtifacts:+ """Load Score artifacts through score_manifest.json."""++ root = Path(score_dir).resolve()+ manifest = _read_json(root / "score_manifest.json")+ artifacts = manifest.get("artifacts", {})+ skills_payload = _read_json(root / artifacts.get("skills", "skills.json"))+ graph = _read_json(root / artifacts.get("graph", "skill_graph.json"))+ lookup = _read_json(root / artifacts.get("score_lookup", "score_lookup.json"))+ io_name_vocab_path = root / artifacts.get("io_name_vocab", "io_name_vocab.json")+ return ScoreArtifacts(+ score_dir=root,+ manifest=manifest,+ skills=skills_payload.get("skills", []),+ graph=graph,+ lookup=lookup,+ io_name_vocab=_read_optional_json(io_name_vocab_path),+ )+++def _read_json(path: Path) -> dict[str, Any]:+ if not path.exists():+ raise FileNotFoundError(f"Missing score artifact: {path}")+ return json.loads(path.read_text(encoding="utf-8"))+++def _read_optional_json(path: Path) -> dict[str, Any] | None:+ if not path.exists():+ return None+ return json.loads(path.read_text(encoding="utf-8"))diff --git a/jiuwenswarm/symphony/orchestration/execution_graph.py b/jiuwenswarm/symphony/orchestration/execution_graph.pynew file mode 100644index 0000000000..1d35eb8cc6--- /dev/null+++ b/jiuwenswarm/symphony/orchestration/execution_graph.py@@ -0,0 +1,109 @@+"""Stable execution graph projection for Orchestration plan results."""++from __future__ import annotations++from typing import Any++from jiuwenswarm.symphony.orchestration.artifacts import ScoreArtifacts+++def build_execution_graph(+ planning_result: dict[str, Any],+ artifacts: ScoreArtifacts,+) -> dict[str, Any]:+ """Project an orchestration result into stable nodes, edges, and gaps."""++ primary_plan = select_primary_plan(planning_result)+ steps = list(primary_plan.get("steps") or [])+ skill_ids = [+ str(step.get("skill_id") or "").strip()+ for step in steps+ if str(step.get("skill_id") or "").strip()+ ]+ skill_id_set = set(skill_ids)++ graph_edges = [+ _project_edge(edge)+ for edge in list(primary_plan.get("can_feed_edges") or [])+ if _edge_touches_selected_skills(edge, skill_id_set)+ ]+ if not graph_edges and skill_id_set:+ graph_edges = [+ _project_edge(edge)+ for edge in artifacts.graph.get("edges", [])+ if _edge_touches_selected_skills(edge, skill_id_set)+ ]++ missing_inputs = _collect_missing_inputs(planning_result, primary_plan)+ diagnostics = []+ decision = planning_result.get("decision")+ if isinstance(decision, dict):+ diagnostics.append({"source": "decision", **decision})++ return {+ "nodes": [+ _project_skill(artifacts.skill_by_id[skill_id])+ for skill_id in skill_ids+ if skill_id in artifacts.skill_by_id+ ],+ "edges": graph_edges,+ "recommended_plans": list(planning_result.get("recommended_plans") or []),+ "missing_inputs": missing_inputs,+ "diagnostics": diagnostics,+ }+++def select_primary_plan(planning_result: dict[str, Any]) -> dict[str, Any]:+ for key in ("recommended_plans", "plans"):+ plans = planning_result.get(key)+ if isinstance(plans, list):+ for plan in plans:+ if isinstance(plan, dict):+ return plan+ return {}+++def _project_skill(skill: dict[str, Any]) -> dict[str, Any]:+ return {+ "id": skill.get("id"),+ "name": skill.get("name"),+ "description": skill.get("description"),+ "inputs": list(skill.get("inputs") or []),+ "outputs": list(skill.get("outputs") or []),+ }+++def _project_edge(edge: dict[str, Any]) -> dict[str, Any]:+ source = edge.get("source") or edge.get("source_id")+ target = edge.get("target") or edge.get("target_id")+ return {+ "source": source,+ "target": target,+ "type": edge.get("type") or edge.get("relation_type") or "can_feed",+ "confidence": edge.get("confidence"),+ "evidence": edge.get("evidence") or edge.get("supporting_fields") or {},+ }+++def _edge_touches_selected_skills(edge: dict[str, Any], skill_ids: set[str]) -> bool:+ source = str(edge.get("source") or edge.get("source_id") or "").strip()+ target = str(edge.get("target") or edge.get("target_id") or "").strip()+ return source in skill_ids and target in skill_ids+++def _collect_missing_inputs(+ planning_result: dict[str, Any],+ primary_plan: dict[str, Any],+) -> list[dict[str, Any]]:+ missing: list[dict[str, Any]] = []+ for item in primary_plan.get("missing_inputs") or []:+ if isinstance(item, dict):+ missing.append(item)+ if not missing:+ for plan in planning_result.get("plans") or []:+ if not isinstance(plan, dict):+ continue+ for item in plan.get("missing_inputs") or []:+ if isinstance(item, dict):+ missing.append(item)+ return missingdiff --git a/jiuwenswarm/symphony/orchestration/planning/__init__.py b/jiuwenswarm/symphony/orchestration/planning/__init__.pynew file mode 100644index 0000000000..cf4120d7b0--- /dev/null+++ b/jiuwenswarm/symphony/orchestration/planning/__init__.py@@ -0,0 +1,27 @@+"""Planning internals for orchestration."""++from jiuwenswarm.symphony.orchestration.planning.models import (+ ArtifactRef,+ InferredInput,+ OrchestrationPlan,+ PlanStep,+)+from jiuwenswarm.symphony.orchestration.planning.fast import FastOneShotPlanner+from jiuwenswarm.symphony.orchestration.planning.plan_builder import (+ compose_plan_group,+ dedupe_plans,+ edge_plan_item,+ path_plans_to_dag,+)++__all__ = [+ "ArtifactRef",+ "InferredInput",+ "OrchestrationPlan",+ "PlanStep",+ "FastOneShotPlanner",+ "compose_plan_group",+ "dedupe_plans",+ "edge_plan_item",+ "path_plans_to_dag",+]diff --git a/jiuwenswarm/symphony/orchestration/planning/fast.py b/jiuwenswarm/symphony/orchestration/planning/fast.pynew file mode 100644index 0000000000..c075a05b65--- /dev/null+++ b/jiuwenswarm/symphony/orchestration/planning/fast.py@@ -0,0 +1,488 @@+"""One-shot fast Symphony score planner."""++from __future__ import annotations++import json+from typing import Any++from jiuwenswarm.symphony.llm import LLMConfig, create_llm_client, llm_usage_context+from jiuwenswarm.symphony.orchestration.artifacts import ScoreArtifacts+from jiuwenswarm.symphony.orchestration.planning.plan_builder import edge_plan_item+from jiuwenswarm.symphony.orchestration.planning.utils import skill_id++FAST_PLANNER_MAX_SKILLS = 40+FAST_PLANNER_MAX_EDGES = 80++FAST_PLANNER_SYSTEM_PROMPT = """You are Symphony's fast Skill planner.+Return strict JSON only.++You receive:+- The user's query.+- Candidate Skills with id, name, and description only.+- Candidate can_feed relationships between those Skills.++Task:+- Select the best existing Skill execution path for the query.+- Use only provided skill IDs.+- Use only provided can_feed edges.+- Do not invent Skills, inputs, outputs, or edge relationships.+- Prefer the shortest path that satisfies the user's intent.+- If required information is missing, set status to "needs_input" and list it.+- If no useful plan exists from the candidates, set status to "no_plan".++Schema:+{+ "title": "short plan title",+ "status": "ready | needs_input | no_plan",+ "reason": "why this plan is best",+ "steps": [+ {"skill_id": "skill-a", "reason": "why this step is used"}+ ],+ "can_feed_edges": [+ {"source_id": "skill-a", "target_id": "skill-b"}+ ],+ "missing_inputs": [+ {"skill_id": "skill-a", "name": "input name", "type": "unknown", "reason": "why it is needed"}+ ]+}+"""+++class FastOneShotPlanner:+ """Ask the LLM for one validated plan from a bounded score subgraph."""++ def __init__(+ self,+ artifacts: ScoreArtifacts,+ *,+ llm_config: LLMConfig | None,+ llm_client: Any | None,+ min_edge_confidence: float,+ top_k: int,+ ) -> None:+ self.artifacts = artifacts+ self.llm_config = llm_config+ self.llm_client = llm_client+ self.min_edge_confidence = min_edge_confidence+ self.top_k = max(1, int(top_k))++ async def plan(self, query: str) -> dict[str, Any]:+ client = self._client()+ subgraph = self._candidate_subgraph()+ prompt_payload = {+ "query": query,+ "top_k": self.top_k,+ "min_edge_confidence": self.min_edge_confidence,+ "skills": subgraph["skills"],+ "can_feed_edges": subgraph["edges"],+ "planning_instructions": [+ "Return the single best plan as strict JSON.",+ "Use only skill IDs from skills.",+ "Use only can_feed_edges from can_feed_edges.",+ "Do not rely on skill inputs or outputs; they are filled by Symphony after validation.",+ ],+ }+ with llm_usage_context("orchestration", "one_shot_fast_planning"):+ raw = await client.complete_json_async(+ system_prompt=FAST_PLANNER_SYSTEM_PROMPT,+ user_content=json.dumps(prompt_payload, ensure_ascii=False),+ error_context="Symphony one-shot fast planning",+ )++ base = {+ "query": query,+ "score_dir": str(self.artifacts.score_dir),+ "planning_mode": "one_shot_fast",+ "llm_call_count": 1,+ "candidate_skill_count": len(subgraph["skills"]),+ "candidate_edge_count": len(subgraph["edges"]),+ }+ try:+ selection = json.loads(raw)+ except json.JSONDecodeError as exc:+ return self._failure(base, f"Invalid fast planner JSON: {raw[:500]}", exc)+ if not isinstance(selection, dict):+ return self._failure(base, "Fast planner returned a non-object JSON payload.")++ materialized = self._materialize_selection(+ selection,+ candidate_skill_ids=set(subgraph["skill_ids"]),+ candidate_edges=subgraph["edge_by_key"],+ )+ if not materialized["valid"]:+ return self._failure(base, materialized["detail"], validation=materialized)++ plan = materialized["plan"]+ return {+ **base,+ "plans": [plan] if plan.get("steps") else [],+ "recommended_plans": [plan] if plan.get("steps") else [],+ "ranking_mode": "one_shot_fast",+ "decision": {+ "mode": "one_shot_fast",+ "strategy": "single_llm_selection",+ "validated_count": 1 if plan.get("steps") else 0,+ "candidate_count": len(subgraph["skills"]),+ },+ "validation": materialized,+ "status": plan.get("status", "no_plan") if plan else "no_plan",+ "reason": plan.get("reason", "") if plan else "",+ }++ def _client(self) -> Any:+ if self.llm_client is not None:+ return self.llm_client+ if self.llm_config is None:+ raise ValueError("fast Symphony planning requires llm_config or llm_client.")+ return create_llm_client(self.llm_config)++ def _candidate_subgraph(self) -> dict[str, Any]:+ skill_by_id = self.artifacts.skill_by_id+ filtered_edges = []+ for edge in self.artifacts.graph.get("edges", []):+ edge_confidence = float(edge.get("confidence") or 0.0)+ if edge.get("type") == "can_feed" and edge_confidence >= self.min_edge_confidence:+ filtered_edges.append(edge)+ selected: set[str] = set()+ sorted_edges = sorted(+ filtered_edges,+ key=lambda item: (+ -float(item.get("confidence") or 0.0),+ str(item.get("source") or ""),+ str(item.get("target") or ""),+ ),+ )+ for edge in sorted_edges:+ for key in ("source", "target"):+ edge_skill_id = skill_id(edge.get(key))+ if (+ edge_skill_id in skill_by_id+ and len(selected) < FAST_PLANNER_MAX_SKILLS+ ):+ selected.add(edge_skill_id)+ if len(selected) >= FAST_PLANNER_MAX_SKILLS:+ break++ candidate_edges = []+ for edge in sorted_edges:+ if (+ skill_id(edge.get("source")) in selected+ and skill_id(edge.get("target")) in selected+ ):+ candidate_edges.append(edge)+ candidate_edges.sort(+ key=lambda item: (+ -float(item.get("confidence") or 0.0),+ skill_id(item.get("source")),+ skill_id(item.get("target")),+ )+ )+ candidate_edges = candidate_edges[:FAST_PLANNER_MAX_EDGES]++ for edge in candidate_edges:+ for key in ("source", "target"):+ edge_skill_id = skill_id(edge.get(key))+ if (+ edge_skill_id in skill_by_id+ and len(selected) < FAST_PLANNER_MAX_SKILLS+ ):+ selected.add(edge_skill_id)++ if not selected:+ for skill in self.artifacts.skills[:FAST_PLANNER_MAX_SKILLS]:+ current_skill_id = str(skill.get("id") or "")+ if current_skill_id.strip():+ selected.add(current_skill_id)++ filtered_candidate_edges = []+ for edge in candidate_edges:+ if (+ skill_id(edge.get("source")) in selected+ and skill_id(edge.get("target")) in selected+ ):+ filtered_candidate_edges.append(edge)+ candidate_edges = filtered_candidate_edges+ skill_payloads = [+ self._skill_payload(skill_by_id[current_skill_id])+ for current_skill_id in sorted(selected)+ if current_skill_id in skill_by_id+ ]+ edge_payloads = [self._edge_payload(edge) for edge in candidate_edges]+ return {+ "skills": skill_payloads,+ "edges": edge_payloads,+ "skill_ids": [item["id"] for item in skill_payloads],+ "edge_by_key": {+ (skill_id(edge.get("source")), skill_id(edge.get("target"))): edge+ for edge in candidate_edges+ },+ }++ def _materialize_selection(+ self,+ selection: dict[str, Any],+ *,+ candidate_skill_ids: set[str],+ candidate_edges: dict[tuple[str, str], dict[str, Any]],+ ) -> dict[str, Any]:+ status = str(selection.get("status") or "ready").strip().lower()+ if status not in {"ready", "needs_input", "no_plan"}:+ status = "ready"+ raw_steps = selection.get("steps") or selection.get("skill_order") or []+ step_ids = self._normalize_step_ids(raw_steps)+ if status == "no_plan" or not step_ids:+ return {+ "valid": True,+ "detail": "",+ "plan": {+ "title": str(+ selection.get("title") or "No Symphony fast plan"+ ).strip(),+ "status": "no_plan",+ "steps": [],+ "stages": [],+ "produced_artifacts": [],+ "missing_inputs": [],+ "can_feed_edges": [],+ "reason": str(selection.get("reason") or "").strip(),+ "plan_classification": "invalid",+ "connectivity_trace": [],+ },+ }++ unknown_ids = [+ current_skill_id+ for current_skill_id in step_ids+ if current_skill_id not in candidate_skill_ids+ ]+ if unknown_ids:+ return {+ "valid": False,+ "detail": f"Fast planner selected unknown skill IDs: {unknown_ids}",+ }+ skill_by_id = self.artifacts.skill_by_id+ missing_artifact_ids = [+ current_skill_id+ for current_skill_id in step_ids+ if current_skill_id not in skill_by_id+ ]+ if missing_artifact_ids:+ return {+ "valid": False,+ "detail": (+ "Fast planner selected missing artifact skill IDs: "+ f"{missing_artifact_ids}"+ ),+ }++ selected_edges_result = self._normalize_selected_edges(+ selection.get("can_feed_edges") or []+ )+ selected_edges = selected_edges_result["edges"]+ if selected_edges_result["invalid"]:+ return {+ "valid": False,+ "detail": (+ "Fast planner returned malformed can_feed edges: "+ f"{selected_edges_result['invalid']}"+ ),+ }+ if len(step_ids) > 1 and not selected_edges:+ selected_edges = [+ (step_ids[index], step_ids[index + 1])+ for index in range(len(step_ids) - 1)+ ]++ invalid_edges = [edge for edge in selected_edges if edge not in candidate_edges]+ if invalid_edges:+ return {+ "valid": False,+ "detail": f"Fast planner selected illegal can_feed edges: {invalid_edges}",+ }+ order = {current_skill_id: index for index, current_skill_id in enumerate(step_ids)}+ backward_edges = [+ (source, target)+ for source, target in selected_edges+ if order.get(source, -1) >= order.get(target, -1)+ ]+ if backward_edges:+ return {+ "valid": False,+ "detail": (+ "Fast planner selected edges that violate step order: "+ f"{backward_edges}"+ ),+ }++ missing_inputs = self._normalize_missing_inputs(+ selection.get("missing_inputs") or [],+ set(step_ids),+ )+ missing_by_skill: dict[str, list[dict[str, Any]]] = {}+ for item in missing_inputs:+ missing_by_skill.setdefault(str(item.get("skill_id") or ""), []).append(item)++ steps = []+ produced_artifacts = []+ for index, current_skill_id in enumerate(step_ids, start=1):+ skill = skill_by_id[current_skill_id]+ outputs = list(skill.get("outputs") or [])+ produced_artifacts.extend(+ {+ "name": item.get("name"),+ "type": item.get("type") or "unknown",+ "source": "skill_output",+ }+ for item in outputs+ if item.get("name")+ )+ steps.append(+ {+ "step": index,+ "skill_id": current_skill_id,+ "name": str(skill.get("name") or current_skill_id),+ "inputs": list(skill.get("inputs") or []),+ "outputs": outputs,+ "missing_inputs": missing_by_skill.get(current_skill_id, []),+ "filled_inputs": [],+ "reason": self._step_reason(+ selection.get("steps") or [],+ current_skill_id,+ ),+ }+ )++ edge_items = [edge_plan_item(candidate_edges[edge]) for edge in selected_edges]+ if missing_inputs:+ status = "needs_input"+ return {+ "valid": True,+ "detail": "",+ "plan": {+ "title": str(selection.get("title") or "Symphony fast plan").strip(),+ "status": status,+ "steps": steps,+ "stages": [+ {"stage": index, "skills": [step]}+ for index, step in enumerate(steps, start=1)+ ],+ "produced_artifacts": produced_artifacts,+ "missing_inputs": missing_inputs,+ "can_feed_edges": edge_items,+ "reason": str(selection.get("reason") or "").strip(),+ "plan_classification": (+ "executable"+ if status == "ready"+ else "structurally_valid_but_incomplete"+ ),+ "connectivity_trace": ["can_feed"] if edge_items else [],+ "source": "one_shot_fast",+ },+ }++ @staticmethod+ def _failure(+ base: dict[str, Any],+ detail: str,+ exc: Exception | None = None,+ *,+ validation: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ payload = {+ **base,+ "success": False,+ "detail": detail,+ "plans": [],+ "recommended_plans": [],+ "ranking_mode": "one_shot_fast_failed",+ "validation": validation or {"valid": False, "detail": detail},+ }+ if exc is not None:+ payload["error"] = str(exc)+ return payload++ @staticmethod+ def _skill_payload(skill: dict[str, Any]) -> dict[str, Any]:+ current_skill_id = str(skill.get("id") or "")+ return {+ "id": current_skill_id,+ "name": str(skill.get("name") or current_skill_id),+ "description": str(skill.get("description") or "")[:800],+ }++ @staticmethod+ def _edge_payload(edge: dict[str, Any]) -> dict[str, Any]:+ return {+ "source_id": skill_id(edge.get("source")),+ "target_id": skill_id(edge.get("target")),+ }++ @staticmethod+ def _normalize_step_ids(raw_steps: Any) -> list[str]:+ if not isinstance(raw_steps, list):+ return []+ output = []+ for item in raw_steps:+ current_skill_id = skill_id(+ item.get("skill_id") if isinstance(item, dict) else item+ ).strip()+ if current_skill_id and current_skill_id not in output:+ output.append(current_skill_id)+ return output++ @staticmethod+ def _normalize_selected_edges(raw_edges: Any) -> dict[str, Any]:+ if not isinstance(raw_edges, list):+ return {"edges": [], "invalid": [raw_edges]}+ edges = []+ invalid = []+ for item in raw_edges:+ if not isinstance(item, dict):+ invalid.append(item)+ continue+ source = skill_id(item.get("source_id") or item.get("source")).strip()+ target = skill_id(item.get("target_id") or item.get("target")).strip()+ if not source or not target:+ invalid.append(item)+ continue+ edge = (source, target)+ if edge not in edges:+ edges.append(edge)+ return {"edges": edges, "invalid": invalid}++ @staticmethod+ def _normalize_missing_inputs(+ raw_items: Any,+ step_ids: set[str],+ ) -> list[dict[str, Any]]:+ if not isinstance(raw_items, list):+ return []+ output = []+ for item in raw_items:+ if not isinstance(item, dict):+ continue+ current_skill_id = skill_id(item.get("skill_id")).strip()+ if current_skill_id and current_skill_id not in step_ids:+ continue+ normalized = {+ "skill_id": current_skill_id,+ "name": str(item.get("name") or "unknown"),+ "type": str(item.get("type") or "unknown"),+ }+ reason = str(item.get("reason") or "").strip()+ if reason:+ normalized["reason"] = reason+ output.append(normalized)+ return output++ @staticmethod+ def _step_reason(raw_steps: Any, target_skill_id: str) -> str:+ if not isinstance(raw_steps, list):+ return ""+ for item in raw_steps:+ if (+ isinstance(item, dict)+ and skill_id(item.get("skill_id")) == target_skill_id+ ):+ return str(item.get("reason") or "").strip()+ return ""diff --git a/jiuwenswarm/symphony/orchestration/planning/input_matching.py b/jiuwenswarm/symphony/orchestration/planning/input_matching.pynew file mode 100644index 0000000000..ebbea1a67c--- /dev/null+++ b/jiuwenswarm/symphony/orchestration/planning/input_matching.py@@ -0,0 +1,181 @@+"""Input and artifact matching helpers for orchestration plans."""++from __future__ import annotations++from typing import Any, Iterable++from jiuwenswarm.symphony.orchestration.planning.models import (+ ArtifactRef,+ InferredInput,+ PlanStep,+)+++def input_coverage_score(+ skill: dict[str, Any],+ available: Iterable[tuple[str, str]],+ *,+ inferred_inputs: list[InferredInput] | None = None,+) -> float:+ required = [+ (str(item.get("name")), str(item.get("type") or "unknown"))+ for item in skill.get("inputs", [])+ if item.get("required", True) and item.get("name")+ ]+ if not required:+ return 1.0+ available_set = set(available)+ inferred_set = inferred_input_keys(str(skill.get("id") or ""), inferred_inputs or [])+ matched = 0+ for item in required:+ if artifact_matches(item, available_set) or inferred_input_matches(+ item,+ inferred_set,+ ):+ matched += 1+ return matched / len(required)+++def consumed_user_artifact_count(+ steps: list[PlanStep],+ artifacts: list[ArtifactRef],+) -> int:+ explicit = {+ artifact.key+ for artifact in artifacts+ if artifact.source != "implicit_query"+ }+ if not steps or not explicit:+ return 0+ consumed = 0+ for item in steps[0].inputs:+ expected = (str(item.get("name")), str(item.get("type") or "unknown"))+ if artifact_matches(expected, explicit):+ consumed += 1+ return consumed+++def missing_inputs(+ skill: dict[str, Any],+ available: Iterable[tuple[str, str]],+ *,+ inferred_inputs: list[InferredInput] | None = None,+) -> list[dict[str, Any]]:+ available_set = set(available)+ inferred_set = inferred_input_keys(str(skill.get("id") or ""), inferred_inputs or [])+ missing = []+ for item in skill.get("inputs", []):+ if not item.get("required", True):+ continue+ expected = (str(item.get("name")), str(item.get("type") or "unknown"))+ if not artifact_matches(expected, available_set) and not inferred_input_matches(+ expected,+ inferred_set,+ ):+ missing.append({"name": expected[0], "type": expected[1]})+ return missing+++def filled_inputs(+ skill: dict[str, Any],+ inferred_inputs: list[InferredInput],+) -> list[dict[str, Any]]:+ skill_id_ = str(skill.get("id") or "")+ input_keys = {+ (str(item.get("name")), str(item.get("type") or "unknown"))+ for item in skill.get("inputs", [])+ if item.get("name")+ }+ filled = []+ for inferred_input in inferred_inputs:+ if inferred_input.skill_id != skill_id_:+ continue+ if inferred_input_matches((inferred_input.name, inferred_input.type), input_keys):+ filled.append(inferred_input.to_dict())+ return filled+++def inferred_input_keys(+ skill_id_: str,+ inferred_inputs: list[InferredInput],+) -> set[tuple[str, str]]:+ return {+ (item.name, item.type)+ for item in inferred_inputs+ if item.skill_id == skill_id_+ }+++def inferred_input_matches(+ expected: tuple[str, str],+ inferred: set[tuple[str, str]],+) -> bool:+ name, type_ = expected+ return any(+ candidate_name == name+ and (+ candidate_type == type_+ or candidate_type == "unknown"+ or type_ == "unknown"+ )+ for candidate_name, candidate_type in inferred+ )+++def artifact_matches(+ expected: tuple[str, str],+ available: set[tuple[str, str]],+) -> bool:+ name, type_ = expected+ if expected in available:+ return True+ return any(+ candidate_name == name and (candidate_type == "unknown" or type_ == "unknown")+ for candidate_name, candidate_type in available+ )+++def edge_feeds_missing_inputs(+ *,+ edge: dict[str, Any],+ source: dict[str, Any],+ target: dict[str, Any],+ missing_keys: set[tuple[str, str]],+) -> bool:+ if not missing_keys:+ return False+ evidence = edge.get("evidence") or {}+ supporting_fields = evidence.get("supporting_fields") or {}+ target_input_names = {+ str(item)+ for item in supporting_fields.get("target_inputs", [])+ if str(item).strip()+ }+ target_input_names.update(+ str(mapping.get("target_input"))+ for mapping in supporting_fields.get("port_mappings", [])+ if isinstance(mapping, dict) and mapping.get("target_input")+ )+ missing_names = {name for name, _ in missing_keys}+ if target_input_names & missing_names:+ return True++ source_outputs = output_keys(source)+ target_inputs = {+ (str(item.get("name")), str(item.get("type") or "unknown"))+ for item in target.get("inputs", [])+ if item.get("name")+ }+ return any(+ missing_key in target_inputs+ and artifact_matches(missing_key, set(source_outputs))+ for missing_key in missing_keys+ )+++def output_keys(skill: dict[str, Any]) -> frozenset[tuple[str, str]]:+ return frozenset(+ (str(item.get("name")), str(item.get("type") or "unknown"))+ for item in skill.get("outputs", [])+ if item.get("name")+ )diff --git a/jiuwenswarm/symphony/orchestration/planning/models.py b/jiuwenswarm/symphony/orchestration/planning/models.pynew file mode 100644index 0000000000..cb09d0a7de--- /dev/null+++ b/jiuwenswarm/symphony/orchestration/planning/models.py@@ -0,0 +1,209 @@+"""Data models for orchestration planning."""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any, Protocol+++@dataclass(frozen=True)+class ArtifactRef:+ """A normalized runtime artifact available to the orchestrator."""++ name: str+ type: str = "unknown"+ source: str = "user_query"++ @property+ def key(self) -> tuple[str, str]:+ return (self.name, self.type)++ def to_dict(self) -> dict[str, Any]:+ return {"name": self.name, "type": self.type, "source": self.source}+++@dataclass(frozen=True)+class InferredInput:+ """A skill input value inferred from the user request."""++ skill_id: str+ name: str+ type: str = "unknown"+ value: Any = None+ source: str = "llm_grounding"++ @property+ def key(self) -> tuple[str, str, str]:+ return (self.skill_id, self.name, self.type)++ def to_dict(self) -> dict[str, Any]:+ return {+ "skill_id": self.skill_id,+ "name": self.name,+ "type": self.type,+ "value": self.value,+ "source": self.source,+ }+++@dataclass(frozen=True)+class GroundedQuery:+ """User query grounded into known artifacts and seed Skills."""++ query: str+ available_artifacts: list[ArtifactRef]+ inferred_inputs: list[InferredInput] = field(default_factory=list)+ seed_skill_ids: tuple[str, ...] = ()++ def to_dict(self) -> dict[str, Any]:+ return {+ "query": self.query,+ "available_artifacts": [+ artifact.to_dict() for artifact in self.available_artifacts+ ],+ "inferred_inputs": [+ inferred_input.to_dict() for inferred_input in self.inferred_inputs+ ],+ "seed_skill_ids": list(self.seed_skill_ids),+ }+++@dataclass(frozen=True)+class PlanStep:+ """One Skill call in a candidate orchestration plan."""++ skill_id: str+ name: str+ inputs: list[dict[str, Any]]+ outputs: list[dict[str, Any]]+ missing_inputs: list[dict[str, Any]] = field(default_factory=list)+ filled_inputs: list[dict[str, Any]] = field(default_factory=list)++ def to_dict(self) -> dict[str, Any]:+ return {+ "skill_id": self.skill_id,+ "name": self.name,+ "inputs": self.inputs,+ "outputs": self.outputs,+ "missing_inputs": self.missing_inputs,+ "filled_inputs": self.filled_inputs,+ }+++@dataclass(frozen=True)+class OrchestrationPlan:+ """A candidate Skill orchestration plan."""++ steps: list[PlanStep]+ produced_artifacts: list[ArtifactRef]+ missing_inputs: list[dict[str, Any]]+ can_feed_edges: list[dict[str, Any]]+ goal_score: float+ edge_confidence: float+ consumed_user_artifacts: int+ status: str+ reasons: list[str]++ def to_dict(self) -> dict[str, Any]:+ from jiuwenswarm.symphony.orchestration.planning.plan_builder import (+ plan_stages,+ )++ return {+ "status": self.status,+ "goal_score": round(self.goal_score, 3),+ "edge_confidence": round(self.edge_confidence, 3),+ "consumed_user_artifacts": self.consumed_user_artifacts,+ "stages": plan_stages(self.steps, self.can_feed_edges),+ "steps": [+ {"step": index + 1, **step.to_dict()}+ for index, step in enumerate(self.steps)+ ],+ "produced_artifacts": [+ artifact.to_dict() for artifact in self.produced_artifacts+ ],+ "missing_inputs": self.missing_inputs,+ "can_feed_edges": self.can_feed_edges,+ "reasons": self.reasons,+ }+++class GroundingClient(Protocol):+ """Minimal JSON completion interface used by Skill orchestration."""++ async def complete_json_async(+ self,+ *,+ system_prompt: str,+ user_content: str,+ timeout: int | None = None,+ error_context: str = "LLM",+ ) -> str:+ ...+++@dataclass(frozen=True)+class BeamCandidateScore:+ """Intent score assigned to a legal beam expansion candidate."""++ skill_id: str+ score: float+ reason: str = ""+ source: str = "llm"+++class BeamCandidateScorer(Protocol):+ """Scores legal can_feed candidates for beam expansion."""++ async def score_forward_candidates(+ self,+ *,+ grounded: GroundedQuery,+ current_skill: dict[str, Any],+ candidates: list[dict[str, Any]],+ ) -> dict[str, BeamCandidateScore]:+ ...++ async def score_backward_candidates(+ self,+ *,+ grounded: GroundedQuery,+ root_skill: dict[str, Any],+ missing_inputs: list[dict[str, Any]],+ candidates: list[dict[str, Any]],+ ) -> dict[str, BeamCandidateScore]:+ ...+++@dataclass(frozen=True)+class PlanningConfig:+ """Runtime planning and ranking knobs.++ Override precedence should be applied by callers as:+ request > runtime service config > manifest defaults.+ """++ min_edge_confidence: float = 0.7+ max_depth: int = 4+ max_plans: int = 20+ max_branch: int = 8+ max_entry_skills: int = 40+ beam_width: int = 40+ min_beam_candidate_score: float = 0.2+ top_m: int = 12+ top_k: int = 3+ include_candidates: bool = True+ conservative_reject: bool = True+ hard_fail_missing_inputs: bool = False+ enable_backward_search: bool = True+++@dataclass(frozen=True)+class SearchState:+ """Internal forward-search state."""++ skill_ids: tuple[str, ...]+ available: frozenset[tuple[str, str]]+ edges: tuple[int, ...]+ beam_score: float = 0.0+ score_reasons: tuple[str, ...] = ()diff --git a/jiuwenswarm/symphony/orchestration/planning/plan_builder.py b/jiuwenswarm/symphony/orchestration/planning/plan_builder.pynew file mode 100644index 0000000000..f7c8fb9a16--- /dev/null+++ b/jiuwenswarm/symphony/orchestration/planning/plan_builder.py@@ -0,0 +1,340 @@+"""Build and compose concrete orchestration plans from search state."""++from __future__ import annotations++from collections import defaultdict, deque+from typing import Any++from jiuwenswarm.symphony.orchestration.planning.input_matching import (+ consumed_user_artifact_count,+ filled_inputs,+ missing_inputs,+ output_keys,+)+from jiuwenswarm.symphony.orchestration.planning.models import (+ ArtifactRef,+ GroundedQuery,+ OrchestrationPlan,+ PlanStep,+ SearchState,+)+from jiuwenswarm.symphony.orchestration.planning.utils import skill_id+++def state_to_plan(+ *,+ state: SearchState,+ grounded: GroundedQuery,+ skill_by_id: dict[str, dict[str, Any]],+ can_feed_edges: list[dict[str, Any]],+) -> OrchestrationPlan:+ available = set(state.available)+ steps: list[PlanStep] = []+ all_missing: list[dict[str, Any]] = []+ produced: set[tuple[str, str]] = set()+ reasons: list[str] = []++ for current_skill_id in state.skill_ids:+ skill = skill_by_id[current_skill_id]+ filled = filled_inputs(skill, grounded.inferred_inputs)+ missing = missing_inputs(+ skill,+ available,+ inferred_inputs=grounded.inferred_inputs,+ )+ all_missing.extend({**item, "skill_id": current_skill_id} for item in missing)+ outputs = output_keys(skill)+ produced.update(outputs)+ available.update(outputs)+ steps.append(+ PlanStep(+ skill_id=current_skill_id,+ name=skill.get("name", current_skill_id),+ inputs=[+ {"name": item.get("name"), "type": item.get("type")}+ for item in skill.get("inputs", [])+ ],+ outputs=[+ {"name": item.get("name"), "type": item.get("type")}+ for item in skill.get("outputs", [])+ ],+ missing_inputs=missing,+ filled_inputs=filled,+ )+ )+ if current_skill_id in grounded.seed_skill_ids:+ reasons.append(f"{current_skill_id} selected as a seed skill")++ edges = [can_feed_edges[index] for index in state.edges]+ edge_confidence = (+ sum(float(edge.get("confidence") or 0.0) for edge in edges) / len(edges)+ if edges+ else 1.0+ )+ goal_score = plan_goal_score(+ skill_ids=state.skill_ids,+ seed_skill_ids=grounded.seed_skill_ids,+ )+ status = "ready" if not all_missing else "needs_input"+ return OrchestrationPlan(+ steps=steps,+ produced_artifacts=[+ ArtifactRef(name=name, type=type_, source="skill_output")+ for name, type_ in sorted(produced)+ ],+ missing_inputs=all_missing,+ can_feed_edges=[edge_plan_item(edge) for edge in edges],+ goal_score=goal_score,+ edge_confidence=edge_confidence,+ consumed_user_artifacts=consumed_user_artifact_count(+ steps,+ grounded.available_artifacts,+ ),+ status=status,+ reasons=[*reasons, *state.score_reasons][:8],+ )+++def build_outgoing_edges(edges: list[dict[str, Any]]) -> dict[str, list[int]]:+ outgoing: dict[str, list[int]] = defaultdict(list)+ for index, edge in enumerate(edges):+ outgoing[skill_id(edge.get("source"))].append(index)+ return outgoing+++def build_incoming_edges(edges: list[dict[str, Any]]) -> dict[str, list[int]]:+ incoming: dict[str, list[int]] = defaultdict(list)+ for index, edge in enumerate(edges):+ incoming[skill_id(edge.get("target"))].append(index)+ return incoming+++def plan_goal_score(+ *,+ skill_ids: tuple[str, ...],+ seed_skill_ids: tuple[str, ...] = (),+) -> float:+ return sum(+ seed_skill_score(current_skill_id, seed_skill_ids=seed_skill_ids)+ for current_skill_id in skill_ids+ )+++def seed_skill_score(skill_id_: str, *, seed_skill_ids: tuple[str, ...]) -> float:+ return 10.0 if skill_id_ in seed_skill_ids else 0.0+++def dedupe_plans(plans: list[OrchestrationPlan]) -> list[OrchestrationPlan]:+ deduped: dict[tuple[str, ...], OrchestrationPlan] = {}+ for plan in plans:+ key = tuple(step.skill_id for step in plan.steps)+ existing = deduped.get(key)+ if existing is None or plan.goal_score > existing.goal_score:+ deduped[key] = plan+ return list(deduped.values())+++def compose_dag_plans(+ path_plans: list[OrchestrationPlan],+ *,+ max_plans: int,+) -> list[OrchestrationPlan]:+ composed: list[OrchestrationPlan] = []+ composed.extend(compose_overlapping_path_plans(path_plans, max_plans=max_plans))++ groups: dict[str, list[OrchestrationPlan]] = defaultdict(list)+ for plan in path_plans:+ if plan.steps:+ groups[plan.steps[0].skill_id].append(plan)++ for group in groups.values():+ branch_plans = [plan for plan in group if len(plan.steps) > 1]+ if len(branch_plans) < 2:+ continue+ composed.append(compose_plan_group(branch_plans))++ return dedupe_plans([*composed, *path_plans])[: max_plans * 2]+++def compose_overlapping_path_plans(+ path_plans: list[OrchestrationPlan],+ *,+ max_plans: int,+) -> list[OrchestrationPlan]:+ output: list[OrchestrationPlan] = []+ seen: set[tuple[str, ...]] = set()+ for left in path_plans:+ left_ids = tuple(step.skill_id for step in left.steps)+ if len(left_ids) < 2:+ continue+ for right in path_plans:+ if left is right:+ continue+ right_ids = tuple(step.skill_id for step in right.steps)+ if len(right_ids) < 2:+ continue+ overlap = path_overlap_size(left_ids, right_ids)+ if overlap <= 0:+ continue+ stitched_ids = (*left_ids, *right_ids[overlap:])+ if len(stitched_ids) <= max(len(left_ids), len(right_ids)):+ continue+ if len(set(stitched_ids)) != len(stitched_ids):+ continue+ if stitched_ids in seen:+ continue+ seen.add(stitched_ids)+ output.append(compose_plan_group([left, right]))+ if len(output) >= max(1, max_plans):+ return output+ return output+++def path_overlap_size(+ left: tuple[str, ...],+ right: tuple[str, ...],+) -> int:+ max_overlap = min(len(left), len(right)) - 1+ for size in range(max_overlap, 0, -1):+ if left[-size:] == right[:size]:+ return size+ return 0+++def compose_plan_group(plans: list[OrchestrationPlan]) -> OrchestrationPlan:+ steps_by_id: dict[str, PlanStep] = {}+ edges_by_key: dict[tuple[str, str], dict[str, Any]] = {}+ produced_by_key: dict[tuple[str, str], ArtifactRef] = {}+ missing_by_key: dict[tuple[str, str, str], dict[str, Any]] = {}+ reasons: list[str] = []++ for plan in plans:+ for step in plan.steps:+ steps_by_id.setdefault(step.skill_id, step)+ for edge in plan.can_feed_edges:+ key = (str(edge.get("source_id") or ""), str(edge.get("target_id") or ""))+ if key[0] and key[1]:+ edges_by_key.setdefault(key, edge)+ for artifact in plan.produced_artifacts:+ produced_by_key.setdefault(artifact.key, artifact)+ for item in plan.missing_inputs:+ key = (+ str(item.get("skill_id") or ""),+ str(item.get("name") or ""),+ str(item.get("type") or "unknown"),+ )+ missing_by_key.setdefault(key, dict(item))+ for reason in plan.reasons:+ if reason not in reasons:+ reasons.append(reason)++ ordered_step_ids = topological_step_ids(+ set(steps_by_id),+ list(edges_by_key.values()),+ )+ steps = []+ for current_skill_id in ordered_step_ids:+ step = steps_by_id.get(current_skill_id)+ if step is not None:+ steps.append(step)+ missing_inputs_list = list(missing_by_key.values())+ edge_confidence = (+ sum(float(edge.get("confidence") or 0.0) for edge in edges_by_key.values())+ / len(edges_by_key)+ if edges_by_key+ else 1.0+ )+ return OrchestrationPlan(+ steps=steps,+ produced_artifacts=list(produced_by_key.values()),+ missing_inputs=missing_inputs_list,+ can_feed_edges=list(edges_by_key.values()),+ goal_score=sum(plan.goal_score for plan in plans),+ edge_confidence=edge_confidence,+ consumed_user_artifacts=max(plan.consumed_user_artifacts for plan in plans),+ status="ready" if not missing_inputs_list else "needs_input",+ reasons=reasons[:8],+ )+++def topological_step_ids(+ skill_ids: set[str],+ edges: list[dict[str, Any]],+) -> list[str]:+ incoming = {current_skill_id: 0 for current_skill_id in skill_ids}+ outgoing: dict[str, list[str]] = defaultdict(list)+ for edge in edges:+ source_id = str(edge.get("source_id") or "")+ target_id = str(edge.get("target_id") or "")+ if source_id not in skill_ids or target_id not in skill_ids:+ continue+ outgoing[source_id].append(target_id)+ incoming[target_id] += 1++ queue = deque(+ sorted(current_skill_id for current_skill_id, count in incoming.items() if count == 0)+ )+ ordered: list[str] = []+ while queue:+ current_skill_id = queue.popleft()+ ordered.append(current_skill_id)+ for target_id in sorted(outgoing.get(current_skill_id, [])):+ incoming[target_id] -= 1+ if incoming[target_id] == 0:+ queue.append(target_id)+ ordered.extend(sorted(skill_ids - set(ordered)))+ return ordered+++def plan_stages(+ steps: list[PlanStep],+ edges: list[dict[str, Any]],+) -> list[dict[str, Any]]:+ step_by_id = {step.skill_id: step for step in steps}+ remaining = set(step_by_id)+ incoming: dict[str, set[str]] = {+ current_skill_id: set() for current_skill_id in remaining+ }+ for edge in edges:+ source_id = str(edge.get("source_id") or "")+ target_id = str(edge.get("target_id") or "")+ if source_id in remaining and target_id in remaining:+ incoming[target_id].add(source_id)++ stages = []+ completed: set[str] = set()+ while remaining:+ ready = sorted(+ current_skill_id+ for current_skill_id in remaining+ if incoming[current_skill_id] <= completed+ )+ if not ready:+ ready = sorted(remaining)+ stages.append(+ {+ "stage": len(stages) + 1,+ "skills": [+ step_by_id[current_skill_id].to_dict()+ for current_skill_id in ready+ ],+ }+ )+ completed.update(ready)+ remaining.difference_update(ready)+ return stages+++def edge_plan_item(edge: dict[str, Any]) -> dict[str, Any]:+ evidence = edge.get("evidence") or {}+ supporting_fields = evidence.get("supporting_fields") or {}+ return {+ "source_id": skill_id(edge.get("source")),+ "target_id": skill_id(edge.get("target")),+ "confidence": edge.get("confidence"),+ "method": edge.get("method"),+ "port_mappings": supporting_fields.get("port_mappings", [])[:5],+ "source_outputs": supporting_fields.get("source_outputs", [])[:3],+ "target_inputs": supporting_fields.get("target_inputs", [])[:3],+ "reasons": evidence.get("reasons", [])[:3],+ }diff --git a/jiuwenswarm/symphony/orchestration/planning/utils.py b/jiuwenswarm/symphony/orchestration/planning/utils.pynew file mode 100644index 0000000000..8cbc5d5a65--- /dev/null+++ b/jiuwenswarm/symphony/orchestration/planning/utils.py@@ -0,0 +1,15 @@+# -*- coding: utf-8 -*-+"""Utility helpers for orchestration planning."""++from __future__ import annotations++from typing import Any+++def skill_id(node_id: Any) -> str:+ text = str(node_id or "")+ return text.removeprefix("skill:")+++def clamp(value: float) -> float:+ return max(0.0, min(1.0, float(value)))diff --git a/jiuwenswarm/symphony/orchestration/service.py b/jiuwenswarm/symphony/orchestration/service.pynew file mode 100644index 0000000000..4b98b1199a--- /dev/null+++ b/jiuwenswarm/symphony/orchestration/service.py@@ -0,0 +1,47 @@+"""Online orchestration planning service APIs."""++from __future__ import annotations++from pathlib import Path+from typing import Any++from jiuwenswarm.symphony.config import SymphonyOrchestrationConfig+from jiuwenswarm.symphony.llm import LLMConfig+from jiuwenswarm.symphony.orchestration import load_score_artifacts+from jiuwenswarm.symphony.orchestration.execution_graph import build_execution_graph+from jiuwenswarm.symphony.orchestration.planning.fast import FastOneShotPlanner+from jiuwenswarm.symphony.orchestration.planning.utils import clamp+++async def plan_from_score(+ score_dir: str | Path,+ query: str,+ llm_config: LLMConfig | None = None,+ *,+ top_k: int = 3,+ max_depth: int = 4,+ min_edge_confidence: float = 0.7,+ llm_client: Any | None = None,+ ranker: Any | None = None,+ orchestration_config: SymphonyOrchestrationConfig | None = None,+) -> dict[str, Any]:+ """Run online planning from an existing Symphony score."""++ if orchestration_config is not None:+ top_k = orchestration_config.top_k+ max_depth = orchestration_config.max_depth+ min_edge_confidence = orchestration_config.min_edge_confidence+ artifacts = load_score_artifacts(score_dir)++ if orchestration_config is not None and orchestration_config.mode != "fast":+ raise ValueError(f"Unsupported orchestration mode: {orchestration_config.mode}")++ result = await FastOneShotPlanner(+ artifacts,+ llm_config=llm_config,+ llm_client=llm_client,+ min_edge_confidence=clamp(min_edge_confidence),+ top_k=max(1, int(top_k)),+ ).plan(query)+ result["execution_graph"] = build_execution_graph(result, artifacts)+ return resultdiff --git a/jiuwenswarm/symphony/score_state.py b/jiuwenswarm/symphony/score_state.pynew file mode 100644index 0000000000..c8941fcf76--- /dev/null+++ b/jiuwenswarm/symphony/score_state.py@@ -0,0 +1,169 @@+"""Persistent state for Symphony Score builds."""++from __future__ import annotations++import hashlib+import json+from dataclasses import dataclass, field+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Iterable++from jiuwenswarm.symphony.fingerprint.models import SkillFingerprint++SCORE_STATE_FILENAME = "score_state.json"+++@dataclass(frozen=True)+class ScoreStateEntry:+ """State tracked for one Skill folder in a Score build."""++ skill_id: str+ relative_path: str+ skill_md_sha256: str+ fingerprint_hash: str+ status: str = "active"+ updated_at: str = ""++ def to_dict(self) -> dict[str, Any]:+ return {+ "skill_id": self.skill_id,+ "relative_path": self.relative_path,+ "skill_md_sha256": self.skill_md_sha256,+ "fingerprint_hash": self.fingerprint_hash,+ "status": self.status,+ "updated_at": self.updated_at,+ }++ @classmethod+ def from_dict(cls, payload: dict[str, Any]) -> "ScoreStateEntry":+ return cls(+ skill_id=str(payload.get("skill_id") or ""),+ relative_path=str(payload.get("relative_path") or ""),+ skill_md_sha256=str(payload.get("skill_md_sha256") or ""),+ fingerprint_hash=str(payload.get("fingerprint_hash") or ""),+ status=str(payload.get("status") or "active"),+ updated_at=str(payload.get("updated_at") or ""),+ )+++@dataclass(frozen=True)+class ScoreState:+ """Serializable incremental Score state."""++ schema_version: str = "Symphony-score-state-v1"+ skills: dict[str, ScoreStateEntry] = field(default_factory=dict)++ def active_entries(self) -> dict[str, ScoreStateEntry]:+ return {+ path: entry+ for path, entry in self.skills.items()+ if entry.status == "active"+ }++ def to_dict(self) -> dict[str, Any]:+ return {+ "schema_version": self.schema_version,+ "skills": {+ path: entry.to_dict()+ for path, entry in sorted(self.skills.items())+ },+ }++ @classmethod+ def from_dict(cls, payload: dict[str, Any]) -> "ScoreState":+ raw_skills = payload.get("skills") or {}+ skills: dict[str, ScoreStateEntry] = {}+ if isinstance(raw_skills, dict):+ for key, value in raw_skills.items():+ if not isinstance(value, dict):+ continue+ entry = ScoreStateEntry.from_dict(value)+ relative_path = entry.relative_path or str(key)+ skills[relative_path] = ScoreStateEntry(+ skill_id=entry.skill_id,+ relative_path=relative_path,+ skill_md_sha256=entry.skill_md_sha256,+ fingerprint_hash=entry.fingerprint_hash,+ status=entry.status,+ updated_at=entry.updated_at,+ )+ return cls(+ schema_version=str(payload.get("schema_version") or "Symphony-score-state-v1"),+ skills=skills,+ )+++class ScoreStateBuilder:+ """Compute folder hashes and the next persistent Score state."""++ def folder_hashes(self, folders: Iterable[Any]) -> dict[str, str]:+ return {+ folder.relative_path: self.file_sha256(folder.entry)+ for folder in folders+ }++ def next_state(+ self,+ *,+ folders: list[Any],+ current_hashes: dict[str, str],+ fingerprints_by_path: dict[str, SkillFingerprint],+ old_state: ScoreState,+ removed_paths: set[str],+ ) -> ScoreState:+ now = datetime.now(timezone.utc).isoformat()+ entries: dict[str, ScoreStateEntry] = {}+ for folder in folders:+ fingerprint = fingerprints_by_path[folder.relative_path]+ entries[folder.relative_path] = ScoreStateEntry(+ skill_id=fingerprint.id,+ relative_path=folder.relative_path,+ skill_md_sha256=current_hashes[folder.relative_path],+ fingerprint_hash=self.fingerprint_hash(fingerprint),+ status="active",+ updated_at=now,+ )++ for relative_path in sorted(removed_paths):+ old_entry = old_state.skills.get(relative_path)+ if old_entry is None:+ continue+ entries[relative_path] = ScoreStateEntry(+ skill_id=old_entry.skill_id,+ relative_path=relative_path,+ skill_md_sha256=old_entry.skill_md_sha256,+ fingerprint_hash=old_entry.fingerprint_hash,+ status="removed",+ updated_at=now,+ )+ return ScoreState(skills=entries)++ @staticmethod+ def fingerprint_hash(fingerprint: SkillFingerprint) -> str:+ payload = json.dumps(fingerprint.to_dict(), ensure_ascii=False, sort_keys=True)+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()++ @staticmethod+ def file_sha256(path: Path) -> str:+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def load_score_state(score_dir: str | Path) -> ScoreState:+ """Load score_state.json, returning an empty state when it is missing."""++ path = Path(score_dir) / SCORE_STATE_FILENAME+ if not path.exists():+ return ScoreState()+ return ScoreState.from_dict(json.loads(path.read_text(encoding="utf-8")))+++def write_score_state(state: ScoreState, score_dir: str | Path) -> None:+ """Write score_state.json with stable formatting."""++ output_path = Path(score_dir)+ output_path.mkdir(parents=True, exist_ok=True)+ (output_path / SCORE_STATE_FILENAME).write_text(+ json.dumps(state.to_dict(), ensure_ascii=False, indent=2),+ encoding="utf-8",+ )