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
fix(symphony): 优化图构建时间
lin-xiaoyu759ef7b29c1b
diff --git a/jiuwenswarm/symphony/build.py b/jiuwenswarm/symphony/build.pyindex c708c178a4..ce5f03473a 100644--- a/jiuwenswarm/symphony/build.py+++ b/jiuwenswarm/symphony/build.py@@ -28,6 +28,9 @@ from jiuwenswarm.symphony.fingerprint import (SkillSchemaExtractor,write_extraction_result,)+from jiuwenswarm.symphony.fingerprint.extract.extractor import (+ SCHEMA_EXTRACTION_PROTOCOL_VERSION,+)from jiuwenswarm.symphony.graph.candidates import CandidateGeneratorfrom jiuwenswarm.symphony.graph.matcher import (CachedOntologyMatcher,@@ -559,6 +562,7 @@ def _fingerprint_signature() -> str:payload = {"schema_version": "Symphony-fingerprint-signature-v1",+ "extraction_protocol": SCHEMA_EXTRACTION_PROTOCOL_VERSION,"fingerprint": asdict(runtime_config.fingerprint),"llm": _llm_signature(llm_config),}diff --git a/jiuwenswarm/symphony/fingerprint/extract/extractor.py b/jiuwenswarm/symphony/fingerprint/extract/extractor.pyindex c7a75b576b..5d6cf70e23 100644--- a/jiuwenswarm/symphony/fingerprint/extract/extractor.py+++ b/jiuwenswarm/symphony/fingerprint/extract/extractor.py@@ -9,6 +9,7 @@ from jiuwenswarm.symphony.llm import (LLMConfig,create_llm_client,llm_usage_context,+ thinking_disabled_request_overrides,)from jiuwenswarm.symphony.fingerprint.models import (ArtifactSpec,@@ -16,10 +17,11 @@ from jiuwenswarm.symphony.fingerprint.models import (ParameterSpec,RawSkillManifest,)+from jiuwenswarm.symphony.shared.llm_payload import compact_json, prune_empty-_LOW_REASONING_REQUEST_OVERRIDES = {- "extra_body": {"thinking": {"type": "disabled"}},-}+SCHEMA_EXTRACTION_PROTOCOL_VERSION = "symphony-schema-extraction-v2"+_MAX_WARNING_COUNT = 3+_MAX_REASON_LENGTH = 160class LLMSchemaExtractor:@@ -42,13 +44,11 @@ class LLMSchemaExtractor: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,+ user_content=compact_json(+ _build_llm_context(manifest, body_limit=self.body_limit)),error_context="LLM schema extraction",- request_overrides=_LOW_REASONING_REQUEST_OVERRIDES,+ request_overrides=thinking_disabled_request_overrides(),)try:payload = json.loads(content)@@ -71,16 +71,14 @@ class LLMSchemaExtractor:[{"system_prompt": _SCHEMA_EXTRACTION_PROMPT,- "user_content": json.dumps(+ "user_content": compact_json(_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,+ request_overrides=thinking_disabled_request_overrides(),)schemas: List[ExtractedSkillSchema] = []for index, content in enumerate(contents, start=1):@@ -118,27 +116,24 @@ class LLMSchemaExtractor:self,manifests: List[RawSkillManifest],) -> List[ExtractedSkillSchema]:+ expected_refs = [f"s{index}" for index in range(1, len(manifests) + 1)]+ contexts = [+ _build_llm_context(+ manifest,+ body_limit=self.body_limit,+ skill_ref=skill_ref,+ )+ for manifest, skill_ref in zip(manifests, expected_refs)+ ]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,- ),+ user_content=compact_json({"skills": contexts}),error_context="LLM schema extraction prompt batch",- request_overrides=_LOW_REASONING_REQUEST_OVERRIDES,+ request_overrides=thinking_disabled_request_overrides(),)try:payload = json.loads(content)@@ -152,7 +147,6 @@ class LLMSchemaExtractor: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):@@ -180,11 +174,12 @@ class LLMSchemaExtractor: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", [])]+ warnings = _short_texts(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())+ warnings.extend(_short_texts(raw_output_notes))+ warnings = warnings[:_MAX_WARNING_COUNT]return ExtractedSkillSchema(description=str(payload.get("description") or ""),@@ -221,18 +216,29 @@ def _build_llm_context(manifest: RawSkillManifest,*,body_limit: int | None = None,+ skill_ref: str | 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",- },+ return prune_empty({+ "skill_ref": skill_ref,"frontmatter": manifest.frontmatter,"body": body,- "body_truncated": body_limit is not None and len(manifest.body) > body_limit,- }+ "body_truncated": (+ True if body_limit is not None and len(manifest.body) > body_limit else None+ ),+ })+++def _short_texts(values: Any) -> List[str]:+ if not isinstance(values, list):+ return []+ texts: List[str] = []+ for item in values:+ text = str(item).strip()+ if text:+ texts.append(text[:_MAX_REASON_LENGTH])+ return textsdef _normalize_body_limit(body_limit: int | None) -> int | None:@@ -241,112 +247,40 @@ def _normalize_body_limit(body_limit: int | None) -> int | 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 artifact kind or concrete-format that is passed between Skills. For media resources, prefer the media-artifact type even when the runtime value is a URL, local path, file reference,-base64 string, or bytes string. For example, imageUrl, translated_image_url,-and image base64 should use type=image. audio_url, audioUrl, audio_file_path,-and audio base64 should use type=audio. video_url, videoUrl, video_path, and-mp4_url should use type=video. Use type=url for ordinary links, webpages,-download links, or non-media remote references.--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. A generated image URL should-use name=image or translated_image_url and type=image, with URL details in the-description. Generated audio/video URLs should similarly use type=audio or-type=video, not type=url.--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.--If an input is a user's natural-language task, request, instruction, topic, or-free-form text to be interpreted by the Skill, name it text, query, or topic-instead of command. Reserve command for true control commands such as CLI-subcommands, action enums, command-line flags, execution switches, or a closed-set of operation names.--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_PROMPT = """Extract a normalized Skill I/O fingerprint from the supplied SKILL.md.++Return JSON only:+{+ "description": "concise capability summary",+ "inputs": [{"name": "semantic_role", "type": "type", "required": true,+ "description": "short description"}],+ "outputs": [{"name": "semantic_deliverable", "type": "type",+ "description": "short description"}],+ "confidence": 0.0,+ "warnings": []+}++Rules:+1. Use only capabilities and runtime I/O supported by all supplied content.+ If body_truncated is true, report uncertainty instead of inventing fields.+2. Inputs are caller-provided runtime values. Exclude credentials, environment+ setup, permissions, caches, telemetry and internal state.+3. Outputs are user-facing or downstream deliverables. Extract the semantic+ artifact, not API wrappers, status fields, logs, debug data or containers.+4. Use short canonical semantic names and put details in descriptions.+5. Classify by artifact semantics rather than transport: image/audio/video+ URLs, paths or base64 remain image/audio/video. Use url for ordinary links.+6. Preferred types: text, markdown, json, csv, table, yaml, xml, pdf, html,+ docx, pptx, xlsx, image, audio, video, file, path, url, code, archive, unknown.+7. Set required=true only when normal execution requires caller input.+8. Treat free-form tasks as query, text or topic; reserve command for explicit+ control operations. Do not emit duplicate semantic inputs or outputs.+9. Keep warnings factual and brief. Return at most three."""_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.+Input is {{"skills": [...]}}. Return {{"schemas": [...]}} with exactly one+schema per input Skill. Preserve each short skill_ref exactly, keep Skills+independent, and return no additional Skills."""diff --git a/jiuwenswarm/symphony/fingerprint/normalize/io_name_resolver.py b/jiuwenswarm/symphony/fingerprint/normalize/io_name_resolver.pyindex 10c9861550..5c0aeca090 100644--- a/jiuwenswarm/symphony/fingerprint/normalize/io_name_resolver.py+++ b/jiuwenswarm/symphony/fingerprint/normalize/io_name_resolver.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport jsonfrom threading import RLock-from typing import Any, Callable, Dict, List, Optional, Set, Tuple+from typing import Any, Callable, Dict, List, Optional, Setfrom jiuwenswarm.symphony.fingerprint.normalize.io_name_vocab import (IONameCandidate,@@ -15,7 +15,9 @@ from jiuwenswarm.symphony.llm import (LLMConfig,create_llm_client,llm_usage_context,+ thinking_disabled_request_overrides,)+from jiuwenswarm.symphony.shared.llm_payload import compact_json, prune_empty_ACTION_ALIAS_EXISTING = "alias_existing"_ACTION_CREATE_NEW = "create_new"@@ -29,6 +31,8 @@ _ALLOWED_ACTIONS = frozenset(_ACTION_EXCLUDE_FROM_VOCAB,})+_MAX_CONTEXT_DESCRIPTION_LENGTH = 160+_MAX_REASON_LENGTH = 160class LLMIONameResolver:@@ -53,11 +57,10 @@ class LLMIONameResolver:candidates_by_skill: List[List[IONameCandidate]],vocabulary: IONameVocabulary,) -> Dict[str, IONameResolution]:- candidate_groups: List[Tuple[str, List[IONameCandidate]]] = []+ pending_candidates: List[IONameCandidate] = []resolutions: Dict[str, IONameResolution] = {}seen: Set[str] = set()- for index, candidates in enumerate(candidates_by_skill):- unique_candidates: List[IONameCandidate] = []+ for candidates in candidates_by_skill:for candidate in candidates:if not candidate.token or candidate.token in seen:continue@@ -67,41 +70,31 @@ class LLMIONameResolver:if cached is not None:resolutions[candidate.token] = cachedcontinue- unique_candidates.append(candidate)- if unique_candidates:- candidate_groups.append(- (_candidate_group_ref(index, unique_candidates), unique_candidates)- )+ pending_candidates.append(candidate)- if not candidate_groups:+ if not pending_candidates:return resolutions+ candidates_by_id = {+ f"i{index}": candidate+ for index, candidate in enumerate(pending_candidates, start=1)+ }context = {- "skills": [- {- "skill_ref": skill_ref,- "candidates": [- _candidate_prompt_payload(candidate)- for candidate in candidates- ],- }- for skill_ref, candidates in candidate_groups+ "candidates": [+ _candidate_prompt_payload(candidate_id, candidate)+ for candidate_id, candidate in candidates_by_id.items()],"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)+ for candidate in pending_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),+ user_content=compact_json(context),timeout=200,error_context="IO name vocabulary prompt batch LLM",- request_overrides={- "extra_body": {"thinking": {"type": "disabled"}},- },+ request_overrides=thinking_disabled_request_overrides(),)try:payload = json.loads(content)@@ -111,55 +104,40 @@ class LLMIONameResolver:f"content_prefix={content[:1000]!r}") from exc- payload_skills = payload.get("skills", [])- if not isinstance(payload_skills, list):+ payload_items = payload.get("resolutions", [])+ if not isinstance(payload_items, list):raise RuntimeError(- "IO name vocabulary prompt batch LLM response must contain skills array."+ "IO name vocabulary prompt batch LLM response must contain "+ "resolutions 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):+ remaining_ids = set(candidates_by_id)+ for item in payload_items:+ if not isinstance(item, dict):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,+ candidate_id = str(item.get("id") or "").strip()+ if candidate_id not in candidates_by_id:+ raise RuntimeError(+ "IO name vocabulary prompt batch LLM response returned "+ f"unknown candidate id: {candidate_id!r}.")-- missing = {- skill_ref: sorted(tokens)- for skill_ref, tokens in remaining_tokens.items()- if tokens- }- if missing:+ if candidate_id not in remaining_ids:+ raise RuntimeError(+ "IO name vocabulary prompt batch LLM response returned "+ f"duplicate candidate id: {candidate_id!r}."+ )+ candidate = candidates_by_id[candidate_id]+ resolution = _resolution_from_payload(item, vocabulary)+ resolutions[candidate.token] = resolution+ with self._cache_lock:+ self._cache[candidate.token] = resolution+ remaining_ids.remove(candidate_id)+ self._emit_progress("done", candidate, resolution)++ if remaining_ids:raise RuntimeError("IO name vocabulary prompt batch LLM response omitted resolutions: "- + json.dumps(missing, ensure_ascii=False, sort_keys=True)+ + json.dumps(sorted(remaining_ids), ensure_ascii=False))return resolutions@@ -173,46 +151,37 @@ class LLMIONameResolver: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,+def _candidate_prompt_payload(+ candidate_id: str,+ candidate: IONameCandidate,+) -> Dict[str, str]:+ return prune_empty({+ "id": candidate_id,"token": candidate.token,- "description": candidate.description,+ "description": candidate.description[:_MAX_CONTEXT_DESCRIPTION_LENGTH],"direction": candidate.direction,"type": candidate.data_type,- }+ })-def _compact_vocabulary_context(vocabulary: IONameVocabulary) -> Dict[str, Any]:+def _compact_vocabulary_context(vocabulary: IONameVocabulary) -> List[Dict[str, Any]]:context = vocabulary.resolver_context()terms = []for item in context.get("terms", []):if not isinstance(item, dict):continue- terms.append(- {+ terms.append(prune_empty({"name": str(item.get("name") or ""),- "definition": str(item.get("definition") or ""),- "aliases": [+ "definition": str(item.get("definition") or "")[+ :_MAX_CONTEXT_DESCRIPTION_LENGTH+ ],+ "aliases": sorted({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,- }+ }),+ }))+ return termsdef _resolution_from_payload(@@ -221,7 +190,7 @@ def _resolution_from_payload() -> IONameResolution:action = str(payload.get("action") or _ACTION_MERGE_EXISTING)if action not in _ALLOWED_ACTIONS:- action = _ACTION_MERGE_EXISTING+ raise RuntimeError(f"Unsupported IO name resolution action: {action!r}.")target = (payload.get("target")@@ -241,7 +210,7 @@ def _resolution_from_payload(action=action,normalized_value=normalized_value,confidence=_coerce_confidence(payload.get("confidence")),- reason=str(payload.get("reason") or ""),+ reason=str(payload.get("reason") or "").strip()[:_MAX_REASON_LENGTH],forced_merge=bool(payload.get("forced_merge")) or action == _ACTION_MERGE_EXISTING,definition=definition,)@@ -255,46 +224,21 @@ def _coerce_confidence(value: Any) -> float: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.+_IO_NAME_PROMPT_BATCH_RESOLVER_PROMPT = (+ "Resolve each candidate Skill I/O name against the supplied canonical vocabulary.\n\n"+ "Return JSON only:\n"+ '{"resolutions":[{"id":"i1","action":"alias_existing|create_new|merge_existing|'+ 'exclude_from_vocab","target":"term","confidence":0.0,"definition":"optional",'+ '"reason":"optional short reason"}]}\n\n'+ """Return exactly one resolution for each candidate id.-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.+- alias_existing: synonymous with an existing term.+- merge_existing: should use the closest existing semantic role.+- create_new: a distinct runtime semantic role.+- exclude_from_vocab: bookkeeping, telemetry or internal-copy data.-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.+Judge semantic role independently of data carrier type. Prefer merging harmless+lexical variants, but preserve directional differences such as source_language+and target_language. Keep reason to one short sentence when needed."""+)diff --git a/jiuwenswarm/symphony/fingerprint/pipeline.py b/jiuwenswarm/symphony/fingerprint/pipeline.pyindex a33fb4b89c..a2bb18f026 100644--- a/jiuwenswarm/symphony/fingerprint/pipeline.py+++ b/jiuwenswarm/symphony/fingerprint/pipeline.py@@ -56,6 +56,8 @@ class FingerprintExtractor:self.progress = progressself.event_log = event_logself.max_workers = max(1, max_workers)+ # Reserved for a future deterministic merge strategy. Normalization LLM+ # batches remain serial because every batch may extend the shared vocabulary.self.normalization_workers = max(1,int(normalization_workers if normalization_workers is not None else max_workers),diff --git a/jiuwenswarm/symphony/graph/matcher/openai.py b/jiuwenswarm/symphony/graph/matcher/openai.pyindex 45aaacf210..8dee072b99 100644--- a/jiuwenswarm/symphony/graph/matcher/openai.py+++ b/jiuwenswarm/symphony/graph/matcher/openai.py@@ -4,18 +4,23 @@ from __future__ import annotationsimport asyncioimport json-from typing import Any, Dict, Iterable, List, Optional, Protocol+from typing import Any, Awaitable, Dict, Iterable, List, Optional, Protocolfrom jiuwenswarm.symphony.graph.matcher.constants import DEFAULT_THRESHOLDSfrom 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.prompt import (+ SYSTEM_PROMPT,+ build_llm_context,+ expand_compact_llm_response,+)from jiuwenswarm.symphony.graph.matcher.validation import validate_llm_matchesfrom 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"}},-}+from jiuwenswarm.symphony.llm import (+ LLMConfig,+ create_llm_client,+ llm_usage_context,+ thinking_disabled_request_overrides,+)class OntologyMatcher(Protocol):@@ -46,7 +51,7 @@ class OpenAICompatibleOntologyMatcher:batch_size: int = 12,max_workers: int = 1,require_consensus: bool = True,- prompt_version: str = "Orchestration-graph-match-v1",+ prompt_version: str = "Orchestration-graph-match-v2",thresholds: Optional[Dict[str, float]] = None,progress: Optional[MatchProgress] = None,) -> None:@@ -93,17 +98,18 @@ class OpenAICompatibleOntologyMatcher:(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)+ request_semaphore = asyncio.Semaphore(self.max_workers)+ results = await _gather_cancel_on_error(+ *(+ self._match_batch(+ registry,+ batch,+ batch_index,+ total_batches,+ request_semaphore=request_semaphore,+ )+ for batch_index, batch in batches+ ))for batch_index, batch_matches, batch_diagnostics in sorted(@@ -155,32 +161,43 @@ class OpenAICompatibleOntologyMatcher:batch: List[RelationCandidate],batch_index: int,total_batches: int,+ *,+ request_semaphore: asyncio.Semaphore,) -> 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,- )++ async def request(+ *,+ reverse_skill_order: bool,+ ) -> tuple[List[LLMMatch], List[GraphDiagnostic]]:+ async with request_semaphore:+ return await self._request_and_validate_batch(+ registry,+ batch,+ reverse_skill_order=reverse_skill_order,+ )+if not self.require_consensus:+ first_matches, first_diagnostics = await request(+ reverse_skill_order=False,+ )return batch_index, first_matches, first_diagnostics- second_matches, second_diagnostics = await self._request_and_validate_batch(- registry,- batch,- reverse_skill_order=True,+ first_result, second_result = await _gather_cancel_on_error(+ request(reverse_skill_order=False),+ request(reverse_skill_order=True),)+ first_matches, first_diagnostics = first_result+ second_matches, second_diagnostics = second_resultagreed_matches, consensus_diagnostics = consensus_matches(first_matches,second_matches,@@ -214,11 +231,11 @@ class OpenAICompatibleOntologyMatcher:user_content=json.dumps(payload,ensure_ascii=False,- indent=2,+ separators=(",", ":"),),timeout=200,error_context="LLM graph matching",- request_overrides=_LOW_REASONING_REQUEST_OVERRIDES,+ request_overrides=thinking_disabled_request_overrides(),)try:raw_payload = json.loads(content)@@ -227,13 +244,17 @@ class OpenAICompatibleOntologyMatcher:"LLM graph matching response is not valid JSON. "f"content_prefix={content[:1000]!r}") from exc- batch_matches, batch_diagnostics = validate_llm_matches(+ expanded_payload, protocol_diagnostics = expand_compact_llm_response(raw_payload,+ batch,+ )+ batch_matches, batch_diagnostics = validate_llm_matches(+ expanded_payload,registry,batch,thresholds=self.thresholds,)- return batch_matches, batch_diagnostics+ return batch_matches, protocol_diagnostics + batch_diagnosticsdef _emit_progress(self,@@ -245,3 +266,14 @@ class OpenAICompatibleOntologyMatcher:if self.progress is None:returnself.progress(event, current, total, details)+++async def _gather_cancel_on_error(*awaitables: Awaitable[Any]) -> List[Any]:+ tasks = [asyncio.ensure_future(awaitable) for awaitable in awaitables]+ try:+ return list(await asyncio.gather(*tasks))+ except BaseException:+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)+ raisediff --git a/jiuwenswarm/symphony/graph/matcher/prompt.py b/jiuwenswarm/symphony/graph/matcher/prompt.pyindex 3e0e06581b..ef973bd3e1 100644--- a/jiuwenswarm/symphony/graph/matcher/prompt.py+++ b/jiuwenswarm/symphony/graph/matcher/prompt.py@@ -1,17 +1,20 @@-"""Prompt and context construction for LLM relation matching."""+"""Compact prompt protocol for LLM relation matching."""from __future__ import annotations-import hashlib-import jsonfrom typing import Any, Dict, Listfrom jiuwenswarm.symphony.fingerprint.models import Fingerprintfrom jiuwenswarm.symphony.graph.models import (- ALLOWED_RELATION_TYPES,+ GraphDiagnostic,RelationCandidate,SkillRegistry,)+from jiuwenswarm.symphony.shared.llm_payload import prune_empty++_MAX_SKILL_DESCRIPTION_LENGTH = 240+_MAX_PORT_DESCRIPTION_LENGTH = 160+_MAX_REASON_LENGTH = 160def build_llm_context(@@ -20,91 +23,249 @@ def build_llm_context(*,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]+ indexed = [+ (f"c{index}", candidate)+ for index, candidate in enumerate(candidates, start=1)+ ]+ if reverse_skill_order:+ indexed.reverse()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(),+ "candidates": [+ _candidate_context(candidate_id, registry, candidate)+ for candidate_id, candidate in indexed+ ]}-def _ordered_skill_ids_for_candidates(+def expand_compact_llm_response(+ payload: Dict[str, Any],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+) -> tuple[Dict[str, Any], List[GraphDiagnostic]]:+ candidates_by_id = {+ f"c{index}": candidate+ for index, candidate in enumerate(candidates, start=1)+ }+ matches = payload.get("matches", [])+ if not isinstance(matches, list):+ return {"matches": matches}, []++ expanded = []+ diagnostics = []+ seen = set()+ for item in matches:+ if not isinstance(item, dict):+ diagnostics.append(_protocol_diagnostic(+ "invalid_match_item",+ "Compact LLM match item must be an object.",+ ))+ continue+ candidate_id = str(item.get("id") or "").strip()+ if candidate_id not in candidates_by_id:+ diagnostics.append(_protocol_diagnostic(+ "unknown_candidate_id",+ f"Compact LLM match returned unknown candidate id: {candidate_id!r}.",+ ))+ continue+ if candidate_id in seen:+ diagnostics.append(_protocol_diagnostic(+ "duplicate_candidate_id",+ f"Compact LLM match repeated candidate id: {candidate_id!r}.",+ ))+ continue+ seen.add(candidate_id)+ candidate = candidates_by_id[candidate_id]+ direction = str(item.get("direction") or "forward").strip().lower()+ if direction not in {"forward", "reverse"}:+ diagnostics.append(_protocol_diagnostic(+ "invalid_candidate_direction",+ f"Compact LLM match returned invalid direction: {direction!r}.",+ ))+ continue+ source_id, target_id = _directed_ids(candidate, direction)+ evidence = _directional_evidence(candidate, source_id, target_id)+ if not evidence:+ diagnostics.append(_protocol_diagnostic(+ "unsupported_candidate_direction",+ f"Candidate {candidate_id!r} has no evidence for {direction}.",+ ))+ continue+ reason = str(item.get("reason") or "").strip()[:_MAX_REASON_LENGTH]+ expanded.append({+ "candidate_id": candidate.key,+ "source_id": source_id,+ "target_id": target_id,+ "relation_type": "can_feed",+ "confidence": item.get("confidence", 0),+ "method": "llm_ontology_match",+ "reasons": [reason] if reason else [],+ "supporting_fields": _supporting_fields(evidence),+ })+ return {"matches": expanded}, diagnostics-def _skill_context(skill: Fingerprint) -> Dict[str, Any]:+def _candidate_context(+ candidate_id: str,+ registry: SkillRegistry,+ candidate: RelationCandidate,+) -> Dict[str, Any]:+ source = registry.skills[candidate.source_id]+ target = registry.skills[candidate.target_id]+ directions = {}+ for direction, source_id, target_id in (+ ("forward", candidate.source_id, candidate.target_id),+ ("reverse", candidate.target_id, candidate.source_id),+ ):+ evidence = _directional_evidence(candidate, source_id, target_id)+ if evidence:+ directions[direction] = _evidence_context(evidence)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],+ "id": candidate_id,+ "source": _skill_context(source),+ "target": _skill_context(target),+ "directions": directions,}-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": ["..."]- }- }- ]-}+def _skill_context(skill: Fingerprint) -> Dict[str, str]:+ return prune_empty({+ "name": skill.name,+ "description": skill.description[:_MAX_SKILL_DESCRIPTION_LENGTH],+ })+++def _evidence_context(evidence: Dict[str, Any]) -> Dict[str, Any]:+ outputs = _compact_fields(evidence.get("source_outputs", []))+ inputs = _compact_fields(evidence.get("target_inputs", []))+ ports = []+ seen = set()+ for mapping in evidence.get("port_mappings", []):+ if not isinstance(mapping, dict):+ continue+ port = prune_empty({+ "output": mapping.get("source_output"),+ "output_type": mapping.get("source_type"),+ "input": mapping.get("target_input"),+ "input_type": mapping.get("target_type"),+ })+ marker = tuple(sorted(port.items()))+ if not port or marker in seen:+ continue+ seen.add(marker)+ ports.append(port)+ return prune_empty({+ "outputs": outputs,+ "inputs": inputs,+ "ports": ports,+ })+++def _compact_fields(values: Any) -> List[Dict[str, Any]]:+ output = []+ seen = set()+ for item in values if isinstance(values, list) else []:+ if not isinstance(item, dict):+ continue+ field = prune_empty({+ "name": item.get("name"),+ "type": item.get("type"),+ "required": item.get("required"),+ "description": str(item.get("description") or "")[+ :_MAX_PORT_DESCRIPTION_LENGTH+ ],+ })+ marker = (+ field.get("name"),+ field.get("type"),+ field.get("required"),+ )+ if marker in seen:+ continue+ seen.add(marker)+ output.append(field)+ return output+++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+ if "directions" in candidate.evidence:+ return {}+ if source_id == candidate.source_id and target_id == candidate.target_id:+ return candidate.evidence+ return {}+++def _directed_ids(+ candidate: RelationCandidate,+ direction: str,+) -> tuple[str, str]:+ if direction == "reverse":+ return candidate.target_id, candidate.source_id+ return candidate.source_id, candidate.target_id+++def _supporting_fields(evidence: Dict[str, Any]) -> Dict[str, Any]:+ pairs = []+ source_outputs = set()+ target_inputs = set()+ for mapping in evidence.get("port_mappings", []):+ if not isinstance(mapping, dict):+ continue+ source_output = str(mapping.get("source_output") or "").strip()+ target_input = str(mapping.get("target_input") or "").strip()+ if not source_output or not target_input:+ continue+ pair = {+ "source_output": source_output,+ "target_input": target_input,+ }+ if pair not in pairs:+ pairs.append(pair)+ source_outputs.add(source_output)+ target_inputs.add(target_input)+ if not pairs:+ source_outputs.update(_field_names(evidence.get("source_outputs", [])))+ target_inputs.update(_field_names(evidence.get("target_inputs", [])))+ return prune_empty({+ "port_mappings": pairs,+ "source_outputs": sorted(source_outputs),+ "target_inputs": sorted(target_inputs),+ })+++def _field_names(values: Any) -> List[str]:+ if not isinstance(values, list):+ return []+ names: List[str] = []+ for item in values:+ if isinstance(item, dict) and item.get("name"):+ names.append(str(item["name"]))+ return names+++def _protocol_diagnostic(code: str, message: str) -> GraphDiagnostic:+ return GraphDiagnostic(+ stage="llm_match",+ severity="warning",+ code=code,+ message=message,+ )+++SYSTEM_PROMPT = """Validate whether each candidate Skill output can feed the target input.++Return JSON only:+{"matches":[{"id":"c1","direction":"forward|reverse","confidence":0.0,"reason":"optional short reason"}]}-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.+Return at most one judgment per candidate id. Use only directions and ports+present in the request. Omit invalid relations or assign low confidence.+Confidence must be between 0 and 1. Keep reason to one short sentence when+useful; do not repeat request data or invent Skills, ports or relations."""diff --git a/jiuwenswarm/symphony/llm.py b/jiuwenswarm/symphony/llm.pyindex ba8ef3a88f..d29534d8b0 100644--- a/jiuwenswarm/symphony/llm.py+++ b/jiuwenswarm/symphony/llm.py@@ -6,12 +6,15 @@ import jsonfrom collections import defaultdictfrom contextlib import contextmanagerfrom contextvars import ContextVar+from copy import deepcopyfrom dataclasses import dataclassfrom threading import Lockfrom typing import Any, Dict, Iterator, List, Optionalfrom json_repair import repair_json+from jiuwenswarm.common.reasoning_injector import inject_reasoning_params+@dataclass(frozen=True)class LLMConfig:@@ -57,8 +60,8 @@ class LLMConfig:client_config = {}if not isinstance(request_config, dict):request_config = {}- client_config = dict(client_config)- request_config = dict(request_config)+ client_config = deepcopy(client_config)+ request_config = deepcopy(request_config)model = str(request_config.get("model")or client_config.get("model_name")@@ -73,6 +76,17 @@ class LLMConfig: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 = inject_reasoning_params(+ model_client_config=client_config,+ model_config_obj=request_config,+ )+ request_config.pop("reasoning_effort", None)+ extra_body = request_config.get("extra_body")+ if not isinstance(extra_body, dict):+ extra_body = {}+ extra_body = deepcopy(extra_body)+ extra_body.update(thinking_disabled_request_overrides()["extra_body"])+ request_config["extra_body"] = extra_bodyrequest_config["model"] = modelreturn cls(model=model,@@ -90,13 +104,13 @@ class LLMConfig: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 {})+ client_config = deepcopy(self.model_client_config or {})if self.base_url:client_config["api_base"] = self.base_urlreturn client_configdef model_request_kwargs(self) -> Dict[str, Any]:- request_config = dict(self.model_config_obj or {})+ request_config = deepcopy(self.model_config_obj or {})request_config["model"] = self.modelrequest_config["temperature"] = self.temperaturerequest_config["top_p"] = self.top_p@@ -218,6 +232,17 @@ def create_llm_client(config: LLMConfig) -> "JiuwenSwarmChatClient":return JiuwenSwarmChatClient(config)+def thinking_disabled_request_overrides() -> Dict[str, Any]:+ """Return isolated provider-compatible controls that disable thinking."""+ return {+ "extra_body": {+ "thinking": {"type": "disabled"},+ "enable_thinking": False,+ "chat_template_kwargs": {"enable_thinking": False},+ }+ }++class JiuwenSwarmChatClient:"""Adapter over openjiuwen's async model invocation."""diff --git a/jiuwenswarm/symphony/shared/llm_payload.py b/jiuwenswarm/symphony/shared/llm_payload.pynew file mode 100644index 0000000000..da35b7c306--- /dev/null+++ b/jiuwenswarm/symphony/shared/llm_payload.py@@ -0,0 +1,32 @@+"""Shared helpers for compact LLM request payloads."""++from __future__ import annotations++import json+from typing import Any+++def compact_json(payload: Any) -> str:+ return json.dumps(+ prune_empty(payload),+ ensure_ascii=False,+ separators=(",", ":"),+ )+++def prune_empty(value: Any) -> Any:+ if isinstance(value, dict):+ cleaned_items = {}+ for key, item in value.items():+ cleaned = prune_empty(item)+ if cleaned not in (None, "", [], {}):+ cleaned_items[key] = cleaned+ return cleaned_items+ if isinstance(value, list):+ cleaned_items = []+ for item in value:+ cleaned = prune_empty(item)+ if cleaned not in (None, "", [], {}):+ cleaned_items.append(cleaned)+ return cleaned_items+ return valuediff --git a/tests/unit_tests/symphony/test_graph_service.py b/tests/unit_tests/symphony/test_graph_service.pyindex ce7ad1a0f6..c8cc114909 100644--- a/tests/unit_tests/symphony/test_graph_service.py+++ b/tests/unit_tests/symphony/test_graph_service.py@@ -246,19 +246,14 @@ class _CaptureJSONClient:self.calls.append(kwargs)return """{- "skills": [+ "resolutions": [{- "skill_ref": "0:text",- "resolutions": [- {- "token": "text",- "action": "alias_existing",- "target": "content",- "confidence": 0.9,- "reason": "same content role",- "definition": "Text content alias"- }- ]+ "id": "i1",+ "action": "alias_existing",+ "target": "content",+ "confidence": 0.9,+ "reason": "same content role",+ "definition": "Text content alias"}]}@@ -277,7 +272,7 @@ class _CaptureSchemaClient:{"schemas": [{- "skill_ref": item["source"]["relative_path"],+ "skill_ref": item["skill_ref"],"description": "Schema","inputs": [{"name": "input", "type": "text"}],"outputs": [{"name": "result", "type": "text"}],@@ -324,23 +319,10 @@ class _CaptureMatchClient:{"matches": [{- "candidate_id": "source->target",- "source_id": "source",- "target_id": "target",- "relation_type": "can_feed",+ "id": "c1",+ "direction": "forward","confidence": 0.95,- "method": "llm_ontology_match",- "reasons": ["result satisfies input"],- "supporting_fields": {- "port_mappings": [- {- "source_output": "result",- "target_input": "input",- }- ],- "source_outputs": ["result"],- "target_inputs": ["input"],- },+ "reason": "result satisfies input",}]}@@ -424,12 +406,16 @@ def _raw_manifest(tmp_path, folder_name):def _expected_thinking_disabled_overrides():return {- "extra_body": {"thinking": {"type": "disabled"}},+ "extra_body": {+ "thinking": {"type": "disabled"},+ "enable_thinking": False,+ "chat_template_kwargs": {"enable_thinking": False},+ },}@pytest.mark.asyncio-async def test_schema_extractor_uses_low_reasoning_for_single_extract(monkeypatch, tmp_path):+async def test_schema_extractor_disables_thinking_for_single_extract(monkeypatch, tmp_path):client = _CaptureSchemaClient()monkeypatch.setattr("jiuwenswarm.symphony.fingerprint.extract.extractor.create_llm_client",@@ -450,11 +436,11 @@ async def test_schema_extractor_uses_low_reasoning_for_single_extract(monkeypatcassert result.outputs[0].name == "result"assert client.calls[0]["request_overrides"] == _expected_thinking_disabled_overrides()- assert "reasoning text" in client.calls[0]["system_prompt"]+ assert "Return JSON only" in client.calls[0]["system_prompt"]@pytest.mark.asyncio-async def test_schema_extractor_uses_low_reasoning_for_many_paths(monkeypatch, tmp_path):+async def test_schema_extractor_disables_thinking_for_many_paths(monkeypatch, tmp_path):client = _CaptureSchemaClient()monkeypatch.setattr("jiuwenswarm.symphony.fingerprint.extract.extractor.create_llm_client",@@ -483,11 +469,11 @@ async def test_schema_extractor_uses_low_reasoning_for_many_paths(monkeypatch, tassert client.calls[0]["request_overrides"] == _expected_thinking_disabled_overrides()assert client.calls[1]["method"] == "one"assert client.calls[1]["request_overrides"] == _expected_thinking_disabled_overrides()- assert "reasoning text" in client.calls[1]["system_prompt"]+ assert "Return JSON only" in client.calls[1]["system_prompt"]@pytest.mark.asyncio-async def test_graph_matcher_uses_low_reasoning_for_forward_and_reverse(monkeypatch):+async def test_graph_matcher_disables_thinking_for_forward_and_reverse(monkeypatch):client = _CaptureMatchClient()monkeypatch.setattr("jiuwenswarm.symphony.graph.matcher.openai.create_llm_client",@@ -560,7 +546,7 @@ async def test_graph_matcher_uses_low_reasoning_for_forward_and_reverse(monkeypa_expected_thinking_disabled_overrides(),_expected_thinking_disabled_overrides(),]- assert all("reasoning text" in call["system_prompt"] for call in client.calls)+ assert all("Return JSON only" in call["system_prompt"] for call in client.calls)@pytest.mark.asyncio@@ -1593,7 +1579,7 @@ async def test_normalizer_can_exclude_candidate_from_io_name_vocab(tmp_path):@pytest.mark.asyncio-async def test_llm_io_name_resolver_uses_low_reasoning_and_compact_vocab(monkeypatch):+async def test_llm_io_name_resolver_disables_thinking_and_uses_compact_vocab(monkeypatch):client = _CaptureJSONClient()monkeypatch.setattr("jiuwenswarm.symphony.fingerprint.normalize.io_name_resolver.create_llm_client",@@ -1638,20 +1624,18 @@ async def test_llm_io_name_resolver_uses_low_reasoning_and_compact_vocab(monkeypassert result["text"].normalized_value == "content"call = client.calls[0]- assert call["request_overrides"] == {- "extra_body": {"thinking": {"type": "disabled"}},- }+ assert call["request_overrides"] == _expected_thinking_disabled_overrides()payload = json.loads(call["user_content"])assert "rules" not in payload- assert payload["vocabulary"]["terms"] == [+ assert payload["vocabulary"] == [{"name": "content","definition": "Generated written content","aliases": ["body"],}]- assert "examples" not in payload["vocabulary"]["terms"][0]- assert "count" not in payload["vocabulary"]["terms"][0]+ assert "examples" not in payload["vocabulary"][0]+ assert "count" not in payload["vocabulary"][0]@pytest.mark.asynciodiff --git a/tests/unit_tests/symphony/test_llm.py b/tests/unit_tests/symphony/test_llm.pyindex 96be623493..a8a4ebbc29 100644--- a/tests/unit_tests/symphony/test_llm.py+++ b/tests/unit_tests/symphony/test_llm.py@@ -1,3 +1,4 @@+from copy import deepcopyfrom types import SimpleNamespaceimport pytest@@ -8,6 +9,7 @@ from jiuwenswarm.symphony.llm import (extract_message_content,get_llm_token_usage_summary,reset_llm_token_usage,+ thinking_disabled_request_overrides,_record_usage_from_response,)@@ -21,6 +23,48 @@ class _FakeInvokeModel:return SimpleNamespace(content='{"ok": true}')+def _model_entry(*, reasoning_level=None, client=None, request=None):+ client_config = {+ "api_key": "key",+ "api_base": "https://example.test/v1",+ "model_name": "model-a",+ "client_provider": "openai",+ **(client or {}),+ }+ request_config = dict(request or {})+ if reasoning_level is not None:+ request_config["reasoning_level"] = reasoning_level+ return {+ "model_client_config": client_config,+ "model_config_obj": request_config,+ }+++def _llm_config():+ return LLMConfig(+ model="model-a",+ model_client_config=_model_entry()["model_client_config"],+ )+++def test_thinking_disabled_request_overrides_returns_isolated_compatibility_fields():+ first = thinking_disabled_request_overrides()+ second = thinking_disabled_request_overrides()++ assert first == {+ "extra_body": {+ "thinking": {"type": "disabled"},+ "enable_thinking": False,+ "chat_template_kwargs": {"enable_thinking": False},+ }+ }+ first["extra_body"]["thinking"]["type"] = "enabled"+ first["extra_body"]["chat_template_kwargs"]["enable_thinking"] = True++ assert second["extra_body"]["thinking"]["type"] == "disabled"+ assert second["extra_body"]["chat_template_kwargs"]["enable_thinking"] is False++def test_extract_message_content_supports_openjiuwen_response_shape():response = SimpleNamespace(content=[{"text": "{\"ok\": true}"}])@@ -78,6 +122,70 @@ def test_llm_config_from_default_models(monkeypatch):assert config.model_request_kwargs()["max_tokens"] == 99+def test_llm_config_removes_internal_reasoning_level():+ config = LLMConfig.from_model_entry(+ _model_entry(reasoning_level="off", request={"max_tokens": 99})+ )++ request_kwargs = config.model_request_kwargs()++ assert "reasoning_level" not in request_kwargs+ assert request_kwargs["max_tokens"] == 99+ assert request_kwargs["extra_body"] == thinking_disabled_request_overrides()["extra_body"]+++def test_llm_config_forces_high_reasoning_config_to_disabled():+ config = LLMConfig.from_model_entry(+ _model_entry(+ reasoning_level="high",+ client={+ "api_base": "https://api.deepseek.com",+ "model_name": "deepseek-v4-pro",+ },+ request={+ "max_tokens": 99,+ "extra_body": {"custom_option": {"enabled": True}},+ },+ )+ )++ request_kwargs = config.model_request_kwargs()++ assert "reasoning_level" not in request_kwargs+ assert "reasoning_effort" not in request_kwargs+ assert request_kwargs["max_tokens"] == 99+ assert request_kwargs["extra_body"] == {+ "custom_option": {"enabled": True},+ **thinking_disabled_request_overrides()["extra_body"],+ }+++def test_llm_config_owns_nested_model_entry_data():+ entry = _model_entry(+ reasoning_level="off",+ client={+ "custom_headers": {"X-Test": "original"},+ },+ request={+ "response_format": {"type": "json_object"},+ "extra_body": {"custom_option": {"enabled": True}},+ },+ )+ original = deepcopy(entry)++ config = LLMConfig.from_model_entry(entry)+ client_kwargs = config.model_client_kwargs()+ request_kwargs = config.model_request_kwargs()+ client_kwargs["custom_headers"]["X-Test"] = "changed"+ request_kwargs["response_format"]["type"] = "text"+ request_kwargs["extra_body"]["custom_option"]["enabled"] = False++ assert entry == original+ assert config.model_client_kwargs()["custom_headers"] == {"X-Test": "original"}+ assert config.model_request_kwargs()["response_format"] == {"type": "json_object"}+ assert config.model_request_kwargs()["extra_body"]["custom_option"] == {"enabled": True}++def test_llm_config_prefers_resolved_default_model(monkeypatch):model_config = {"models": {@@ -131,32 +239,14 @@ def test_llm_config_does_not_fallback_to_environment_model(monkeypatch):def test_create_llm_client_uses_jiuwenswarm_client():- client = create_llm_client(- LLMConfig(- model="model-a",- model_client_config={- "api_key": "key",- "api_base": "https://example.test/v1",- "client_provider": "openai",- },- )- )+ client = create_llm_client(_llm_config())assert type(client).__name__ == "JiuwenSwarmChatClient"@pytest.mark.asyncioasync def test_complete_json_async_passes_request_overrides_to_invoke():- client = create_llm_client(- LLMConfig(- model="model-a",- model_client_config={- "api_key": "key",- "api_base": "https://example.test/v1",- "client_provider": "openai",- },- )- )+ client = create_llm_client(_llm_config())fake_model = _FakeInvokeModel()setattr(client, "_model", fake_model)@@ -177,16 +267,7 @@ async def test_complete_json_async_passes_request_overrides_to_invoke():@pytest.mark.asyncioasync def test_complete_json_async_omits_request_overrides_by_default():- client = create_llm_client(- LLMConfig(- model="model-a",- model_client_config={- "api_key": "key",- "api_base": "https://example.test/v1",- "client_provider": "openai",- },- )- )+ client = create_llm_client(_llm_config())fake_model = _FakeInvokeModel()setattr(client, "_model", fake_model)@@ -198,16 +279,7 @@ async def test_complete_json_async_omits_request_overrides_by_default():@pytest.mark.asyncioasync def test_complete_json_many_async_passes_request_overrides_to_each_invoke():- client = create_llm_client(- LLMConfig(- model="model-a",- model_client_config={- "api_key": "key",- "api_base": "https://example.test/v1",- "client_provider": "openai",- },- )- )+ client = create_llm_client(_llm_config())fake_model = _FakeInvokeModel()setattr(client, "_model", fake_model)@@ -234,16 +306,7 @@ async def test_complete_json_many_async_passes_request_overrides_to_each_invoke(@pytest.mark.asyncioasync def test_complete_json_many_async_omits_request_overrides_by_default():- client = create_llm_client(- LLMConfig(- model="model-a",- model_client_config={- "api_key": "key",- "api_base": "https://example.test/v1",- "client_provider": "openai",- },- )- )+ client = create_llm_client(_llm_config())fake_model = _FakeInvokeModel()setattr(client, "_model", fake_model)diff --git a/tests/unit_tests/symphony/test_llm_concurrency.py b/tests/unit_tests/symphony/test_llm_concurrency.pynew file mode 100644index 0000000000..420d0e6108--- /dev/null+++ b/tests/unit_tests/symphony/test_llm_concurrency.py@@ -0,0 +1,291 @@+import asyncio+import json++import pytest++from jiuwenswarm.symphony.fingerprint.batching import gather_limited+from jiuwenswarm.symphony.fingerprint.models import (+ ArtifactSpec,+ ExtractedSkillSchema,+ Fingerprint,+ ParameterSpec,+ RawSkillManifest,+ SkillFolder,+)+from jiuwenswarm.symphony.fingerprint.normalize import (+ IONameResolution,+ SkillFingerprintNormalizer,+)+from jiuwenswarm.symphony.fingerprint.pipeline import FingerprintExtractor+from jiuwenswarm.symphony.graph import (+ OpenAICompatibleOntologyMatcher,+ RelationCandidate,+ SkillRegistry,+)+from jiuwenswarm.symphony.llm import LLMConfig+++class _DelayedMatchClient:+ def __init__(self, delay=0.02):+ self.delay = delay+ self.active = 0+ self.max_active = 0+ self.call_count = 0++ async def complete_json_async(self, **kwargs):+ del kwargs+ self.call_count += 1+ self.active += 1+ self.max_active = max(self.max_active, self.active)+ try:+ await asyncio.sleep(self.delay)+ finally:+ self.active -= 1+ return json.dumps(+ {+ "matches": [+ {+ "id": "c1",+ "direction": "forward",+ "confidence": 0.95,+ }+ ]+ }+ )+++class _FailingMatchClient:+ def __init__(self):+ self.call_count = 0+ self.cancelled_count = 0++ async def complete_json_async(self, **kwargs):+ del kwargs+ self.call_count += 1+ if self.call_count == 1:+ await asyncio.sleep(0)+ raise RuntimeError("forward failed")+ try:+ await asyncio.sleep(10)+ except asyncio.CancelledError:+ self.cancelled_count += 1+ raise+ return '{"matches":[]}'+++class _VocabularyObservingResolver:+ batch_size = 1++ def __init__(self):+ self.vocabulary_snapshots = []++ async def resolve_async(self, candidates_by_skill, vocabulary):+ self.vocabulary_snapshots.append(vocabulary.term_names())+ return {+ candidate.token: IONameResolution(+ action="create_new",+ normalized_value=candidate.token,+ confidence=0.9,+ )+ for candidates in candidates_by_skill+ for candidate in candidates+ }+++def _llm_config():+ return LLMConfig(+ model="model-a",+ model_client_config={+ "api_key": "key",+ "api_base": "https://example.test/v1",+ "client_provider": "openai",+ },+ )+++def _fingerprint(skill_id, *, consumes):+ return Fingerprint(+ type="skill",+ id=skill_id,+ name=skill_id,+ description="Consumes input" if consumes else "Produces result",+ version="1.0.0",+ inputs=[ParameterSpec(name="input", type="text")] if consumes else [],+ outputs=[] if consumes else [ArtifactSpec(name="result", type="text")],+ )+++def _registry_and_candidates(count):+ skills = {}+ candidates = []+ for index in range(count):+ source_id = f"source-{index}"+ target_id = f"target-{index}"+ skills[source_id] = _fingerprint(source_id, consumes=False)+ skills[target_id] = _fingerprint(target_id, consumes=True)+ candidates.append(+ RelationCandidate(+ source_id=source_id,+ target_id=target_id,+ relation_hints=["can_feed"],+ candidate_methods=["test"],+ priority="high",+ evidence={+ "directions": {+ f"{source_id}->{target_id}": {+ "port_mappings": [+ {+ "source_output": "result",+ "target_input": "input",+ }+ ],+ "source_outputs": [{"name": "result"}],+ "target_inputs": [{"name": "input"}],+ }+ }+ },+ )+ )+ return SkillRegistry(skills=skills), candidates+++def _matcher(monkeypatch, client, *, workers):+ monkeypatch.setattr(+ "jiuwenswarm.symphony.graph.matcher.openai.create_llm_client",+ lambda config: client,+ )+ return OpenAICompatibleOntologyMatcher(+ _llm_config(),+ batch_size=1,+ max_workers=workers,+ require_consensus=True,+ )+++ ("workers", "candidate_count", "expected_max_active"),+ [(1, 1, 1), (2, 1, 2), (3, 3, 3)],+)+async def test_graph_consensus_respects_request_worker_limit(+ monkeypatch,+ workers,+ candidate_count,+ expected_max_active,+):+ client = _DelayedMatchClient(delay=0.01)+ matcher = _matcher(monkeypatch, client, workers=workers)+ registry, candidates = _registry_and_candidates(candidate_count)++ await matcher.match(registry, candidates)++ assert client.call_count == candidate_count * 2+ assert client.max_active == expected_max_active+++ ("candidate_count", "workers", "expected_calls", "expected_cancelled"),+ [(1, 2, 2, 1), (2, 4, 4, 3)],+)+async def test_graph_failure_cancels_remaining_requests(+ monkeypatch,+ candidate_count,+ workers,+ expected_calls,+ expected_cancelled,+):+ client = _FailingMatchClient()+ matcher = _matcher(monkeypatch, client, workers=workers)+ registry, candidates = _registry_and_candidates(candidate_count)++ with pytest.raises(RuntimeError, match="forward failed"):+ await matcher.match(registry, candidates)++ assert client.call_count == expected_calls+ assert client.cancelled_count == expected_cancelled+++async def test_extraction_batches_preserve_order_and_worker_limit():+ active = 0+ max_active = 0++ async def run_batch(batch):+ nonlocal active, max_active+ active += 1+ max_active = max(max_active, active)+ try:+ await asyncio.sleep(0.01 * (4 - batch[0]))+ return batch[0]+ finally:+ active -= 1++ results = await gather_limited(+ [[1], [2], [3]],+ max_workers=2,+ run_batch=run_batch,+ )++ assert results == [1, 2, 3]+ assert max_active == 2+++async def test_extraction_batch_failure_is_propagated():+ async def run_batch(batch):+ if batch == [2]:+ raise RuntimeError("extract failed")+ await asyncio.sleep(0)+ return batch[0]++ with pytest.raises(RuntimeError, match="extract failed"):+ await gather_limited(+ [[1], [2], [3]],+ max_workers=2,+ run_batch=run_batch,+ )+++async def test_normalization_batches_commit_vocabulary_in_order(tmp_path):+ resolver = _VocabularyObservingResolver()+ normalizer = SkillFingerprintNormalizer(io_name_resolver=resolver)+ extractor = FingerprintExtractor(+ schema_extractor=object(),+ normalizer=normalizer,+ normalization_workers=4,+ normalization_batch_size=1,+ )+ manifests = {}+ schemas = {}+ indexed_folders = []+ for index, input_name in enumerate(("first_value", "second_value")):+ folder = SkillFolder(+ id_hint=f"skill-{index}",+ path=tmp_path / f"skill-{index}",+ entry=tmp_path / f"skill-{index}" / "SKILL.md",+ relative_path=f"skill-{index}",+ )+ manifests[index] = RawSkillManifest(+ folder=folder,+ frontmatter={"name": f"skill-{index}"},+ body="Test.",+ body_sha256=f"sha-{index}",+ )+ schemas[index] = ExtractedSkillSchema(+ description="Test schema",+ inputs=[ParameterSpec(name=input_name, type="text")],+ outputs=[],+ )+ indexed_folders.append((index, folder))++ results = await extractor._normalize_schemas(+ indexed_folders,+ len(indexed_folders),+ manifests,+ schemas,+ )++ assert list(results) == [0, 1]+ assert resolver.vocabulary_snapshots == [[], ["first_value"]]diff --git a/tests/unit_tests/symphony/test_llm_payload_compaction.py b/tests/unit_tests/symphony/test_llm_payload_compaction.pynew file mode 100644index 0000000000..e6055d3487--- /dev/null+++ b/tests/unit_tests/symphony/test_llm_payload_compaction.py@@ -0,0 +1,420 @@+import json+from pathlib import Path++import pytest++from jiuwenswarm.symphony.fingerprint.extract.extractor import (+ _SCHEMA_EXTRACTION_PROMPT,+ _build_llm_context,+ schema_from_llm_payload,+)+from jiuwenswarm.symphony.fingerprint.models import (+ ArtifactSpec,+ Fingerprint,+ ParameterSpec,+ RawSkillManifest,+ SkillFolder,+)+from jiuwenswarm.symphony.fingerprint.normalize import (+ IONameCandidate,+ IONameVocabTerm,+ IONameVocabulary,+ LLMIONameResolver,+)+from jiuwenswarm.symphony.fingerprint.normalize.io_name_resolver import (+ _resolution_from_payload,+)+from jiuwenswarm.symphony.llm import LLMConfig+from jiuwenswarm.symphony import build as build_module+from jiuwenswarm.symphony.config import symphony_config_from_dict+from jiuwenswarm.symphony.graph.matcher.openai import (+ OpenAICompatibleOntologyMatcher,+)+from jiuwenswarm.symphony.graph.matcher import prompt as graph_prompt+from jiuwenswarm.symphony.graph.models import RelationCandidate, SkillRegistry+++def _manifest(+ body: str,+ *,+ frontmatter: dict | None = None,+ relative_path: str = "example",+) -> RawSkillManifest:+ return RawSkillManifest(+ folder=SkillFolder(+ id_hint="example",+ path=Path("skills/example"),+ entry=Path("skills/example/SKILL.md"),+ relative_path=relative_path,+ ),+ frontmatter=frontmatter or {},+ body=body,+ body_sha256="digest",+ )+++def test_schema_prompt_is_at_least_45_percent_shorter():+ assert len(_SCHEMA_EXTRACTION_PROMPT) <= 2498+++def test_schema_context_preserves_non_empty_frontmatter_without_source_metadata():+ context = _build_llm_context(+ _manifest(+ "Full body.",+ frontmatter={+ "name": "example",+ "description": "Example skill.",+ "metadata": {"owner": "team", "empty": ""},+ "license": None,+ "tags": [],+ },+ )+ )++ assert context == {+ "frontmatter": {+ "name": "example",+ "description": "Example skill.",+ "metadata": {"owner": "team"},+ },+ "body": "Full body.",+ }+++def test_schema_context_uses_short_ref_only_for_batch_correlation():+ context = _build_llm_context(+ _manifest("Full body.", relative_path="long/path/to/example"),+ skill_ref="s1",+ )++ assert context == {"skill_ref": "s1", "body": "Full body."}+++def test_schema_context_only_marks_actual_truncation():+ full = _build_llm_context(_manifest("short"), body_limit=20)+ truncated = _build_llm_context(_manifest("long body"), body_limit=4)++ assert "body_truncated" not in full+ assert truncated == {"body": "long", "body_truncated": True}+++def test_schema_warnings_are_limited_and_truncated():+ schema = schema_from_llm_payload(+ {+ "warnings": ["a" * 200, "second", "", "fourth"],+ "raw_output_notes": ["third", "ignored"],+ }+ )++ assert schema.warnings == ["a" * 160, "second", "fourth"]+++def test_compact_schema_context_is_smaller_than_pretty_json():+ context = _build_llm_context(_manifest("body", frontmatter={"name": "example"}))+ compact = json.dumps(context, ensure_ascii=False, separators=(",", ":"))+ pretty = json.dumps(context, ensure_ascii=False, indent=2)++ assert len(compact) < len(pretty)+++class _IOCaptureClient:+ def __init__(self) -> None:+ self.call = None++ async def complete_json_async(self, **kwargs):+ self.call = kwargs+ return json.dumps(+ {+ "resolutions": [+ {+ "id": "i1",+ "action": "alias_existing",+ "target": "content",+ "confidence": 0.9,+ }+ ]+ }+ )+++async def test_io_resolution_uses_compact_ids_and_full_clean_vocabulary():+ resolver = LLMIONameResolver(LLMConfig(model="test"))+ client = _IOCaptureClient()+ resolver.client = client+ vocabulary = IONameVocabulary(+ version="v1",+ max_vocab_size=20,+ terms=[+ IONameVocabTerm(+ name="content",+ definition="Content value." + ("x" * 200),+ aliases={"body", "body", ""},+ )+ ],+ )+ candidate = IONameCandidate(+ raw_value="input_text",+ token="input_text",+ description="Text supplied by the caller.",+ skill_id="long-skill-id",+ direction="input",+ data_type="text",+ )++ result = await resolver.resolve_async([[candidate]], vocabulary)++ payload = json.loads(client.call["user_content"])+ assert payload == {+ "candidates": [+ {+ "id": "i1",+ "token": "input_text",+ "description": "Text supplied by the caller.",+ "direction": "input",+ "type": "text",+ }+ ],+ "vocabulary": [+ {+ "name": "content",+ "definition": ("Content value." + ("x" * 200))[:160],+ "aliases": ["body"],+ }+ ],+ }+ assert result["input_text"].normalized_value == "content"+ assert "\n" not in client.call["user_content"]+++def test_io_resolution_reason_is_optional_and_truncated():+ vocabulary = IONameVocabulary(version="v1", max_vocab_size=20, terms=[])++ missing = _resolution_from_payload(+ {"action": "create_new", "target": "report", "confidence": 0.8},+ vocabulary,+ )+ long = _resolution_from_payload(+ {+ "action": "create_new",+ "target": "report",+ "confidence": 0.8,+ "reason": "r" * 200,+ },+ vocabulary,+ )++ assert missing.reason == ""+ assert long.reason == "r" * 160+++def _graph_fixture():+ source_output = ArtifactSpec(+ name="report",+ type="markdown",+ description="Generated report." + ("o" * 200),+ )+ target_input = ParameterSpec(+ name="document",+ type="markdown",+ description="Document to review." + ("i" * 200),+ )+ source = Fingerprint(+ type="skill",+ id="source-with-a-long-id",+ name="Source",+ description="Produces a report." + ("s" * 300),+ version="1",+ inputs=[],+ outputs=[source_output],+ )+ target = Fingerprint(+ type="skill",+ id="target-with-a-long-id",+ name="Target",+ description="Reviews a report." + ("t" * 300),+ version="1",+ inputs=[target_input],+ outputs=[],+ )+ mapping = {+ "source_output": "report",+ "source_type": "markdown",+ "target_input": "document",+ "target_type": "markdown",+ "match_method": "semantic_overlap_match",+ "match_reason": "descriptions overlap",+ }+ candidate = RelationCandidate(+ source_id=source.id,+ target_id=target.id,+ relation_hints=["can_feed"],+ candidate_methods=["semantic_overlap_match"],+ priority="medium",+ evidence={+ "directions": {+ f"{source.id}->{target.id}": {+ "source_outputs": [source_output.to_dict()],+ "target_inputs": [target_input.to_dict()],+ "port_mappings": [mapping],+ "matched_terms": ["report"],+ }+ }+ },+ )+ return SkillRegistry(skills={source.id: source, target.id: target}), candidate+++def test_graph_context_only_contains_compact_candidate_evidence():+ registry, candidate = _graph_fixture()++ context = graph_prompt.build_llm_context(registry, [candidate])++ assert set(context) == {"candidates"}+ item = context["candidates"][0]+ assert item["id"] == "c1"+ assert item["source"] == {+ "name": "Source",+ "description": registry.skills[candidate.source_id].description[:240],+ }+ assert item["target"] == {+ "name": "Target",+ "description": registry.skills[candidate.target_id].description[:240],+ }+ forward = item["directions"]["forward"]+ assert forward["outputs"] == [{+ "name": "report",+ "type": "markdown",+ "description": registry.skills[candidate.source_id].outputs[0].description[:160],+ }]+ assert forward["inputs"] == [{+ "name": "document",+ "type": "markdown",+ "required": True,+ "description": registry.skills[candidate.target_id].inputs[0].description[:160],+ }]+ assert forward["ports"] == [{+ "output": "report",+ "output_type": "markdown",+ "input": "document",+ "input_type": "markdown",+ }]+ assert not {+ "input_sha256",+ "allowed_relation_types",+ "priority",+ "candidate_methods",+ } & set(item)+++def test_graph_compact_response_is_expanded_from_candidate_evidence():+ registry, candidate = _graph_fixture()+ expand = getattr(graph_prompt, "expand_compact_llm_response", None)++ assert callable(expand)+ payload, diagnostics = expand(+ {+ "matches": [+ {+ "id": "c1",+ "direction": "forward",+ "confidence": 0.92,+ "reason": "r" * 200,+ }+ ]+ },+ [candidate],+ )++ assert diagnostics == []+ match = payload["matches"][0]+ assert match == {+ "candidate_id": candidate.key,+ "source_id": candidate.source_id,+ "target_id": candidate.target_id,+ "relation_type": "can_feed",+ "confidence": 0.92,+ "method": "llm_ontology_match",+ "reasons": ["r" * 160],+ "supporting_fields": {+ "port_mappings": [{"source_output": "report", "target_input": "document"}],+ "source_outputs": ["report"],+ "target_inputs": ["document"],+ },+ }+++def test_graph_compact_response_reports_unknown_and_duplicate_ids():+ _, candidate = _graph_fixture()+ expand = getattr(graph_prompt, "expand_compact_llm_response", None)++ assert callable(expand)+ payload, diagnostics = expand(+ {+ "matches": [+ {"id": "unknown", "direction": "forward", "confidence": 0.8},+ {"id": "c1", "direction": "forward", "confidence": 0.8},+ {"id": "c1", "direction": "forward", "confidence": 0.9},+ ]+ },+ [candidate],+ )++ assert len(payload["matches"]) == 1+ assert [item.code for item in diagnostics] == [+ "unknown_candidate_id",+ "duplicate_candidate_id",+ ]+++def test_graph_context_supports_legacy_direct_candidate_evidence_shape():+ registry, candidate = _graph_fixture()+ direct_candidate = 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"][candidate.key],+ )++ context = graph_prompt.build_llm_context(registry, [direct_candidate])++ assert "forward" in context["candidates"][0]["directions"]+++def test_graph_context_is_at_least_50_percent_smaller_than_previous_shape():+ registry, candidate = _graph_fixture()+ compact = graph_prompt.build_llm_context(registry, [candidate])+ previous = {+ "allowed_relation_types": ["can_feed"],+ "skills": [+ registry.skills[candidate.source_id].graph_identity_dict(),+ registry.skills[candidate.target_id].graph_identity_dict(),+ ],+ "candidates": [candidate.to_dict()],+ "input_sha256": "x" * 64,+ }++ compact_size = len(json.dumps(compact, ensure_ascii=False, separators=(",", ":")))+ previous_size = len(json.dumps(previous, ensure_ascii=False, separators=(",", ":")))++ assert compact_size <= previous_size * 0.5+++def test_prompt_protocol_versions_invalidate_fingerprint_and_relation_caches(+ monkeypatch,+):+ config = symphony_config_from_dict({})+ llm_config = LLMConfig(model="test")+ first = build_module._fingerprint_signature(config, llm_config)+ monkeypatch.setattr(+ build_module,+ "SCHEMA_EXTRACTION_PROTOCOL_VERSION",+ "symphony-schema-extraction-v3",+ )+ second = build_module._fingerprint_signature(config, llm_config)+ matcher = OpenAICompatibleOntologyMatcher(llm_config)++ assert first != second+ assert matcher.prompt_version == "Orchestration-graph-match-v2"