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 总谱增量构建、指纹/关系缓存、断点续构建
layShang2643026ece6794a
diff --git a/jiuwenswarm/extensions/symphony/extension.py b/jiuwenswarm/extensions/symphony/extension.pyindex c80852cfca..88a9ac9d2c 100644--- a/jiuwenswarm/extensions/symphony/extension.py+++ b/jiuwenswarm/extensions/symphony/extension.py@@ -18,6 +18,7 @@ from jiuwenswarm.symphony.build import score_statusfrom jiuwenswarm.symphony.orchestration import load_score_artifactsfrom jiuwenswarm.symphony.orchestration.execution_graph import select_primary_planfrom jiuwenswarm.symphony.orchestration.service import plan_from_score+from jiuwenswarm.symphony.score_storage import resolve_score_artifact_dirSYMPHONY_BUILD_SCORE = "symphony.build_score"SYMPHONY_SCORE_STATUS = "symphony.score_status"@@ -396,7 +397,11 @@ def _current_token_usage_summary() -> dict[str, Any]:def _read_manifest_token_usage(score_dir: Path) -> dict[str, Any]:try:- payload = json.loads((score_dir / "score_manifest.json").read_text(encoding="utf-8"))+ payload = json.loads(+ (resolve_score_artifact_dir(score_dir) / "score_manifest.json").read_text(+ encoding="utf-8"+ )+ )except (OSError, json.JSONDecodeError):return {}if not isinstance(payload, dict):diff --git a/jiuwenswarm/symphony/build.py b/jiuwenswarm/symphony/build.pyindex 2423b12477..e2ff900981 100644--- a/jiuwenswarm/symphony/build.py+++ b/jiuwenswarm/symphony/build.py@@ -3,7 +3,11 @@from __future__ import annotationsimport json-from dataclasses import dataclass+import hashlib+import os+import uuid+from dataclasses import asdict, dataclass+from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Callable@@ -25,6 +29,7 @@ from jiuwenswarm.symphony.fingerprint import (write_extraction_result,)from jiuwenswarm.symphony.graph.matcher import (+ CachedOntologyMatcher,OntologyMatcher,OpenAICompatibleOntologyMatcher,)@@ -37,6 +42,13 @@ from jiuwenswarm.symphony.score_state import (load_score_state,write_score_state,)+from jiuwenswarm.symphony.score_storage import (+ build_artifact_dir,+ build_run_dir,+ latest_incomplete_build,+ publish_artifact_dir,+ score_exists,+)@dataclass(frozen=True)@@ -49,6 +61,8 @@ class ScoreStatus:changed_count: intadded_count: intremoved_count: int+ resume_available: bool = False+ checkpoint_dir: str = ""detail: str = ""def to_dict(self) -> dict[str, Any]:@@ -61,6 +75,8 @@ class ScoreStatus:"changed_count": self.changed_count,"added_count": self.added_count,"removed_count": self.removed_count,+ "resume_available": self.resume_available,+ "checkpoint_dir": self.checkpoint_dir,"detail": self.detail,}@@ -75,6 +91,9 @@ class ScoreBuildResult:removed_count: intedge_count: intdiagnostics_count: int+ relation_reused_count: int = 0+ relation_resolved_count: int = 0+ version: str = ""detail: str = ""def to_dict(self) -> dict[str, Any]:@@ -87,6 +106,9 @@ class ScoreBuildResult:"removed_count": self.removed_count,"edge_count": self.edge_count,"diagnostics_count": self.diagnostics_count,+ "relation_reused_count": self.relation_reused_count,+ "relation_resolved_count": self.relation_resolved_count,+ "version": self.version,"detail": self.detail,}@@ -179,7 +201,7 @@ class SymphonyScoreBuilder: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()+ exists = score_exists(output_dir)added = [path for path in current_hashes if path not in active_entries]changed = [path@@ -188,6 +210,7 @@ class SymphonyScoreBuilder:]removed = [path for path in active_entries if path not in current_hashes]stale = (not exists) or bool(added or changed or removed)+ resume_from = latest_incomplete_build(output_dir)detail = "score is fresh"if not exists:detail = "Symphony Score is missing"@@ -203,6 +226,8 @@ class SymphonyScoreBuilder:changed_count=len(changed),added_count=len(added),removed_count=len(removed),+ resume_available=resume_from is not None,+ checkpoint_dir=str(resume_from) if resume_from is not None else "",detail=detail,)@@ -218,11 +243,32 @@ class SymphonyScoreBuilder:io_name_resolver: Any | None = None,build_log: Callable[..., None] | None = None,symphony_config: SymphonyConfig | None = None,+ resume: bool = True,) -> 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()+ run_id = _new_run_id()+ checkpoint = _BuildCheckpoint(build_run_dir(output_dir, run_id))+ artifact_dir = build_artifact_dir(output_dir, run_id)+ artifact_dir.mkdir(parents=True, exist_ok=True)+ resume_from = latest_incomplete_build(output_dir) if resume else None+ checkpoint.record(+ "update.start",+ status="running",+ skills_root=str(skills_root),+ score_dir=str(output_dir),+ artifact_dir=str(artifact_dir),+ force=force,+ resume_from=str(resume_from) if resume_from is not None else "",+ )+ if resume_from is not None:+ _record_build_log(+ build_log,+ "resume.detected",+ checkpoint_dir=str(resume_from),+ )normalization_runtime_config = runtime_config.fingerprint.normalizationnormalization_config = NormalizationConfig(@@ -255,12 +301,22 @@ class SymphonyScoreBuilder:normalization_workers=runtime_config.fingerprint.normalization.workers,normalization_batch_size=runtime_config.fingerprint.normalization.batch_size,)+ fingerprint_signature = _fingerprint_signature(runtime_config, llm_config)_record_build_log(build_log, "scan.start", skills_root=str(skills_root))+ checkpoint.record("fingerprint.start", status="running")extraction_result = await fingerprint_extractor.extract_from_root(skills_root,- output_dir=output_dir,+ output_dir=artifact_dir,max_depth=runtime_config.fingerprint.scan.max_depth,force=force,+ cache_dir=output_dir,+ fingerprint_signature=fingerprint_signature,+ )+ checkpoint.record(+ "fingerprint.done",+ status="running",+ reused_count=extraction_result.reused_count,+ extracted_count=extraction_result.extracted_count,)_record_build_log(build_log,@@ -268,7 +324,7 @@ class SymphonyScoreBuilder:fingerprint_count=len(extraction_result.fingerprints),diagnostics_count=len(extraction_result.diagnostics),)- write_extraction_result(extraction_result, output_dir)+ write_extraction_result(extraction_result, artifact_dir)_record_build_log(build_log, "artifact.fingerprints.write.done")_record_build_log(@@ -282,11 +338,30 @@ class SymphonyScoreBuilder:build_config=runtime_config.build,build_log=build_log,)+ if not force:+ matcher = CachedOntologyMatcher(+ matcher,+ output_dir / "cache" / "relation_matches.json",+ fingerprints=extraction_result.fingerprints,+ )graph_builder = GraphBuilder(matcher=matcher)+ checkpoint.record("graph.start", status="running")graph_result = await graph_builder.build(extraction_result.fingerprints,progress=build_log,)+ relation_cache_stats = getattr(matcher, "stats", None)+ relation_reused_count = int(getattr(relation_cache_stats, "reused_count", 0) or 0)+ relation_resolved_count = int(+ getattr(relation_cache_stats, "resolved_count", 0) or 0+ )+ checkpoint.record(+ "graph.done",+ status="running",+ edge_count=len(graph_result.graph.edges),+ relation_reused_count=relation_reused_count,+ relation_resolved_count=relation_resolved_count,+ )_record_build_log(build_log,"graph.build.done",@@ -294,10 +369,12 @@ class SymphonyScoreBuilder:match_count=len(graph_result.llm_matches),edge_count=len(graph_result.graph.edges),diagnostics_count=len(graph_result.diagnostics),+ relation_reused_count=relation_reused_count,+ relation_resolved_count=relation_resolved_count,)_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)+ write_graph_build_result(graph_result, artifact_dir)+ _write_io_vocab(extraction_result.io_name_vocab, artifact_dir)_record_build_log(build_log, "artifact.graph.write.done")new_state = self.state_builder.next_state(@@ -310,10 +387,22 @@ class SymphonyScoreBuilder:_record_build_log(build_log,"state.write.start",- path=str(output_dir / SCORE_STATE_FILENAME),+ path=str(artifact_dir / SCORE_STATE_FILENAME),)- write_score_state(new_state, output_dir)+ write_score_state(new_state, artifact_dir)_record_build_log(build_log, "state.write.done")+ checkpoint.record("publish.start", status="running")+ published_dir = publish_artifact_dir(+ output_dir,+ artifact_dir,+ version=run_id,+ )+ checkpoint.record(+ "publish.done",+ status="success",+ version=run_id,+ published_dir=str(published_dir),+ )return ScoreBuildResult(success=True,@@ -326,6 +415,9 @@ class SymphonyScoreBuilder:diagnostics_count=(len(extraction_result.diagnostics) + len(graph_result.diagnostics)),+ relation_reused_count=relation_reused_count,+ relation_resolved_count=relation_resolved_count,+ version=run_id,)@@ -360,6 +452,7 @@ async def build_score(build_log: Callable[..., None] | None = None,symphony_config: SymphonyConfig | None = None,runtime_factory: ScoreBuildRuntimeFactory | None = None,+ resume: bool = True,) -> ScoreBuildResult:"""Build or refresh the offline Symphony Score."""@@ -378,6 +471,7 @@ async def build_score(io_name_resolver=io_name_resolver,build_log=build_log,symphony_config=symphony_config,+ resume=resume,)@@ -412,3 +506,70 @@ def _write_io_vocab(payload: dict[str, Any], score_dir: Path) -> None:json.dumps(payload, ensure_ascii=False, indent=2),encoding="utf-8",)+++class _BuildCheckpoint:+ def __init__(self, run_dir: Path) -> None:+ self.run_dir = run_dir+ self.path = run_dir / "checkpoint.json"++ def record(self, stage: str, *, status: str, **details: Any) -> None:+ now = datetime.now(timezone.utc).isoformat()+ payload = {+ "schema_version": "Symphony-build-checkpoint-v1",+ "run_id": self.run_dir.name,+ "stage": stage,+ "status": status,+ "updated_at": now,+ **details,+ }+ if self.path.is_file():+ try:+ previous = json.loads(self.path.read_text(encoding="utf-8"))+ except json.JSONDecodeError:+ previous = {}+ payload.setdefault("started_at", previous.get("started_at") or now)+ else:+ payload["started_at"] = now+ self.run_dir.mkdir(parents=True, exist_ok=True)+ tmp = self.path.with_suffix(".json.tmp")+ tmp.write_text(+ json.dumps(payload, ensure_ascii=False, indent=2, default=str),+ encoding="utf-8",+ )+ os.replace(tmp, self.path)+++def _new_run_id() -> str:+ stamp = datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S")+ return f"{stamp}-{uuid.uuid4().hex[:12]}"+++def _fingerprint_signature(+ runtime_config: SymphonyConfig,+ llm_config: LLMConfig | None,+) -> str:+ payload = {+ "schema_version": "Symphony-fingerprint-signature-v1",+ "fingerprint": asdict(runtime_config.fingerprint),+ "llm": _llm_signature(llm_config),+ }+ return _stable_hash(payload)+++def _llm_signature(llm_config: LLMConfig | None) -> dict[str, Any]:+ if llm_config is None:+ return {}+ return {+ "backend": getattr(llm_config, "backend", ""),+ "model": getattr(llm_config, "model", ""),+ "temperature": getattr(llm_config, "temperature", ""),+ }+++def _stable_hash(payload: Any) -> str:+ return hashlib.sha256(+ json.dumps(payload, ensure_ascii=False, sort_keys=True, default=str).encode(+ "utf-8"+ )+ ).hexdigest()diff --git a/jiuwenswarm/symphony/fingerprint/incremental.py b/jiuwenswarm/symphony/fingerprint/incremental.pyindex 26b1b6a4f5..a4cc496b39 100644--- a/jiuwenswarm/symphony/fingerprint/incremental.py+++ b/jiuwenswarm/symphony/fingerprint/incremental.py@@ -3,16 +3,26 @@from __future__ import annotationsimport json+import hashlib+import osfrom dataclasses import dataclass+from datetime import datetime, timezonefrom pathlib import Path-from typing import Callable--from jiuwenswarm.symphony.fingerprint.models import SkillFolder, SkillFingerprint+from typing import Any, Callable++from jiuwenswarm.symphony.fingerprint.models import (+ ExtractionDiagnostic,+ NormalizationDecision,+ NormalizationResult,+ SkillFolder,+ SkillFingerprint,+)from jiuwenswarm.symphony.fingerprint.normalize import (IONameVocabulary,SkillFingerprintNormalizer,)from jiuwenswarm.symphony.score_state import load_score_state+from jiuwenswarm.symphony.score_storage import resolve_score_artifact_dirIndexedSkillFolder = tuple[int, SkillFolder]@@ -29,8 +39,10 @@ class FingerprintReusePlan:class IncrementalFingerprintStore:"""Load prior Score artifacts and decide what must be re-extracted."""- def __init__(self, output_dir: Path) -> None:+ def __init__(self, output_dir: Path, *, signature: str = "") -> None:self.output_dir = output_dir+ self.signature = signature+ self.cache = FingerprintResultCache(output_dir, signature=signature)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}@@ -69,6 +81,17 @@ class IncrementalFingerprintStore:if on_reuse is not None:on_reuse(folder_index, folder, old_fingerprint)continue+ cached = None if force else self.cache.load(+ folder.relative_path,+ current_hashes[folder.relative_path],+ )+ if cached is not None:+ fingerprints.append(cached.fingerprint)+ fingerprints_by_path[folder.relative_path] = cached.fingerprint+ reused_count += 1+ if on_reuse is not None:+ on_reuse(folder_index, folder, cached.fingerprint)+ continuechanged_folders.append((folder_index, folder))return FingerprintReusePlan(@@ -79,9 +102,93 @@ class IncrementalFingerprintStore:reused_count=reused_count,)+ def save_result(+ self,+ folder: SkillFolder,+ skill_md_sha256: str,+ result: NormalizationResult,+ ) -> None:+ self.cache.save(folder.relative_path, skill_md_sha256, result)+++class FingerprintResultCache:+ """Per-skill normalized fingerprint cache.++ The cache is intentionally outside published Score artifacts. A failed build+ may still leave valid per-skill extraction results that can be reused by the+ next build.+ """++ def __init__(self, score_dir: Path, *, signature: str = "") -> None:+ self.score_dir = Path(score_dir).resolve()+ self.signature = signature+ self.root = self.score_dir / "cache" / "fingerprints"++ def load(+ self,+ relative_path: str,+ skill_md_sha256: str,+ ) -> NormalizationResult | None:+ path = self._path(relative_path)+ if not path.is_file():+ return None+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return None+ if str(payload.get("skill_md_sha256") or "") != skill_md_sha256:+ return None+ if str(payload.get("signature") or "") != self.signature:+ return None+ fingerprint_payload = payload.get("fingerprint")+ if not isinstance(fingerprint_payload, dict):+ return None+ return NormalizationResult(+ fingerprint=SkillFingerprint.from_dict(fingerprint_payload),+ diagnostics=[+ _diagnostic_from_dict(item)+ for item in payload.get("diagnostics", [])+ if isinstance(item, dict)+ ],+ decisions=[+ _decision_from_dict(item)+ for item in payload.get("decisions", [])+ if isinstance(item, dict)+ ],+ )++ def save(+ self,+ relative_path: str,+ skill_md_sha256: str,+ result: NormalizationResult,+ ) -> None:+ self.root.mkdir(parents=True, exist_ok=True)+ payload = {+ "schema_version": "Symphony-fingerprint-cache-v1",+ "relative_path": relative_path,+ "skill_md_sha256": skill_md_sha256,+ "signature": self.signature,+ "fingerprint": result.fingerprint.to_dict(),+ "diagnostics": [item.to_dict() for item in result.diagnostics],+ "decisions": [item.to_dict() for item in result.decisions],+ "updated_at": datetime.now(timezone.utc).isoformat(),+ }+ target = self._path(relative_path)+ tmp = target.with_suffix(target.suffix + ".tmp")+ tmp.write_text(+ json.dumps(payload, ensure_ascii=False, indent=2),+ encoding="utf-8",+ )+ os.replace(tmp, target)++ def _path(self, relative_path: str) -> Path:+ digest = hashlib.sha256(relative_path.encode("utf-8")).hexdigest()+ return self.root / f"{digest}.json"+def load_fingerprints(output_dir: Path) -> list[SkillFingerprint]:- path = output_dir / "fingerprints.json"+ path = resolve_score_artifact_dir(output_dir) / "fingerprints.json"if not path.exists():return []payload = json.loads(path.read_text(encoding="utf-8"))@@ -96,7 +203,36 @@ def load_io_name_vocabulary(output_dir: Path,normalizer: SkillFingerprintNormalizer,) -> IONameVocabulary:- path = output_dir / "io_name_vocab.json"+ path = resolve_score_artifact_dir(output_dir) / "io_name_vocab.json"if not path.exists():return IONameVocabulary.from_config(normalizer.config)return IONameVocabulary.load(path, normalizer.config)+++def _diagnostic_from_dict(payload: dict[str, Any]) -> ExtractionDiagnostic:+ return ExtractionDiagnostic(+ stage=str(payload.get("stage") or ""),+ severity=str(payload.get("severity") or ""),+ code=str(payload.get("code") or ""),+ message=str(payload.get("message") or ""),+ skill_id=payload.get("skill_id"),+ path=payload.get("path"),+ details=payload.get("details") if isinstance(payload.get("details"), dict) else {},+ )+++def _decision_from_dict(payload: dict[str, Any]) -> NormalizationDecision:+ return NormalizationDecision(+ skill_id=str(payload.get("skill_id") or ""),+ path=payload.get("path"),+ direction=str(payload.get("direction") or ""),+ field=str(payload.get("field") or ""),+ raw_value=str(payload.get("raw_value") or ""),+ token=str(payload.get("token") or ""),+ normalized_value=str(payload.get("normalized_value") or ""),+ method=str(payload.get("method") or ""),+ vocab=str(payload.get("vocab") or ""),+ vocab_version=str(payload.get("vocab_version") or ""),+ confidence=float(payload.get("confidence") or 0.0),+ details=payload.get("details") if isinstance(payload.get("details"), dict) else {},+ )diff --git a/jiuwenswarm/symphony/fingerprint/pipeline.py b/jiuwenswarm/symphony/fingerprint/pipeline.pyindex 567097522b..a33fb4b89c 100644--- a/jiuwenswarm/symphony/fingerprint/pipeline.py+++ b/jiuwenswarm/symphony/fingerprint/pipeline.py@@ -69,16 +69,22 @@ class FingerprintExtractor:*,max_depth: int | None = None,force: bool = False,+ cache_dir: Union[Path, str] | None = None,+ fingerprint_signature: str = "",) -> FingerprintExtractionResult:output_path = Path(output_dir).resolve()+ cache_path = Path(cache_dir).resolve() if cache_dir is not None else output_pathfolders, 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)+ incremental_store = IncrementalFingerprintStore(+ cache_path,+ signature=fingerprint_signature,+ )self.normalizer.io_name_vocabulary = load_io_name_vocabulary(- output_path,+ cache_path,self.normalizer,)reuse_plan = incremental_store.plan(@@ -112,6 +118,11 @@ class FingerprintExtractor:normalized = extracted_results[folder_index]fingerprints.append(normalized.fingerprint)fingerprints_by_path[folder.relative_path] = normalized.fingerprint+ incremental_store.save_result(+ folder,+ current_hashes[folder.relative_path],+ normalized,+ )diagnostics.extend(normalized.diagnostics)decisions.extend(normalized.decisions)self._emit_event(diff --git a/jiuwenswarm/symphony/graph/matcher/__init__.py b/jiuwenswarm/symphony/graph/matcher/__init__.pyindex 1a9ba5e115..1146a3654e 100644--- a/jiuwenswarm/symphony/graph/matcher/__init__.py+++ b/jiuwenswarm/symphony/graph/matcher/__init__.py@@ -1,6 +1,7 @@"""LLM-backed relation matching for Skill graph."""from jiuwenswarm.symphony.graph.matcher.matcher import (+ CachedOntologyMatcher,DEFAULT_THRESHOLDS,OntologyMatcher,OpenAICompatibleOntologyMatcher,@@ -9,6 +10,7 @@ from jiuwenswarm.symphony.graph.matcher.matcher import (__all__ = ["DEFAULT_THRESHOLDS",+ "CachedOntologyMatcher","OntologyMatcher","OpenAICompatibleOntologyMatcher","validate_llm_matches",diff --git a/jiuwenswarm/symphony/graph/matcher/cache.py b/jiuwenswarm/symphony/graph/matcher/cache.pynew file mode 100644index 0000000000..c03f800099--- /dev/null+++ b/jiuwenswarm/symphony/graph/matcher/cache.py@@ -0,0 +1,266 @@+"""Persistent cache for ontology relation matching."""++from __future__ import annotations++import hashlib+import json+import os+from dataclasses import dataclass+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Iterable++from jiuwenswarm.symphony.fingerprint.models import SkillFingerprint+from jiuwenswarm.symphony.graph.models import LLMMatch, RelationCandidate, SkillRegistry+++@dataclass(frozen=True)+class RelationCacheStats:+ reused_count: int = 0+ resolved_count: int = 0+ stored_count: int = 0+++class CachedOntologyMatcher:+ """Wrap an ontology matcher with a per-candidate persistent cache."""++ def __init__(+ self,+ matcher: Any,+ cache_path: str | Path,+ *,+ fingerprints: Iterable[SkillFingerprint],+ ) -> None:+ self.matcher = matcher+ self.cache = RelationMatchCache(+ cache_path,+ matcher_signature=_matcher_signature(matcher),+ fingerprints=fingerprints,+ )+ self.diagnostics = []+ self.stats = RelationCacheStats()++ async def match(+ self,+ registry: SkillRegistry,+ candidates: Iterable[RelationCandidate],+ ) -> list[LLMMatch]:+ candidate_list = list(candidates)+ cached_matches: list[tuple[int, list[LLMMatch]]] = []+ misses: list[tuple[int, RelationCandidate]] = []+ reused_count = 0+ for index, candidate in enumerate(candidate_list):+ matches = self.cache.load(candidate)+ if matches is None:+ misses.append((index, candidate))+ continue+ cached_matches.append((index, matches))+ reused_count += 1++ resolved_by_index: dict[int, list[LLMMatch]] = {}+ diagnostics: list[Any] = []+ if misses:+ for chunk in _chunked(misses, _matcher_batch_size(self.matcher)):+ miss_candidates = [candidate for _, candidate in chunk]+ resolved_matches = list(+ await self.matcher.match(registry, miss_candidates)+ )+ resolved_by_candidate = _matches_by_candidate(+ miss_candidates,+ resolved_matches,+ )+ for index, candidate in chunk:+ matches = resolved_by_candidate.get(candidate.key, [])+ resolved_by_index[index] = matches+ self.cache.store(candidate, matches)+ self.cache.flush()+ if hasattr(self.matcher, "diagnostics"):+ diagnostics.extend(list(self.matcher.diagnostics))++ combined: list[tuple[int, LLMMatch]] = []+ for index, matches in cached_matches:+ combined.extend((index, match) for match in matches)+ for index, matches in resolved_by_index.items():+ combined.extend((index, match) for match in matches)++ if diagnostics:+ self.diagnostics = diagnostics+ elif hasattr(self.matcher, "diagnostics"):+ self.diagnostics = list(self.matcher.diagnostics)+ self.stats = RelationCacheStats(+ reused_count=reused_count,+ resolved_count=len(misses),+ stored_count=len(misses),+ )+ ordered_matches = []+ for _index, match in sorted(+ combined,+ key=lambda item: (item[0], item[1].source_id, item[1].target_id),+ ):+ ordered_matches.append(match)+ return ordered_matches++ def manifest_metadata(self) -> dict[str, Any]:+ if hasattr(self.matcher, "manifest_metadata"):+ metadata = dict(self.matcher.manifest_metadata())+ else:+ metadata = {"matcher": self.matcher.__class__.__name__}+ metadata["relation_cache"] = {+ "schema_version": "Symphony-relation-match-cache-v1",+ "reused_count": self.stats.reused_count,+ "resolved_count": self.stats.resolved_count,+ }+ return metadata++ @property+ def thresholds(self) -> dict[str, float]:+ return dict(getattr(self.matcher, "thresholds", {}))+++class RelationMatchCache:+ """JSON cache keyed by candidate evidence, fingerprints, and matcher config."""++ def __init__(+ self,+ path: str | Path,+ *,+ matcher_signature: dict[str, Any],+ fingerprints: Iterable[SkillFingerprint],+ ) -> None:+ self.path = Path(path).resolve()+ self.matcher_signature = matcher_signature+ self.fingerprint_hashes = {+ item.id: _stable_sha256(item.to_dict())+ for item in fingerprints+ }+ self._records = self._load()+ self._dirty = False++ def load(self, candidate: RelationCandidate) -> list[LLMMatch] | None:+ record = self._records.get(self._key(candidate))+ if not isinstance(record, dict):+ return None+ if record.get("schema_version") != "Symphony-relation-match-cache-v1":+ return None+ return [+ _match_from_dict(item)+ for item in record.get("matches", [])+ if isinstance(item, dict)+ ]++ def store(self, candidate: RelationCandidate, matches: list[LLMMatch]) -> None:+ self._records[self._key(candidate)] = {+ "schema_version": "Symphony-relation-match-cache-v1",+ "candidate_id": candidate.key,+ "matches": [match.to_dict() for match in matches],+ "updated_at": datetime.now(timezone.utc).isoformat(),+ }+ self._dirty = True++ def flush(self) -> None:+ if not self._dirty:+ return+ self.path.parent.mkdir(parents=True, exist_ok=True)+ payload = {+ "schema_version": "Symphony-relation-match-cache-index-v1",+ "records": self._records,+ }+ tmp = self.path.with_suffix(self.path.suffix + ".tmp")+ tmp.write_text(+ json.dumps(payload, ensure_ascii=False, indent=2),+ encoding="utf-8",+ )+ os.replace(tmp, self.path)+ self._dirty = False++ def _load(self) -> dict[str, Any]:+ if not self.path.is_file():+ return {}+ try:+ payload = json.loads(self.path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return {}+ records = payload.get("records")+ return records if isinstance(records, dict) else {}++ def _key(self, candidate: RelationCandidate) -> str:+ source_hash = self.fingerprint_hashes.get(candidate.source_id, "")+ target_hash = self.fingerprint_hashes.get(candidate.target_id, "")+ payload = {+ "candidate": candidate.to_dict(),+ "source_fingerprint_hash": source_hash,+ "target_fingerprint_hash": target_hash,+ "matcher": self.matcher_signature,+ }+ return _stable_sha256(payload)+++def _matches_by_candidate(+ candidates: list[RelationCandidate],+ matches: list[LLMMatch],+) -> dict[str, list[LLMMatch]]:+ candidate_by_pair = {}+ for candidate in candidates:+ candidate_by_pair[(candidate.source_id, candidate.target_id)] = candidate.key+ candidate_by_pair[(candidate.target_id, candidate.source_id)] = candidate.key+ output: dict[str, list[LLMMatch]] = {candidate.key: [] for candidate in candidates}+ for match in matches:+ candidate_key = match.candidate_id or candidate_by_pair.get(+ (match.source_id, match.target_id)+ )+ if candidate_key in output:+ output[candidate_key].append(match)+ return output+++def _matcher_signature(matcher: Any) -> dict[str, Any]:+ if hasattr(matcher, "manifest_metadata"):+ metadata = dict(matcher.manifest_metadata())+ else:+ metadata = {"matcher": matcher.__class__.__name__}+ metadata.pop("api_key", None)+ metadata.pop("base_url", None)+ thresholds = getattr(matcher, "thresholds", None)+ if thresholds is not None:+ metadata["thresholds"] = dict(thresholds)+ return metadata+++def _matcher_batch_size(matcher: Any) -> int:+ try:+ return max(1, int(getattr(matcher, "batch_size", 0) or 0))+ except (TypeError, ValueError):+ return 1+++def _chunked(values: list[Any], size: int) -> list[list[Any]]:+ return [+ values[index: index + size]+ for index in range(0, len(values), max(1, size))+ ]+++def _match_from_dict(payload: dict[str, Any]) -> LLMMatch:+ return LLMMatch(+ source_id=str(payload.get("source_id") or ""),+ target_id=str(payload.get("target_id") or ""),+ relation_type=str(payload.get("relation_type") or ""),+ confidence=float(payload.get("confidence") or 0.0),+ method=str(payload.get("method") or "llm_ontology_match"),+ reasons=[str(item) for item in payload.get("reasons", [])],+ supporting_fields=(+ payload.get("supporting_fields")+ if isinstance(payload.get("supporting_fields"), dict)+ else {}+ ),+ candidate_id=payload.get("candidate_id"),+ accepted=bool(payload.get("accepted", False)),+ diagnostics=[str(item) for item in payload.get("diagnostics", [])],+ raw=payload.get("raw") if isinstance(payload.get("raw"), dict) else {},+ )+++def _stable_sha256(payload: Any) -> str:+ return hashlib.sha256(+ json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8")+ ).hexdigest()diff --git a/jiuwenswarm/symphony/graph/matcher/matcher.py b/jiuwenswarm/symphony/graph/matcher/matcher.pyindex bd557ec553..b23b09bee2 100644--- a/jiuwenswarm/symphony/graph/matcher/matcher.py+++ b/jiuwenswarm/symphony/graph/matcher/matcher.py@@ -6,10 +6,12 @@ from jiuwenswarm.symphony.graph.matcher.openai import (OntologyMatcher,OpenAICompatibleOntologyMatcher,)+from jiuwenswarm.symphony.graph.matcher.cache import CachedOntologyMatcherfrom jiuwenswarm.symphony.graph.matcher.validation import validate_llm_matches__all__ = ["DEFAULT_THRESHOLDS",+ "CachedOntologyMatcher","MatchProgress","OntologyMatcher","OpenAICompatibleOntologyMatcher",diff --git a/jiuwenswarm/symphony/graph/matcher/openai.py b/jiuwenswarm/symphony/graph/matcher/openai.pyindex 9436b4c53e..45aaacf210 100644--- a/jiuwenswarm/symphony/graph/matcher/openai.py+++ b/jiuwenswarm/symphony/graph/matcher/openai.py@@ -141,7 +141,6 @@ class OpenAICompatibleOntologyMatcher: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,diff --git a/jiuwenswarm/symphony/orchestration/artifacts.py b/jiuwenswarm/symphony/orchestration/artifacts.pyindex b3d5670e6c..c276552130 100644--- a/jiuwenswarm/symphony/orchestration/artifacts.py+++ b/jiuwenswarm/symphony/orchestration/artifacts.py@@ -7,6 +7,8 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any+from jiuwenswarm.symphony.score_storage import resolve_score_artifact_dir+@dataclass(frozen=True)class ScoreArtifacts:@@ -27,7 +29,7 @@ class ScoreArtifacts:def load_score_artifacts(score_dir: str | Path) -> ScoreArtifacts:"""Load Score artifacts through score_manifest.json."""- root = Path(score_dir).resolve()+ root = resolve_score_artifact_dir(score_dir)manifest = _read_json(root / "score_manifest.json")artifacts = manifest.get("artifacts", {})skills_payload = _read_json(root / artifacts.get("skills", "skills.json"))diff --git a/jiuwenswarm/symphony/score_state.py b/jiuwenswarm/symphony/score_state.pyindex c8941fcf76..70ab8f498f 100644--- a/jiuwenswarm/symphony/score_state.py+++ b/jiuwenswarm/symphony/score_state.py@@ -10,6 +10,7 @@ from pathlib import Pathfrom typing import Any, Iterablefrom jiuwenswarm.symphony.fingerprint.models import SkillFingerprint+from jiuwenswarm.symphony.score_storage import resolve_score_artifact_dirSCORE_STATE_FILENAME = "score_state.json"@@ -152,7 +153,7 @@ class ScoreStateBuilder: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+ path = resolve_score_artifact_dir(score_dir) / SCORE_STATE_FILENAMEif not path.exists():return ScoreState()return ScoreState.from_dict(json.loads(path.read_text(encoding="utf-8")))diff --git a/jiuwenswarm/symphony/score_storage.py b/jiuwenswarm/symphony/score_storage.pynew file mode 100644index 0000000000..90fe68c094--- /dev/null+++ b/jiuwenswarm/symphony/score_storage.py@@ -0,0 +1,144 @@+"""Versioned storage helpers for Symphony Score artifacts."""++from __future__ import annotations++import json+import os+from dataclasses import dataclass+from pathlib import Path+from typing import Any++CURRENT_POINTER_FILENAME = "current.json"+VERSIONS_DIRNAME = "versions"+BUILD_RUNS_DIRNAME = ".build_runs"+++@dataclass(frozen=True)+class ScorePointer:+ """Pointer to the currently published Score version."""++ version: str+ path: str++ def to_dict(self) -> dict[str, Any]:+ return {+ "schema_version": "Symphony-score-pointer-v1",+ "version": self.version,+ "path": self.path,+ }++ @classmethod+ def from_dict(cls, payload: dict[str, Any]) -> "ScorePointer":+ version = str(payload.get("version") or "").strip()+ path = str(payload.get("path") or "").strip()+ if not version or not path:+ raise ValueError("Invalid Symphony score pointer.")+ return cls(version=version, path=path)+++def resolve_score_artifact_dir(score_dir: str | Path) -> Path:+ """Return the directory containing the currently readable artifacts.++ New builds publish versioned artifacts behind ``current.json``. Older+ layouts stored artifacts directly in ``score_dir``; this helper keeps that+ legacy layout readable.+ """++ root = Path(score_dir).resolve()+ pointer_path = root / CURRENT_POINTER_FILENAME+ if not pointer_path.is_file():+ return root++ pointer = ScorePointer.from_dict(+ json.loads(pointer_path.read_text(encoding="utf-8"))+ )+ candidate = (root / pointer.path).resolve()+ if not _is_relative_to(candidate, root):+ raise ValueError(f"Symphony score pointer escapes score_dir: {candidate}")+ return candidate+++def score_manifest_path(score_dir: str | Path) -> Path:+ return resolve_score_artifact_dir(score_dir) / "score_manifest.json"+++def score_exists(score_dir: str | Path) -> bool:+ return score_manifest_path(score_dir).is_file()+++def build_runs_dir(score_dir: str | Path) -> Path:+ return Path(score_dir).resolve() / BUILD_RUNS_DIRNAME+++def build_run_dir(score_dir: str | Path, run_id: str) -> Path:+ return build_runs_dir(score_dir) / run_id+++def build_artifact_dir(score_dir: str | Path, run_id: str) -> Path:+ return build_run_dir(score_dir, run_id) / "artifacts"+++def publish_artifact_dir(+ score_dir: str | Path,+ artifact_dir: str | Path,+ *,+ version: str,+) -> Path:+ """Publish a fully built artifact directory as the current Score version."""++ root = Path(score_dir).resolve()+ source = Path(artifact_dir).resolve()+ versions_dir = root / VERSIONS_DIRNAME+ versions_dir.mkdir(parents=True, exist_ok=True)+ target = versions_dir / version+ if target.exists():+ raise FileExistsError(f"Symphony score version already exists: {target}")+ os.replace(source, target)++ pointer = ScorePointer(+ version=version,+ path=f"{VERSIONS_DIRNAME}/{version}",+ )+ tmp_pointer = root / f".{CURRENT_POINTER_FILENAME}.{version}.tmp"+ tmp_pointer.write_text(+ json.dumps(pointer.to_dict(), ensure_ascii=False, indent=2),+ encoding="utf-8",+ )+ os.replace(tmp_pointer, root / CURRENT_POINTER_FILENAME)+ return target+++def latest_incomplete_build(score_dir: str | Path) -> Path | None:+ runs_root = build_runs_dir(score_dir)+ if not runs_root.is_dir():+ return None+ candidates = []+ for child in runs_root.iterdir():+ checkpoint = child / "checkpoint.json"+ if not checkpoint.is_file():+ continue+ try:+ payload = json.loads(checkpoint.read_text(encoding="utf-8"))+ except json.JSONDecodeError:+ continue+ candidates.append(+ (+ str(payload.get("updated_at") or ""),+ str(payload.get("status") or ""),+ child,+ )+ )+ if not candidates:+ return None+ _updated_at, status, path = sorted(candidates, key=lambda item: item[0])[-1]+ if status in {"running", "failed"}:+ return path+ return None+++def _is_relative_to(path: Path, root: Path) -> bool:+ try:+ path.relative_to(root)+ except ValueError:+ return False+ return Truediff --git a/tests/unit_tests/symphony/test_graph_service.py b/tests/unit_tests/symphony/test_graph_service.pyindex bc38cfc5ac..c703c6bb35 100644--- a/tests/unit_tests/symphony/test_graph_service.py+++ b/tests/unit_tests/symphony/test_graph_service.py@@ -38,11 +38,14 @@ from jiuwenswarm.symphony.score_state import ()from jiuwenswarm.symphony.build import (ScoreBuildRuntimeFactory,- score_status,build_score,+ score_status,+ _fingerprint_signature,)from jiuwenswarm.symphony.llm import LLMConfigfrom jiuwenswarm.symphony.config import symphony_config_from_dict+from jiuwenswarm.symphony.graph.matcher.cache import CachedOntologyMatcher+from jiuwenswarm.symphony.orchestration.artifacts import load_score_artifactsclass _SchemaExtractor:@@ -58,6 +61,25 @@ class _SchemaExtractor:)+class _LinkedSchemaExtractor:+ def __init__(self):+ self.extract_count = 0++ async def extract(self, manifest):+ self.extract_count += 1+ if manifest.folder.id_hint == "skill-1":+ return ExtractedSkillSchema(+ description="Create a draft.",+ inputs=[ParameterSpec(name="brief", type="text")],+ outputs=[ArtifactSpec(name="draft", type="markdown")],+ )+ return ExtractedSkillSchema(+ description="Review a draft.",+ inputs=[ParameterSpec(name="draft", type="markdown")],+ outputs=[ArtifactSpec(name="review", type="markdown")],+ )++class _NoopMatcher:thresholds = {"can_feed": 0.7}@@ -69,6 +91,33 @@ class _NoopMatcher:return {"matcher": "noop"}+class _CountingAcceptedMatcher:+ thresholds = {"can_feed": 0.7}++ def __init__(self):+ self.calls = []++ async def match(self, registry, candidates):+ del registry+ candidates = list(candidates)+ self.calls.append([candidate.key for candidate in candidates])+ return [+ LLMMatch(+ source_id=candidate.source_id,+ target_id=candidate.target_id,+ relation_type="can_feed",+ confidence=0.9,+ accepted=True,+ candidate_id=candidate.key,+ )+ for candidate in candidates+ ]++ @staticmethod+ def manifest_metadata():+ return {"matcher": "counting-accepted"}++class _MismatchedBatchSchemaExtractor(_SchemaExtractor):use_batch = Truebatch_size = 2@@ -640,6 +689,60 @@ def test_default_matcher_uses_configured_min_edge_confidence():assert matcher.thresholds == {"can_feed": 0.42}+def test_llm_endpoint_does_not_change_fingerprint_cache_signature():+ runtime_config = symphony_config_from_dict({})+ first_signature = _fingerprint_signature(+ runtime_config,+ LLMConfig(+ model="model",+ model_client_config={+ "api_key": "key-a",+ "api_base": "https://a.example.test/v1",+ "client_provider": "openai",+ },+ ),+ )+ second_signature = _fingerprint_signature(+ runtime_config,+ LLMConfig(+ model="model",+ model_client_config={+ "api_key": "key-b",+ "api_base": "https://b.example.test/v1",+ "client_provider": "openai",+ },+ ),+ )++ assert first_signature == second_signature+++def test_llm_endpoint_is_not_recorded_in_relation_cache_signature(tmp_path):+ matcher = ScoreBuildRuntimeFactory().matcher(+ LLMConfig(+ model="model",+ model_client_config={+ "api_key": "key",+ "api_base": "https://example.test/v1",+ "client_provider": "openai",+ },+ ),+ build_config=symphony_config_from_dict({}).build,+ )++ metadata = matcher.manifest_metadata()+ cached_matcher = CachedOntologyMatcher(+ matcher,+ tmp_path / "relation_matches.json",+ fingerprints=[],+ )++ assert "base_url" not in metadata+ assert "api_key" not in metadata+ assert "base_url" not in cached_matcher.cache.matcher_signature+ assert "api_key" not in cached_matcher.cache.matcher_signature++@pytest.mark.asyncioasync def test_build_score_uses_configured_scan_max_depth(tmp_path):skills_root = tmp_path / "skills"@@ -734,6 +837,71 @@ async def test_build_score_reuses_unchanged_and_reextracts_changed_skills(tmp_paassert fourth.reused_count == 0+async def test_build_score_publishes_versioned_artifacts_and_loads_current(tmp_path):+ skills_root = tmp_path / "skills"+ score_dir = tmp_path / "score"+ for index in range(2):+ skill_dir = skills_root / f"skill-{index + 1}"+ skill_dir.mkdir(parents=True)+ (skill_dir / "SKILL.md").write_text(+ f"---\nname: Skill {index + 1}\n---\n\nTest skill {index + 1}.",+ encoding="utf-8",+ )++ result = await build_score(+ skills_root,+ score_dir,+ schema_extractor=_LinkedSchemaExtractor(),+ matcher=_CountingAcceptedMatcher(),+ io_name_resolver=_CreateNewIONameResolver(),+ )+ artifacts = load_score_artifacts(score_dir)++ assert result.version+ assert (score_dir / "current.json").is_file()+ assert (score_dir / "versions" / result.version / "score_manifest.json").is_file()+ assert artifacts.score_dir == (score_dir / "versions" / result.version).resolve()+ assert [skill["id"] for skill in artifacts.skills] == ["skill-1", "skill-2"]+++async def test_build_score_reuses_unchanged_relation_matches(tmp_path):+ skills_root = tmp_path / "skills"+ score_dir = tmp_path / "score"+ for index in range(2):+ skill_dir = skills_root / f"skill-{index + 1}"+ skill_dir.mkdir(parents=True)+ (skill_dir / "SKILL.md").write_text(+ f"---\nname: Skill {index + 1}\n---\n\nTest skill {index + 1}.",+ encoding="utf-8",+ )++ first_matcher = _CountingAcceptedMatcher()+ first = await build_score(+ skills_root,+ score_dir,+ schema_extractor=_LinkedSchemaExtractor(),+ matcher=first_matcher,+ io_name_resolver=_CreateNewIONameResolver(),+ )+ second_matcher = _CountingAcceptedMatcher()+ second = await build_score(+ skills_root,+ score_dir,+ schema_extractor=_LinkedSchemaExtractor(),+ matcher=second_matcher,+ io_name_resolver=_CreateNewIONameResolver(),+ )++ assert first.relation_resolved_count >= 1+ assert first.relation_reused_count == 0+ assert first_matcher.calls+ assert second.relation_resolved_count == 0+ assert second.relation_reused_count == first.relation_resolved_count+ assert second_matcher.calls == []++@pytest.mark.asyncioasync def test_build_score_reports_removed_skills(tmp_path):skills_root = tmp_path / "skills"@@ -843,6 +1011,47 @@ async def test_fingerprint_extractor_extract_from_root_preserves_changed_folder_]+async def test_fingerprint_extractor_reuses_per_skill_cache_without_published_state(tmp_path):+ skills_root = tmp_path / "skills"+ output_dir = tmp_path / "score"+ skill_dir = skills_root / "skill-1"+ skill_dir.mkdir(parents=True)+ (skill_dir / "SKILL.md").write_text(+ "---\nname: Skill 1\n---\n\nTest skill 1.",+ encoding="utf-8",+ )++ first_schema_extractor = _SchemaExtractor()+ first = await FingerprintExtractor(+ schema_extractor=first_schema_extractor,+ normalizer=SkillFingerprintNormalizer(+ io_name_resolver=_CreateNewIONameResolver(),+ ),+ ).extract_from_root(+ skills_root,+ output_dir=output_dir,+ fingerprint_signature="test-signature",+ )+ second_schema_extractor = _SchemaExtractor()+ second = await FingerprintExtractor(+ schema_extractor=second_schema_extractor,+ normalizer=SkillFingerprintNormalizer(+ io_name_resolver=_CreateNewIONameResolver(),+ ),+ ).extract_from_root(+ skills_root,+ output_dir=output_dir,+ fingerprint_signature="test-signature",+ )++ assert first.extracted_count == 1+ assert first.reused_count == 0+ assert second.extracted_count == 0+ assert second.reused_count == 1+ assert second_schema_extractor.extract_count == 0++@pytest.mark.asyncioasync def test_fingerprint_extractor_batch_schema_count_mismatch_raises(tmp_path):skills_root = tmp_path / "skills"