coding-language-library 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mcp/server.py ADDED
@@ -0,0 +1,219 @@
1
+ #!/usr/bin/env python3
2
+ """Read-only MCP access to the source-linked language catalogue."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import shutil
8
+ import sys
9
+ from collections import Counter
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ if __package__:
14
+ from .task_matching import compare_candidates, get_suitability_evidence, recommend_stack
15
+ else:
16
+ from task_matching import compare_candidates, get_suitability_evidence, recommend_stack
17
+
18
+ HERE = Path(__file__).resolve().parent
19
+ DATA = next((candidate for candidate in (HERE.parent / "data", HERE / "data")
20
+ if (candidate / "inventory.json").is_file()), HERE / "data")
21
+ PROTOCOL = "2024-11-05"
22
+
23
+
24
+ def load_inventory() -> dict[str, Any]:
25
+ return json.loads((DATA / "inventory.json").read_text(encoding="utf-8"))
26
+
27
+
28
+ def load_adapters() -> dict[str, Any]:
29
+ return json.loads((DATA / "adapters.json").read_text(encoding="utf-8"))
30
+
31
+
32
+ def load_suitability_profiles() -> dict[str, Any]:
33
+ return json.loads((DATA / "suitability_profiles.json").read_text(encoding="utf-8"))
34
+
35
+
36
+ def norm(value: str) -> str:
37
+ return "".join(ch for ch in value.casefold() if ch.isalnum() or ch in "+#")
38
+
39
+
40
+ def identifiers(row: dict[str, Any]) -> list[str]:
41
+ values = [row["id"], row["name"], *row.get("aliases", [])]
42
+ for source, details in row.get("sources", {}).items():
43
+ values.append(str(details.get("id", "")))
44
+ if source == "github_linguist" and details.get("language_id") is not None:
45
+ values.append(str(details["language_id"]))
46
+ values.extend(details.get("aliases", []))
47
+ return [str(value) for value in values if value]
48
+
49
+
50
+ def get_language(query: str) -> dict[str, Any]:
51
+ key = norm(query)
52
+ exact = [row for row in load_inventory()["languages"]
53
+ if query == row["id"] or any(norm(value) == key for value in identifiers(row))]
54
+ if not exact:
55
+ raise ValueError(f"'{query}' is not in the source-linked inventory")
56
+ if len(exact) > 1:
57
+ raise ValueError(f"'{query}' matches multiple records: {', '.join(row['id'] for row in exact)}")
58
+ return exact[0]
59
+
60
+
61
+ def flatten(value: Any) -> list[str]:
62
+ if isinstance(value, str): return [value]
63
+ if isinstance(value, dict): return [item for child in value.values() for item in flatten(child)]
64
+ if isinstance(value, list): return [item for child in value for item in flatten(child)]
65
+ return []
66
+
67
+
68
+ def package_summary(row: dict[str, Any]) -> dict[str, Any]:
69
+ categories = Counter(category for tool in row["tools"] for category in tool["categories"])
70
+ return {"id": row["id"], "name": row["name"], "aliases": row["aliases"],
71
+ "sources": sorted(row["sources"]), "readiness": row["readiness"],
72
+ "tool_counts": dict(sorted(categories.items())), "tools": [p["name"] for p in row["tools"]],
73
+ "package_identifiers": row["package_identifiers"],
74
+ "homebrew_formulas": [p["name"] for p in row["homebrew_formulas"]]}
75
+
76
+
77
+ def tool_search_index(args: dict[str, Any]) -> str:
78
+ query = str(args.get("query", "")).strip()
79
+ if not query: raise ValueError("query is required")
80
+ key = norm(query)
81
+ index = load_inventory()
82
+ matches = [package_summary(row) for row in index["languages"] if any(key in norm(s) for s in flatten(row))]
83
+ offset = max(0, int(args.get("offset", 0)))
84
+ limit = min(100, max(1, int(args.get("limit", 25))))
85
+ return json.dumps({"total": len(matches), "offset": offset, "limit": limit,
86
+ "source_counts": index["counts"], "results": matches[offset:offset + limit]}, ensure_ascii=False, indent=1)
87
+
88
+
89
+ def readiness_match(row: dict[str, Any], category: str) -> bool:
90
+ filters = {"language-server": "language-server-catalogued", "runtime-or-compiler": "runtime-or-compiler-catalogued",
91
+ "development-tools": "development-tools-catalogued", "package-manager": "package-manager-identifiers-recorded",
92
+ "linguist": "github-language-identified", "wikidata": "wikidata-linked", "pldb": "pldb-listed",
93
+ "single-source": "single-source"}
94
+ if category == "all": return True
95
+ if category not in filters: raise ValueError(f"unknown filter '{category}'; use {', '.join([*filters, 'all'])}")
96
+ return filters[category] in row["readiness"]
97
+
98
+
99
+ def tool_list_shelf(args: dict[str, Any]) -> str:
100
+ index = load_inventory()
101
+ category = str(args.get("filter", "all"))
102
+ rows = [package_summary(row) for row in index["languages"] if readiness_match(row, category)]
103
+ offset = max(0, int(args.get("offset", 0)))
104
+ limit = min(100, max(1, int(args.get("limit", 50))))
105
+ return json.dumps({"generated_at": index["generated_at"], "total": len(rows), "offset": offset,
106
+ "limit": limit, "filter": category, "results": rows[offset:offset + limit]}, ensure_ascii=False, indent=1)
107
+
108
+
109
+ def tool_get_language(args: dict[str, Any]) -> str:
110
+ row = get_language(str(args.get("name", "")))
111
+ lsp_tools = [tool for tool in row["tools"] if "LSP" in tool["categories"]]
112
+ adapter = load_adapters()["adapters"][0]
113
+ verification = adapter.get("verification", {})
114
+ candidates = []
115
+ for tool in lsp_tools:
116
+ binaries = tool.get("executables", {})
117
+ executable = (verification.get("executable") if tool["name"] == verification.get("package")
118
+ and verification.get("executable") in binaries else next(iter(binaries), None))
119
+ if not executable: continue
120
+ tested = tool["name"] == verification.get("package") and executable == verification.get("executable")
121
+ candidates.append({"status": "tested-with-this-pairing" if tested else "candidate-not-yet-tested",
122
+ "adapter": adapter["url"], "adapter_version": adapter["version"], "adapter_install": adapter["install"],
123
+ "language_server_package": tool["name"], "language_server_install": tool["install"],
124
+ "executable": executable, "mcp_command": adapter["name"],
125
+ "mcp_args": ["--workspace", "<absolute project path>", "--lsp", executable,
126
+ *(["--", *verification.get("arguments", [])] if tested else [])],
127
+ "source_id": tool["source_id"], "tested_mcp_tools": verification.get("mcp_tools", []) if tested else []})
128
+ result = dict(row)
129
+ result["mcp_candidates"] = candidates
130
+ result["use_note"] = "Catalogue evidence does not prove installation or compatibility."
131
+ return json.dumps(result, ensure_ascii=False, indent=1)
132
+
133
+
134
+ def tool_check_tools(args: dict[str, Any]) -> str:
135
+ row = get_language(str(args.get("name", "")))
136
+ candidates: set[str] = set()
137
+ for package in row["tools"]:
138
+ if set(package["categories"]) & {"LSP", "Runtime", "Compiler"}:
139
+ candidates.update(package.get("executables", {}))
140
+ for formula in row["homebrew_formulas"]:
141
+ if formula["available"]: candidates.update(formula.get("executables", []))
142
+ limit = min(100, max(1, int(args.get("limit", 40))))
143
+ checked = [{"executable": exe, "found_on_path": shutil.which(exe) is not None,
144
+ "path": shutil.which(exe)} for exe in sorted(candidates)[:limit]]
145
+ return json.dumps({"id": row["id"], "name": row["name"], "checked": len(checked), "limit": limit,
146
+ "note": "PATH check only; absolute paths are returned and isolated environments may not be visible.",
147
+ "executables": checked}, ensure_ascii=False, indent=1)
148
+
149
+
150
+ def tool_recommend_stack(args: dict[str, Any]) -> str:
151
+ result = recommend_stack(args.get("task_profile", {}), load_suitability_profiles(), args.get("limit", 5))
152
+ return json.dumps({"recommendations": result}, ensure_ascii=False, indent=1)
153
+
154
+
155
+ def tool_compare_candidates(args: dict[str, Any]) -> str:
156
+ result = compare_candidates(args.get("candidate_ids", []), args.get("task_profile", {}), load_suitability_profiles())
157
+ return json.dumps({"comparisons": result}, ensure_ascii=False, indent=1)
158
+
159
+
160
+ def tool_get_suitability_evidence(args: dict[str, Any]) -> str:
161
+ result = get_suitability_evidence(args.get("language_id", ""), args.get("capability"), load_suitability_profiles())
162
+ return json.dumps(result, ensure_ascii=False, indent=1)
163
+
164
+
165
+ TASK_PROFILE_SCHEMA = json.loads((DATA / "task_profile.schema.json").read_text(encoding="utf-8"))
166
+
167
+
168
+ TOOLS = {
169
+ "search_index": (tool_search_index, {"description": "Search canonical identities, aliases, extensions, source IDs, package IDs, and linked tools.",
170
+ "inputSchema": {"type": "object", "properties": {"query": {"type": "string"}, "offset": {"type": "integer", "default": 0}, "limit": {"type": "integer", "default": 25}}, "required": ["query"]}}),
171
+ "list_shelf": (tool_list_shelf, {"description": "Page through the source union or filter by source coverage and recorded tooling.",
172
+ "inputSchema": {"type": "object", "properties": {"filter": {"type": "string", "enum": ["all", "language-server", "runtime-or-compiler", "development-tools", "package-manager", "linguist", "wikidata", "pldb", "single-source"], "default": "all"}, "offset": {"type": "integer", "default": 0}, "limit": {"type": "integer", "default": 50}}}}),
173
+ "get_language": (tool_get_language, {"description": "Get a source-linked record and its tool and adapter evidence.", "inputSchema": {"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]}}),
174
+ "check_tools": (tool_check_tools, {"description": "Check recorded language-tool and Homebrew executable names against PATH.", "inputSchema": {"type": "object", "properties": {"name": {"type": "string"}, "limit": {"type": "integer", "default": 40}}, "required": ["name"]}}),
175
+ "recommend_stack": (tool_recommend_stack, {"description": "Rank recorded language stacks for a structured task profile. Unknown constraints remain visible; the tool installs nothing.", "annotations": {"readOnlyHint": True}, "inputSchema": {"type": "object", "properties": {"task_profile": TASK_PROFILE_SCHEMA, "limit": {"type": "integer", "default": 5, "minimum": 1, "maximum": 20}}, "required": ["task_profile"]}}),
176
+ "compare_candidates": (tool_compare_candidates, {"description": "Compare stack IDs against one structured task profile, including failed and unknown constraints.", "annotations": {"readOnlyHint": True}, "inputSchema": {"type": "object", "properties": {"candidate_ids": {"type": "array", "items": {"type": "string"}, "minItems": 1}, "task_profile": TASK_PROFILE_SCHEMA}, "required": ["candidate_ids", "task_profile"]}}),
177
+ "get_suitability_evidence": (tool_get_suitability_evidence, {"description": "Return documented suitability claims and evidence for a canonical language ID.", "annotations": {"readOnlyHint": True}, "inputSchema": {"type": "object", "properties": {"language_id": {"type": "string"}, "capability": {"type": "string"}}, "required": ["language_id"]}}),
178
+ }
179
+
180
+
181
+ def respond(msg_id: Any, result: Any = None, error: Any = None) -> dict[str, Any]:
182
+ out: dict[str, Any] = {"jsonrpc": "2.0", "id": msg_id}
183
+ out["error" if error is not None else "result"] = error if error is not None else result
184
+ return out
185
+
186
+
187
+ def handle(msg: dict[str, Any]) -> dict[str, Any] | None:
188
+ method, msg_id = msg.get("method"), msg.get("id")
189
+ if method == "notifications/initialized" or msg_id is None: return None
190
+ if method == "initialize":
191
+ return respond(msg_id, {"protocolVersion": PROTOCOL, "capabilities": {"tools": {}}, "serverInfo": {"name": "coding-language-library", "version": "0.3.1"}})
192
+ if method == "ping": return respond(msg_id, {})
193
+ if method == "tools/list": return respond(msg_id, {"tools": [{"name": n, **spec} for n, (_, spec) in TOOLS.items()]})
194
+ if method == "tools/call":
195
+ params = msg.get("params", {}); name = params.get("name")
196
+ if name not in TOOLS: return respond(msg_id, error={"code": -32602, "message": f"unknown tool {name}"})
197
+ try:
198
+ text = TOOLS[name][0](params.get("arguments", {}) or {})
199
+ return respond(msg_id, {"content": [{"type": "text", "text": text}], "isError": False})
200
+ except (ValueError, KeyError, OSError, TypeError) as exc:
201
+ return respond(msg_id, {"content": [{"type": "text", "text": str(exc)}], "isError": True})
202
+ return respond(msg_id, error={"code": -32601, "message": f"method not found: {method}"})
203
+
204
+
205
+ def main() -> int:
206
+ for line in sys.stdin:
207
+ if not line.strip(): continue
208
+ try: msg = json.loads(line)
209
+ except json.JSONDecodeError:
210
+ sys.stdout.write(json.dumps(respond(None, error={"code": -32700, "message": "parse error"})) + "\n")
211
+ sys.stdout.flush(); continue
212
+ reply = handle(msg)
213
+ if reply is not None:
214
+ sys.stdout.write(json.dumps(reply, ensure_ascii=False) + "\n"); sys.stdout.flush()
215
+ return 0
216
+
217
+
218
+ if __name__ == "__main__":
219
+ raise SystemExit(main())
mcp/task_matching.py ADDED
@@ -0,0 +1,375 @@
1
+ """Evidence-backed, deterministic task-to-stack matching."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from typing import Any
8
+
9
+
10
+ MAX_RESULTS = 20
11
+ CAPABILITY_STATUSES = {"supported", "supported_with_conditions", "unsupported", "unknown"}
12
+ VERIFICATION_STATUSES = {"catalogue_only", "source_documented", "environment_checked", "project_tested"}
13
+ RANK_WEIGHTS = {
14
+ "existing_language": 100,
15
+ "existing_framework": 60,
16
+ "team_experience": 20,
17
+ "priority_step": 10,
18
+ "priority_cap": 60,
19
+ }
20
+
21
+
22
+ def _norm(value: str) -> str:
23
+ return "".join(char for char in value.casefold() if char.isalnum() or char in "+#")
24
+
25
+
26
+ PROSE_PATTERNS = [
27
+ (re.compile(r"\b(?:memory|ram)\b|\b\d+(?:\.\d+)?\s*(?:mb|gb|kib|mib|gib)\b", re.IGNORECASE), "requirements.memory_limit_mb"),
28
+ (re.compile(r"\bnative\b", re.IGNORECASE), "requirements.native_dependencies_allowed"),
29
+ (re.compile(r"\bplatform\b", re.IGNORECASE), "target.platform"),
30
+ (re.compile(r"\b(?:deploy|deployment)\b", re.IGNORECASE), "target.deployment"),
31
+ (re.compile(r"\bintegrat(?:e|es|ed|ion|ions)\b", re.IGNORECASE), "requirements.required_integrations"),
32
+ ]
33
+
34
+
35
+ def _unstructured_terms(task: dict[str, Any]) -> list[str]:
36
+ """Constraint terms named in the task text but missing from the structured fields."""
37
+ text = task.get("task", "") if isinstance(task.get("task"), str) else ""
38
+ if not text.strip():
39
+ return []
40
+ requirements = task.get("requirements", {})
41
+ target = task.get("target", {})
42
+ occupied = {
43
+ "requirements.memory_limit_mb": requirements.get("memory_limit_mb") is not None,
44
+ "requirements.native_dependencies_allowed": requirements.get("native_dependencies_allowed") is not None,
45
+ "requirements.required_integrations": bool(requirements.get("required_integrations")),
46
+ "target.platform": bool(target.get("platform")),
47
+ "target.deployment": bool(target.get("deployment")),
48
+ }
49
+ found: list[str] = []
50
+ for pattern, field in PROSE_PATTERNS:
51
+ if not occupied.get(field) and field not in found and pattern.search(text):
52
+ found.append(field)
53
+ return found
54
+
55
+
56
+ def _validate_evidence(evidence: Any, context: str) -> None:
57
+ if not isinstance(evidence, list):
58
+ raise ValueError(f"{context}.evidence must be a list")
59
+ for index, item in enumerate(evidence):
60
+ if not isinstance(item, dict):
61
+ raise ValueError(f"{context}.evidence[{index}] must be an object")
62
+ for field in ("source_url", "checked_at", "applies_to"):
63
+ value = item.get(field)
64
+ if not isinstance(value, str) or not value.strip():
65
+ raise ValueError(f"{context}.evidence[{index}].{field} is required")
66
+ if not item["source_url"].startswith("https://"):
67
+ raise ValueError(f"{context}.evidence[{index}].source_url must use HTTPS")
68
+
69
+
70
+ def _profiles(profiles: dict[str, Any]) -> list[dict[str, Any]]:
71
+ if not isinstance(profiles, dict) or profiles.get("schema_version") != 1:
72
+ raise ValueError("unsupported suitability profile schema")
73
+ stacks = profiles.get("stacks")
74
+ if not isinstance(stacks, list):
75
+ raise ValueError("suitability profiles must contain a stacks list")
76
+ ids: list[str] = []
77
+ for index, stack in enumerate(stacks):
78
+ context = f"stacks[{index}]"
79
+ if not isinstance(stack, dict):
80
+ raise ValueError(f"{context} must be an object")
81
+ for field in ("id", "language_id", "language_name"):
82
+ value = stack.get(field)
83
+ if not isinstance(value, str) or not value.strip():
84
+ raise ValueError(f"{context}.{field} must be a non-empty string")
85
+ ids.append(stack["id"])
86
+ for field in ("framework", "runtime"):
87
+ value = stack.get(field)
88
+ if value is not None and not isinstance(value, str):
89
+ raise ValueError(f"{context}.{field} must be a string")
90
+ frameworks = stack.get("frameworks", [])
91
+ if not isinstance(frameworks, list) or any(not isinstance(value, str) or not value.strip() for value in frameworks):
92
+ raise ValueError(f"{context}.frameworks must be a list of non-empty strings")
93
+ verification = stack.get("verification_status", "catalogue_only")
94
+ if not isinstance(verification, str) or verification not in VERIFICATION_STATUSES:
95
+ raise ValueError(f"{context}.verification_status is invalid")
96
+ capabilities = stack.get("capabilities", {})
97
+ if not isinstance(capabilities, dict):
98
+ raise ValueError(f"{context}.capabilities must be an object")
99
+ for key, claim in capabilities.items():
100
+ claim_context = f"{context}.capabilities.{key}"
101
+ if not isinstance(key, str) or not key or not isinstance(claim, dict):
102
+ raise ValueError(f"{claim_context} must be a named object")
103
+ status = claim.get("status", "unknown")
104
+ if not isinstance(status, str) or status not in CAPABILITY_STATUSES:
105
+ raise ValueError(f"{claim_context}.status is invalid")
106
+ conditions = claim.get("conditions", [])
107
+ if not isinstance(conditions, list) or any(not isinstance(value, str) for value in conditions):
108
+ raise ValueError(f"{claim_context}.conditions must be a list of strings")
109
+ _validate_evidence(claim.get("evidence", []), claim_context)
110
+ signals = stack.get("preference_signals", {})
111
+ if not isinstance(signals, dict):
112
+ raise ValueError(f"{context}.preference_signals must be an object")
113
+ for name, signal in signals.items():
114
+ signal_context = f"{context}.preference_signals.{name}"
115
+ if not isinstance(name, str) or not name or not isinstance(signal, dict):
116
+ raise ValueError(f"{signal_context} must be a named object")
117
+ status = signal.get("status", "unknown")
118
+ if not isinstance(status, str) or status not in CAPABILITY_STATUSES:
119
+ raise ValueError(f"{signal_context}.status is invalid")
120
+ _validate_evidence(signal.get("evidence", []), signal_context)
121
+ if len(ids) != len(set(ids)):
122
+ raise ValueError("duplicate stack identifiers")
123
+ return stacks
124
+
125
+
126
+ def _validate_task(task: dict[str, Any]) -> None:
127
+ if not isinstance(task, dict) or not isinstance(task.get("task"), str) or not task["task"].strip():
128
+ raise ValueError("task_profile.task must be a non-empty string")
129
+ allowed = {"task", "existing_project", "target", "requirements", "priorities", "team_experience", "unknowns"}
130
+ extra = set(task) - allowed
131
+ if extra:
132
+ raise ValueError("unsupported task_profile fields: " + ", ".join(sorted(extra)))
133
+ section_fields = {
134
+ "existing_project": {"languages", "frameworks"},
135
+ "target": {"platform", "deployment"},
136
+ "requirements": {"required_integrations", "memory_limit_mb", "native_dependencies_allowed"},
137
+ }
138
+ for section, allowed_fields in section_fields.items():
139
+ value = task.get(section, {})
140
+ if not isinstance(value, dict):
141
+ raise ValueError(f"task_profile.{section} must be an object")
142
+ extra = set(value) - allowed_fields
143
+ if extra:
144
+ raise ValueError(f"unsupported task_profile.{section} fields: " + ", ".join(sorted(extra)))
145
+ existing = task.get("existing_project", {})
146
+ for field in ("languages", "frameworks"):
147
+ values = existing.get(field, [])
148
+ if not isinstance(values, list) or any(not isinstance(value, str) or not value.strip() for value in values):
149
+ raise ValueError(f"task_profile.existing_project.{field} must be a list of non-empty strings")
150
+ target = task.get("target", {})
151
+ for field in ("platform", "deployment"):
152
+ if field in target and (not isinstance(target[field], str) or not target[field].strip()):
153
+ raise ValueError(f"task_profile.target.{field} must be a non-empty string")
154
+ requirements = task.get("requirements", {})
155
+ integrations = requirements.get("required_integrations", [])
156
+ if not isinstance(integrations, list) or any(not isinstance(value, str) or not value.strip() for value in integrations):
157
+ raise ValueError("task_profile.requirements.required_integrations must be a list of non-empty strings")
158
+ memory = requirements.get("memory_limit_mb")
159
+ if memory is not None and (isinstance(memory, bool) or not isinstance(memory, (int, float)) or not math.isfinite(memory) or memory <= 0):
160
+ raise ValueError("task_profile.requirements.memory_limit_mb must be a positive finite number")
161
+ native_allowed = requirements.get("native_dependencies_allowed")
162
+ if native_allowed is not None and not isinstance(native_allowed, bool):
163
+ raise ValueError("task_profile.requirements.native_dependencies_allowed must be boolean")
164
+ for field in ("priorities", "team_experience", "unknowns"):
165
+ values = task.get(field, [])
166
+ if not isinstance(values, list) or any(not isinstance(value, str) or not value.strip() for value in values):
167
+ raise ValueError(f"task_profile.{field} must be a list of non-empty strings")
168
+
169
+
170
+ def _capability_result(stack: dict[str, Any], key: str) -> tuple[str, dict[str, Any] | None]:
171
+ claim = stack.get("capabilities", {}).get(key)
172
+ if not isinstance(claim, dict):
173
+ return "unknown", None
174
+ status = claim.get("status", "unknown")
175
+ if status not in {"supported", "supported_with_conditions", "unsupported", "unknown"}:
176
+ return "unknown", None
177
+ return status, claim
178
+
179
+
180
+ def _hard_constraints(task: dict[str, Any], stack: dict[str, Any]) -> dict[str, list[str]]:
181
+ result = {"passed": [], "failed": [], "unknown": []}
182
+ checks: list[tuple[str, str]] = []
183
+ target = task.get("target", {})
184
+ if target.get("platform"):
185
+ checks.append((f"target.platform={target['platform']}", f"platform.{_norm(target['platform'])}"))
186
+ if target.get("deployment"):
187
+ checks.append((f"target.deployment={target['deployment']}", f"deployment.{_norm(target['deployment'])}"))
188
+ for integration in task.get("requirements", {}).get("required_integrations", []):
189
+ checks.append((f"integration.{_norm(integration)}", f"integration.{_norm(integration)}"))
190
+
191
+ requirements = task.get("requirements", {})
192
+ if requirements.get("memory_limit_mb") is not None:
193
+ key = "resources.memory_peak_mb"
194
+ status, claim = _capability_result(stack, key)
195
+ value = claim.get("value") if claim else None
196
+ label = f"requirements.memory_limit_mb<={requirements['memory_limit_mb']}"
197
+ if status == "supported" and isinstance(value, (int, float)):
198
+ (result["passed"] if value <= requirements["memory_limit_mb"] else result["failed"]).append(label)
199
+ else:
200
+ result["unknown"].append(label)
201
+
202
+ if requirements.get("native_dependencies_allowed") is False:
203
+ key = "dependencies.native"
204
+ status, claim = _capability_result(stack, key)
205
+ value = claim.get("value") if claim else None
206
+ label = "requirements.native_dependencies_allowed=false"
207
+ if status == "supported" and value == "not_required":
208
+ result["passed"].append(label)
209
+ elif status == "supported" and value == "required":
210
+ result["failed"].append(label)
211
+ else:
212
+ result["unknown"].append(label)
213
+
214
+ for label, key in checks:
215
+ status, _ = _capability_result(stack, key)
216
+ if status == "supported":
217
+ result["passed"].append(label)
218
+ elif status == "unsupported":
219
+ result["failed"].append(label)
220
+ else:
221
+ result["unknown"].append(label)
222
+ return result
223
+
224
+
225
+ def _rank(task: dict[str, Any], stack: dict[str, Any]) -> tuple[int, list[str]]:
226
+ score = 0
227
+ reasons: list[str] = []
228
+ existing = task.get("existing_project", {})
229
+ languages = {_norm(value) for value in existing.get("languages", [])}
230
+ frameworks = {_norm(value) for value in existing.get("frameworks", [])}
231
+ stack_language = {_norm(stack.get("language_id", "")), _norm(stack.get("language_name", ""))}
232
+ stack_frameworks = stack.get("frameworks", [stack.get("framework", "")])
233
+ stack_framework = {_norm(value) for value in stack_frameworks if isinstance(value, str)}
234
+ stack_framework.add(_norm(stack.get("id", "")))
235
+ if languages & stack_language:
236
+ score += RANK_WEIGHTS["existing_language"]
237
+ reasons.append("Matches an existing project language (+100).")
238
+ if frameworks & stack_framework:
239
+ score += RANK_WEIGHTS["existing_framework"]
240
+ reasons.append("Matches a framework already used by the project (+60).")
241
+
242
+ experience = {_norm(value) for value in task.get("team_experience", [])}
243
+ if experience & (stack_language | stack_framework):
244
+ score += RANK_WEIGHTS["team_experience"]
245
+ reasons.append("Matches recorded team experience (+20).")
246
+
247
+ signals = stack.get("preference_signals", {})
248
+ priorities = task.get("priorities", [])
249
+ for index, priority in enumerate(priorities):
250
+ weight = min((len(priorities) - index) * RANK_WEIGHTS["priority_step"], RANK_WEIGHTS["priority_cap"])
251
+ signal = signals.get(priority) if isinstance(signals, dict) else None
252
+ if isinstance(signal, dict) and signal.get("status") == "supported" and signal.get("evidence"):
253
+ score += weight
254
+ reasons.append(f"Evidence supports priority '{priority}' (+{weight}).")
255
+ return score, reasons
256
+
257
+
258
+ def _supported_signal(signal: Any) -> bool:
259
+ return (isinstance(signal, dict) and signal.get("status") == "supported"
260
+ and bool(signal.get("evidence")))
261
+
262
+
263
+ def _record(task: dict[str, Any], stack: dict[str, Any], unstructured: list[str] | None = None) -> dict[str, Any]:
264
+ constraints = _hard_constraints(task, stack)
265
+ score, reasons = _rank(task, stack)
266
+ if unstructured is None:
267
+ unstructured = _unstructured_terms(task)
268
+ capabilities = stack.get("capabilities", {})
269
+ signals = stack.get("preference_signals", {})
270
+ evidence = [
271
+ {"kind": "capability", "capability": key, **claim}
272
+ for key, claim in sorted(capabilities.items())
273
+ if isinstance(claim, dict) and claim.get("evidence")
274
+ ]
275
+ for priority, signal in sorted(signals.items()):
276
+ if isinstance(signal, dict) and signal.get("evidence"):
277
+ evidence.append({
278
+ "kind": "preference_signal",
279
+ "priority": priority,
280
+ "status": signal.get("status", "unknown"),
281
+ "conditions": signal.get("conditions", []),
282
+ "evidence": signal["evidence"],
283
+ })
284
+ unknown_preferences = [
285
+ priority for priority in task.get("priorities", [])
286
+ if not _supported_signal(signals.get(priority))
287
+ ]
288
+ if unknown_preferences:
289
+ reasons.append("No profile evidence ranks these priorities: " + ", ".join(unknown_preferences) + ".")
290
+ if not reasons:
291
+ reasons.append("No evidence-backed preference distinguishes this candidate.")
292
+ reasons.extend(stack.get("reasons", []))
293
+ return {
294
+ "candidate": {
295
+ "stack_id": stack["id"],
296
+ "language_id": stack["language_id"],
297
+ "language": stack["language_name"],
298
+ "framework": stack.get("framework"),
299
+ "runtime": stack.get("runtime"),
300
+ },
301
+ "hard_constraints": constraints,
302
+ "rank_score": score,
303
+ "rank_score_note": "Relative comparison points, not a probability of success.",
304
+ "reasons": reasons,
305
+ "tradeoffs": stack.get("tradeoffs", []),
306
+ "evidence": evidence,
307
+ "verification_status": stack.get("verification_status", "catalogue_only"),
308
+ "unstructured_terms": unstructured,
309
+ "open_questions": task.get("unknowns", []),
310
+ "next_validation": stack.get("next_validation", "Build and test a minimal representative project."),
311
+ }
312
+
313
+
314
+ def _assign_ranks(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
315
+ previous_score: int | None = None
316
+ current_rank = 0
317
+ for index, row in enumerate(rows, start=1):
318
+ if row["rank_score"] != previous_score:
319
+ current_rank = index
320
+ previous_score = row["rank_score"]
321
+ row["rank"] = current_rank
322
+ return rows
323
+
324
+
325
+
326
+ def recommend_stack(task_profile: dict[str, Any], profiles: dict[str, Any], limit: int = 5) -> list[dict[str, Any]]:
327
+ _validate_task(task_profile)
328
+ if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= MAX_RESULTS:
329
+ raise ValueError(f"limit must be an integer from 1 to {MAX_RESULTS}")
330
+ ranked = []
331
+ unstructured = _unstructured_terms(task_profile)
332
+ for stack in _profiles(profiles):
333
+ record = _record(task_profile, stack, unstructured)
334
+ if record["hard_constraints"]["failed"]:
335
+ continue
336
+ ranked.append(record)
337
+ ranked.sort(key=lambda row: -row["rank_score"])
338
+ return _assign_ranks(ranked[:limit])
339
+
340
+
341
+ def compare_candidates(candidate_ids: list[str], task_profile: dict[str, Any], profiles: dict[str, Any]) -> list[dict[str, Any]]:
342
+ if not isinstance(candidate_ids, list) or not candidate_ids or any(not isinstance(value, str) for value in candidate_ids):
343
+ raise ValueError("candidate_ids must be a non-empty list of stack IDs")
344
+ stacks = _profiles(profiles)
345
+ by_id = {stack["id"]: stack for stack in stacks}
346
+ if len(set(candidate_ids)) != len(candidate_ids):
347
+ raise ValueError("candidate_ids must not contain duplicates")
348
+ missing = sorted(set(candidate_ids) - set(by_id))
349
+ if missing:
350
+ raise ValueError("unknown candidate stack IDs: " + ", ".join(missing))
351
+ _validate_task(task_profile)
352
+ compared = [_record(task_profile, by_id[value], _unstructured_terms(task_profile)) for value in candidate_ids]
353
+ compared.sort(key=lambda row: -row["rank_score"])
354
+ return _assign_ranks(compared)
355
+
356
+
357
+ def get_suitability_evidence(language_id: str, capability: str | None, profiles: dict[str, Any]) -> dict[str, Any]:
358
+ if not isinstance(language_id, str) or not language_id:
359
+ raise ValueError("language_id is required")
360
+ stacks = _profiles(profiles)
361
+ matches = [stack for stack in stacks if stack.get("language_id") == language_id]
362
+ if not matches:
363
+ raise ValueError(f"unknown language ID: {language_id}")
364
+ if capability is not None and (not isinstance(capability, str) or not capability.strip()):
365
+ raise ValueError("capability must be a non-empty string")
366
+ claims = []
367
+ for stack in matches:
368
+ capabilities = stack.get("capabilities", {})
369
+ selected = {capability: capabilities.get(capability)} if capability else capabilities
370
+ for key, claim in sorted(selected.items()):
371
+ if isinstance(claim, dict):
372
+ claims.append({"stack_id": stack["id"], "capability": key, **claim})
373
+ else:
374
+ claims.append({"stack_id": stack["id"], "capability": key, "status": "unknown", "evidence": []})
375
+ return {"language_id": language_id, "capability": capability, "claims": claims}