prompt-capability-optimizer 1.0.0
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.
- package/LICENSE +21 -0
- package/README.md +165 -0
- package/SKILL.md +275 -0
- package/adapters/environment_adapters.md +94 -0
- package/adapters/host_capabilities.json +135 -0
- package/bin/cli.js +33 -0
- package/index.js +54 -0
- package/package.json +51 -0
- package/prompt_capability_optimizer/__init__.py +35 -0
- package/prompt_capability_optimizer/__main__.py +7 -0
- package/prompt_capability_optimizer/adapters/__init__.py +21 -0
- package/prompt_capability_optimizer/adapters/agent_adapters.py +281 -0
- package/prompt_capability_optimizer/adapters/host_adapter.py +48 -0
- package/prompt_capability_optimizer/capabilities/__init__.py +7 -0
- package/prompt_capability_optimizer/capabilities/extractor.py +92 -0
- package/prompt_capability_optimizer/capabilities/graph.py +53 -0
- package/prompt_capability_optimizer/classification/__init__.py +6 -0
- package/prompt_capability_optimizer/classification/task_classifier.py +126 -0
- package/prompt_capability_optimizer/cli.py +85 -0
- package/prompt_capability_optimizer/config.py +42 -0
- package/prompt_capability_optimizer/critique/__init__.py +6 -0
- package/prompt_capability_optimizer/critique/self_critique_engine.py +144 -0
- package/prompt_capability_optimizer/discovery/__init__.py +16 -0
- package/prompt_capability_optimizer/discovery/find_skills_adapter.py +143 -0
- package/prompt_capability_optimizer/discovery/local_discovery.py +114 -0
- package/prompt_capability_optimizer/discovery/mcp_discovery.py +145 -0
- package/prompt_capability_optimizer/discovery/registry.py +52 -0
- package/prompt_capability_optimizer/discovery/web_discovery.py +157 -0
- package/prompt_capability_optimizer/engine.py +201 -0
- package/prompt_capability_optimizer/intent/__init__.py +6 -0
- package/prompt_capability_optimizer/intent/intent_analyzer.py +61 -0
- package/prompt_capability_optimizer/models.py +162 -0
- package/prompt_capability_optimizer/optimization/__init__.py +8 -0
- package/prompt_capability_optimizer/optimization/execution_pass.py +52 -0
- package/prompt_capability_optimizer/optimization/optimizer.py +85 -0
- package/prompt_capability_optimizer/optimization/semantic_pass.py +113 -0
- package/prompt_capability_optimizer/scoring/__init__.py +7 -0
- package/prompt_capability_optimizer/scoring/deduplicator.py +46 -0
- package/prompt_capability_optimizer/scoring/scoring_engine.py +34 -0
- package/prompt_capability_optimizer/security/__init__.py +14 -0
- package/prompt_capability_optimizer/security/governance.py +41 -0
- package/prompt_capability_optimizer/security/injection_detector.py +60 -0
- package/prompt_capability_optimizer/security/secret_protector.py +61 -0
- package/prompt_capability_optimizer/security/trust_engine.py +96 -0
- package/prompt_capability_optimizer/verification/__init__.py +6 -0
- package/prompt_capability_optimizer/verification/verification_engine.py +101 -0
- package/references/capability_graph.md +83 -0
- package/references/cross_agent_matrix.md +62 -0
- package/references/prompt_engineering_standards.md +90 -0
- package/references/scoring_rubric.md +49 -0
- package/references/security_and_trust.md +48 -0
- package/scripts/capability_checker.py +88 -0
- package/scripts/prompt_optimizer_engine.py +41 -0
- package/templates/execution_plan_template.md +51 -0
- package/templates/optimized_prompt_template.md +55 -0
- package/templates/verification_matrix_template.md +26 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mahmoud Abdelhameid (Develper.net@gmail.com). All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Prompt Capability Optimizer Core Engine
|
|
6
|
+
=======================================
|
|
7
|
+
End-to-end execution pipeline connecting classification, capability graph,
|
|
8
|
+
discovery, trust evaluation, two-pass optimization, self-critique, and Mode C lifecycle.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from typing import Dict, Any, List, Optional
|
|
12
|
+
from .models import PromptIR, Resource, ClassificationReport, CritiqueReport, RiskLevel
|
|
13
|
+
from .config import DEFAULT_CONFIG, OptimizerConfig
|
|
14
|
+
from .classification.task_classifier import TaskClassifier
|
|
15
|
+
from .intent.intent_analyzer import IntentAnalyzer
|
|
16
|
+
from .capabilities.extractor import CapabilityExtractor
|
|
17
|
+
from .capabilities.graph import CapabilityGraph
|
|
18
|
+
from .discovery.registry import ResourceRegistry
|
|
19
|
+
from .discovery.local_discovery import LocalSkillDiscovery
|
|
20
|
+
from .discovery.mcp_discovery import McpDiscovery
|
|
21
|
+
from .discovery.web_discovery import WebDiscovery
|
|
22
|
+
from .discovery.find_skills_adapter import FindSkillsAdapter
|
|
23
|
+
from .security.trust_engine import TrustEngine
|
|
24
|
+
from .security.injection_detector import PromptInjectionDetector
|
|
25
|
+
from .security.secret_protector import SecretProtector
|
|
26
|
+
from .scoring.deduplicator import CapabilityDeduplicator
|
|
27
|
+
from .verification.verification_engine import VerificationEngine
|
|
28
|
+
from .optimization.optimizer import TwoPassOptimizer
|
|
29
|
+
from .critique.self_critique_engine import SelfCritiqueEngine
|
|
30
|
+
|
|
31
|
+
class PromptOptimizerEngine:
|
|
32
|
+
|
|
33
|
+
def __init__(self, config: Optional[OptimizerConfig] = None):
|
|
34
|
+
self.config = config or DEFAULT_CONFIG
|
|
35
|
+
self.registry = ResourceRegistry()
|
|
36
|
+
self.find_skills_adapter = FindSkillsAdapter()
|
|
37
|
+
self.web_discovery = WebDiscovery()
|
|
38
|
+
|
|
39
|
+
def _populate_discovery(self, required_caps: List[str], depth: int):
|
|
40
|
+
# 1. Real local skill discovery
|
|
41
|
+
local_skills = LocalSkillDiscovery.discover()
|
|
42
|
+
self.registry.register_many(local_skills)
|
|
43
|
+
|
|
44
|
+
# 2. Real host MCP discovery with parsed state machine
|
|
45
|
+
mcp_servers = McpDiscovery.discover()
|
|
46
|
+
self.registry.register_many(mcp_servers)
|
|
47
|
+
|
|
48
|
+
# 3. Real find-skills integration: query for specialized capabilities
|
|
49
|
+
if depth >= 1 and self.config.enable_find_skills_cli:
|
|
50
|
+
for cap_name in required_caps:
|
|
51
|
+
# Query open skills ecosystem for packages matching capability
|
|
52
|
+
skills_results = self.find_skills_adapter.search(cap_name, limit=2)
|
|
53
|
+
if skills_results:
|
|
54
|
+
self.registry.register_many(skills_results)
|
|
55
|
+
|
|
56
|
+
# 4. Real Web Discovery pipeline for dynamic/unseen technologies
|
|
57
|
+
if depth >= 1 and self.config.enable_web_discovery:
|
|
58
|
+
for cap_name in required_caps:
|
|
59
|
+
web_docs = self.web_discovery.discover_for_capability(cap_name)
|
|
60
|
+
if web_docs:
|
|
61
|
+
self.registry.register_many(web_docs)
|
|
62
|
+
|
|
63
|
+
def optimize(self, raw_prompt: str, mode: str = "B", confirmed_execution: bool = False) -> Dict[str, Any]:
|
|
64
|
+
"""
|
|
65
|
+
Executes the full pipeline:
|
|
66
|
+
Intent -> Classify -> Capabilities -> Discovery -> Scoring -> Two-Pass Optimization -> Critique -> Mode C Governance -> Output
|
|
67
|
+
"""
|
|
68
|
+
# Step 0: Security Sanity Check (Secret protection & Prompt Injection Detection)
|
|
69
|
+
secrets_found = SecretProtector.find_secrets(raw_prompt)
|
|
70
|
+
safe_prompt = SecretProtector.redact(raw_prompt)
|
|
71
|
+
injection_scan = PromptInjectionDetector.scan(safe_prompt)
|
|
72
|
+
if injection_scan["is_suspicious"]:
|
|
73
|
+
safe_prompt = PromptInjectionDetector.sanitize(safe_prompt)
|
|
74
|
+
|
|
75
|
+
# Step 1: Classification & Intent
|
|
76
|
+
classification = TaskClassifier.classify(safe_prompt)
|
|
77
|
+
intent_data = IntentAnalyzer.analyze(safe_prompt)
|
|
78
|
+
|
|
79
|
+
# Step 2: Capability Extraction & Graph
|
|
80
|
+
caps = CapabilityExtractor.extract_capabilities(safe_prompt)
|
|
81
|
+
cap_graph = CapabilityGraph(caps)
|
|
82
|
+
required_cap_names = cap_graph.get_capability_names()
|
|
83
|
+
|
|
84
|
+
# Step 3: Real Discovery (Local, find-skills, MCP, Web)
|
|
85
|
+
self.registry.clear()
|
|
86
|
+
self._populate_discovery(required_cap_names, classification.level)
|
|
87
|
+
|
|
88
|
+
# Step 4: Capability Matching & Trust Evaluation
|
|
89
|
+
matched_resources: List[Resource] = []
|
|
90
|
+
for cap_name in required_cap_names:
|
|
91
|
+
found = self.registry.find_by_capability(cap_name)
|
|
92
|
+
for r in found:
|
|
93
|
+
TrustEngine.evaluate_resource_trust(r)
|
|
94
|
+
if r not in matched_resources:
|
|
95
|
+
matched_resources.append(r)
|
|
96
|
+
|
|
97
|
+
# Step 5: Scoring, Filtering & Deduplication
|
|
98
|
+
max_skills = self.config.max_skills_level_4 if classification.level >= 4 else self.config.max_skills_per_prompt
|
|
99
|
+
selected_resources = CapabilityDeduplicator.deduplicate(
|
|
100
|
+
matched_resources,
|
|
101
|
+
max_count=max_skills,
|
|
102
|
+
min_utility=self.config.utility_conditional_threshold
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
# Ensure at least baseline agent execution tool is bound for complex tasks if none was discovered
|
|
106
|
+
if not selected_resources and classification.level >= 2:
|
|
107
|
+
selected_resources.append(Resource(
|
|
108
|
+
id="builtin:native-agent-tools",
|
|
109
|
+
name="Native Host Agent Execution Tools",
|
|
110
|
+
type=ResourceType.BUILTIN_TOOL,
|
|
111
|
+
source="host_runtime",
|
|
112
|
+
capabilities=["filesystem-access", "shell-execution"],
|
|
113
|
+
relevance=8.0,
|
|
114
|
+
capability_match=8.0,
|
|
115
|
+
quality=9.0,
|
|
116
|
+
trust=10.0,
|
|
117
|
+
reputation=10.0,
|
|
118
|
+
compatibility=10.0,
|
|
119
|
+
freshness=10.0,
|
|
120
|
+
overhead=1.0,
|
|
121
|
+
risk=0.0,
|
|
122
|
+
risk_level=RiskLevel.NO_SIDE_EFFECT
|
|
123
|
+
))
|
|
124
|
+
|
|
125
|
+
# Step 6: Dynamic Repository Verification
|
|
126
|
+
verification_directives = VerificationEngine.derive_verification_directives()
|
|
127
|
+
|
|
128
|
+
# Step 7: Two-Pass Optimization
|
|
129
|
+
prompt_ir = TwoPassOptimizer.optimize(
|
|
130
|
+
raw_prompt=safe_prompt,
|
|
131
|
+
classification=classification,
|
|
132
|
+
selected_resources=selected_resources,
|
|
133
|
+
verification_cmds=verification_directives
|
|
134
|
+
)
|
|
135
|
+
rendered_prompt = TwoPassOptimizer.render_prompt(prompt_ir)
|
|
136
|
+
|
|
137
|
+
# Step 8: Real Qualitative Self-Critique
|
|
138
|
+
critique_report = SelfCritiqueEngine.evaluate(rendered_prompt, depth=classification.level)
|
|
139
|
+
|
|
140
|
+
# Step 9: Automatic Correction Pass (if critique indicates missing requirements)
|
|
141
|
+
if not critique_report.passed:
|
|
142
|
+
for rec in critique_report.recommendations:
|
|
143
|
+
if "negative" in rec.lower():
|
|
144
|
+
prompt_ir.negative_constraints.append("Do NOT alter unrequested codebase layers.")
|
|
145
|
+
if "completion" in rec.lower():
|
|
146
|
+
prompt_ir.completion_criteria.append("100% of integration checks pass against baseline.")
|
|
147
|
+
rendered_prompt = TwoPassOptimizer.render_prompt(prompt_ir)
|
|
148
|
+
# Re-evaluate
|
|
149
|
+
critique_report = SelfCritiqueEngine.evaluate(rendered_prompt, depth=classification.level)
|
|
150
|
+
|
|
151
|
+
# Step 10: Mode C Lifecycle & Governance Check
|
|
152
|
+
execution_status = "NOT_REQUESTED"
|
|
153
|
+
if mode.upper() == "C":
|
|
154
|
+
task_has_side_effects = any(kw in safe_prompt.lower() for kw in ["install", "deploy", "delete", "drop", "publish", "push", "remove", "migrate"])
|
|
155
|
+
resource_has_side_effects = any(r.risk_level in [RiskLevel.EXTERNAL_SIDE_EFFECT, RiskLevel.DESTRUCTIVE] for r in selected_resources)
|
|
156
|
+
has_side_effects = task_has_side_effects or resource_has_side_effects
|
|
157
|
+
|
|
158
|
+
if has_side_effects and not confirmed_execution:
|
|
159
|
+
execution_status = "AWAITING_USER_APPROVAL (Side-effects detected; explicit confirmation required)"
|
|
160
|
+
else:
|
|
161
|
+
execution_status = "READY_FOR_CONTROLLED_EXECUTION"
|
|
162
|
+
|
|
163
|
+
return {
|
|
164
|
+
"mode": mode.upper(),
|
|
165
|
+
"execution_status": execution_status,
|
|
166
|
+
"classification": {
|
|
167
|
+
"level": classification.level,
|
|
168
|
+
"confidence": classification.confidence,
|
|
169
|
+
"signals": classification.signals,
|
|
170
|
+
"reasoning": classification.reasoning
|
|
171
|
+
},
|
|
172
|
+
"required_capabilities": required_cap_names,
|
|
173
|
+
"selected_resources": [
|
|
174
|
+
{
|
|
175
|
+
"name": r.name,
|
|
176
|
+
"type": r.type.value,
|
|
177
|
+
"utility_score": r.utility_score,
|
|
178
|
+
"trust": r.trust,
|
|
179
|
+
"source": r.source,
|
|
180
|
+
"risk_level": r.risk_level.value
|
|
181
|
+
}
|
|
182
|
+
for r in selected_resources
|
|
183
|
+
],
|
|
184
|
+
"security": {
|
|
185
|
+
"secrets_redacted": len(secrets_found),
|
|
186
|
+
"injection_threats_neutralized": len(injection_scan["threats_detected"])
|
|
187
|
+
},
|
|
188
|
+
"critique": {
|
|
189
|
+
"passed": critique_report.passed,
|
|
190
|
+
"score": critique_report.score,
|
|
191
|
+
"confidence": critique_report.confidence,
|
|
192
|
+
"critical_issues": critique_report.critical_issues,
|
|
193
|
+
"recommendations": critique_report.recommendations
|
|
194
|
+
},
|
|
195
|
+
"diff": {
|
|
196
|
+
"added_constraints": prompt_ir.diff.added_constraints,
|
|
197
|
+
"selected_capabilities": prompt_ir.diff.selected_capabilities,
|
|
198
|
+
"verification_directives": prompt_ir.diff.added_verification
|
|
199
|
+
},
|
|
200
|
+
"optimized_prompt": rendered_prompt
|
|
201
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mahmoud Abdelhameid (Develper.net@gmail.com). All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Semantic Intent Analyzer
|
|
6
|
+
========================
|
|
7
|
+
Dissects user prompts into primary intent, explicit constraints, input expectations,
|
|
8
|
+
and required deliverables while guarding against intent alteration.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from typing import Dict, Any, List
|
|
13
|
+
|
|
14
|
+
class IntentAnalyzer:
|
|
15
|
+
|
|
16
|
+
ACTION_VERBS = [
|
|
17
|
+
"build", "create", "implement", "design", "refactor", "fix",
|
|
18
|
+
"debug", "audit", "optimize", "test", "explain", "review", "migrate"
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
@classmethod
|
|
22
|
+
def analyze(cls, raw_prompt: str) -> Dict[str, Any]:
|
|
23
|
+
cleaned = raw_prompt.strip()
|
|
24
|
+
lines = [line.strip() for line in cleaned.splitlines() if line.strip()]
|
|
25
|
+
|
|
26
|
+
primary_intent = lines[0] if lines else cleaned
|
|
27
|
+
action_verb = "execute"
|
|
28
|
+
for v in cls.ACTION_VERBS:
|
|
29
|
+
if re.search(rf"\b{v}\b", primary_intent, re.IGNORECASE):
|
|
30
|
+
action_verb = v.lower()
|
|
31
|
+
break
|
|
32
|
+
|
|
33
|
+
# Detect explicit user constraints (e.g., using ..., with ..., do not ...)
|
|
34
|
+
constraints = []
|
|
35
|
+
negative_constraints = []
|
|
36
|
+
|
|
37
|
+
# Look for negative directives
|
|
38
|
+
neg_matches = re.findall(r"\b(?:do not|don't|never|without|avoid)\s+([^,.;\n]+)", cleaned, re.IGNORECASE)
|
|
39
|
+
for nm in neg_matches:
|
|
40
|
+
negative_constraints.append(f"Do not {nm.strip()}")
|
|
41
|
+
|
|
42
|
+
# Look for explicit technology or pattern constraints
|
|
43
|
+
tech_matches = re.findall(r"\b(?:using|with|in)\s+([A-Za-z0-9_\-\+\#\.\s]+?)(?:,|\.|\n|and|$)", cleaned, re.IGNORECASE)
|
|
44
|
+
for tm in tech_matches:
|
|
45
|
+
item = tm.strip()
|
|
46
|
+
if len(item) > 1 and item.lower() not in ["the", "a", "an", "this", "these"]:
|
|
47
|
+
constraints.append(f"Utilize {item}")
|
|
48
|
+
|
|
49
|
+
# Formulate a crisp objective sentence
|
|
50
|
+
objective = primary_intent
|
|
51
|
+
if not objective.endswith("."):
|
|
52
|
+
objective += "."
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
"primary_intent": primary_intent,
|
|
56
|
+
"action_verb": action_verb,
|
|
57
|
+
"objective": objective,
|
|
58
|
+
"explicit_constraints": constraints,
|
|
59
|
+
"negative_constraints": negative_constraints,
|
|
60
|
+
"raw_text": cleaned
|
|
61
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mahmoud Abdelhameid (Develper.net@gmail.com). All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Core Data Models and Normalized Schemas
|
|
6
|
+
=======================================
|
|
7
|
+
Defines common dataclasses for capabilities, discovered resources, host runtime
|
|
8
|
+
specifications, prompt intermediate representations, and critique results.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import List, Dict, Any, Optional, Set
|
|
13
|
+
from enum import Enum
|
|
14
|
+
|
|
15
|
+
class ResourceType(str, Enum):
|
|
16
|
+
SKILL = "skill"
|
|
17
|
+
MCP = "mcp"
|
|
18
|
+
CONNECTOR = "connector"
|
|
19
|
+
PLUGIN = "plugin"
|
|
20
|
+
BUILTIN_TOOL = "tool"
|
|
21
|
+
WEB_RESOURCE = "web_resource"
|
|
22
|
+
DOCUMENTATION = "documentation"
|
|
23
|
+
|
|
24
|
+
class CapabilityStatus(str, Enum):
|
|
25
|
+
AVAILABLE = "available"
|
|
26
|
+
UNAVAILABLE = "unavailable"
|
|
27
|
+
UNKNOWN = "unknown"
|
|
28
|
+
HOST_DECLARED = "host_declared"
|
|
29
|
+
RUNTIME_DETECTED = "runtime_detected"
|
|
30
|
+
INFERRED = "inferred"
|
|
31
|
+
|
|
32
|
+
class McpServerStatus(str, Enum):
|
|
33
|
+
CONFIGURED = "CONFIGURED"
|
|
34
|
+
PARSED = "PARSED"
|
|
35
|
+
REACHABLE = "REACHABLE"
|
|
36
|
+
INITIALIZED = "INITIALIZED"
|
|
37
|
+
TOOLS_DISCOVERED = "TOOLS_DISCOVERED"
|
|
38
|
+
|
|
39
|
+
class RiskLevel(str, Enum):
|
|
40
|
+
NO_SIDE_EFFECT = "NO_SIDE_EFFECT"
|
|
41
|
+
LOW_RISK = "LOW_RISK"
|
|
42
|
+
EXTERNAL_SIDE_EFFECT = "EXTERNAL_SIDE_EFFECT"
|
|
43
|
+
DESTRUCTIVE = "DESTRUCTIVE"
|
|
44
|
+
|
|
45
|
+
class RequirementCategory(str, Enum):
|
|
46
|
+
USER_EXPLICIT = "USER_EXPLICIT"
|
|
47
|
+
DERIVED_NECESSITY = "DERIVED_NECESSITY"
|
|
48
|
+
PROJECT_CONSTRAINT = "PROJECT_CONSTRAINT"
|
|
49
|
+
SECURITY_REQUIREMENT = "SECURITY_REQUIREMENT"
|
|
50
|
+
VERIFICATION_REQUIREMENT = "VERIFICATION_REQUIREMENT"
|
|
51
|
+
OPTIONAL_RECOMMENDATION = "OPTIONAL_RECOMMENDATION"
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class ClassifiedRequirement:
|
|
55
|
+
text: str
|
|
56
|
+
category: RequirementCategory
|
|
57
|
+
source: str = "intent"
|
|
58
|
+
|
|
59
|
+
@dataclass
|
|
60
|
+
class Capability:
|
|
61
|
+
name: str
|
|
62
|
+
domain: str = "general"
|
|
63
|
+
importance: float = 1.0 # 0.0 - 1.0
|
|
64
|
+
dependencies: List[str] = field(default_factory=list)
|
|
65
|
+
description: str = ""
|
|
66
|
+
|
|
67
|
+
@dataclass
|
|
68
|
+
class Resource:
|
|
69
|
+
id: str
|
|
70
|
+
name: str
|
|
71
|
+
type: ResourceType
|
|
72
|
+
source: str # local, registry, host, web
|
|
73
|
+
capabilities: List[str] = field(default_factory=list)
|
|
74
|
+
location: Optional[str] = None
|
|
75
|
+
relevance: float = 5.0 # 0.0 - 10.0
|
|
76
|
+
capability_match: float = 5.0 # 0.0 - 10.0
|
|
77
|
+
quality: float = 5.0 # 0.0 - 10.0
|
|
78
|
+
trust: float = 5.0 # 0.0 - 10.0 (security/integrity)
|
|
79
|
+
reputation: float = 5.0 # 0.0 - 10.0 (stars/downloads/community)
|
|
80
|
+
compatibility: float = 8.0 # 0.0 - 10.0
|
|
81
|
+
freshness: float = 5.0 # 0.0 - 10.0
|
|
82
|
+
overhead: float = 2.0 # 0.0 - 10.0
|
|
83
|
+
risk: float = 1.0 # 0.0 - 10.0
|
|
84
|
+
risk_level: RiskLevel = RiskLevel.LOW_RISK
|
|
85
|
+
permissions: List[str] = field(default_factory=list)
|
|
86
|
+
metadata: Dict[str, Any] = field(default_factory=dict)
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def utility_score(self) -> float:
|
|
90
|
+
"""
|
|
91
|
+
Authoritative formula from references/scoring_rubric.md:
|
|
92
|
+
Utility = (0.25*R + 0.25*M + 0.15*Q + 0.15*T + 0.10*C + 0.05*F) - (0.10*O + 0.20*K)
|
|
93
|
+
"""
|
|
94
|
+
pos = (
|
|
95
|
+
0.25 * self.relevance +
|
|
96
|
+
0.25 * self.capability_match +
|
|
97
|
+
0.15 * self.quality +
|
|
98
|
+
0.15 * self.trust +
|
|
99
|
+
0.10 * self.compatibility +
|
|
100
|
+
0.05 * self.freshness
|
|
101
|
+
)
|
|
102
|
+
neg = (0.10 * self.overhead) + (0.20 * self.risk)
|
|
103
|
+
return round(pos - neg, 3)
|
|
104
|
+
|
|
105
|
+
@dataclass
|
|
106
|
+
class HostCapabilityItem:
|
|
107
|
+
capability: str
|
|
108
|
+
status: CapabilityStatus
|
|
109
|
+
confidence: float
|
|
110
|
+
details: Dict[str, Any] = field(default_factory=dict)
|
|
111
|
+
|
|
112
|
+
@dataclass
|
|
113
|
+
class ClassificationReport:
|
|
114
|
+
level: int # 0 to 4
|
|
115
|
+
confidence: float
|
|
116
|
+
signals: List[str]
|
|
117
|
+
reasoning: str
|
|
118
|
+
|
|
119
|
+
@dataclass
|
|
120
|
+
class CritiqueFinding:
|
|
121
|
+
dimension: str
|
|
122
|
+
passed: bool
|
|
123
|
+
score: float
|
|
124
|
+
finding: str
|
|
125
|
+
recommendation: str
|
|
126
|
+
|
|
127
|
+
@dataclass
|
|
128
|
+
class CritiqueReport:
|
|
129
|
+
passed: bool
|
|
130
|
+
score: float
|
|
131
|
+
confidence: float
|
|
132
|
+
findings: List[CritiqueFinding]
|
|
133
|
+
critical_issues: List[str] = field(default_factory=list)
|
|
134
|
+
recommendations: List[str] = field(default_factory=list)
|
|
135
|
+
|
|
136
|
+
@dataclass
|
|
137
|
+
class PromptDiff:
|
|
138
|
+
removed_ambiguities: List[str] = field(default_factory=list)
|
|
139
|
+
added_constraints: List[str] = field(default_factory=list)
|
|
140
|
+
added_verification: List[str] = field(default_factory=list)
|
|
141
|
+
selected_capabilities: List[str] = field(default_factory=list)
|
|
142
|
+
preserved_intent_summary: str = ""
|
|
143
|
+
|
|
144
|
+
@dataclass
|
|
145
|
+
class PromptIR:
|
|
146
|
+
raw_prompt: str
|
|
147
|
+
role: str = ""
|
|
148
|
+
objective: str = ""
|
|
149
|
+
context: str = ""
|
|
150
|
+
categorized_requirements: List[ClassifiedRequirement] = field(default_factory=list)
|
|
151
|
+
constraints: List[str] = field(default_factory=list)
|
|
152
|
+
negative_constraints: List[str] = field(default_factory=list)
|
|
153
|
+
optional_recommendations: List[str] = field(default_factory=list)
|
|
154
|
+
required_capabilities: List[str] = field(default_factory=list)
|
|
155
|
+
selected_resources: List[Resource] = field(default_factory=list)
|
|
156
|
+
implementation_requirements: List[str] = field(default_factory=list)
|
|
157
|
+
edge_cases: List[str] = field(default_factory=list)
|
|
158
|
+
verification_directives: List[str] = field(default_factory=list)
|
|
159
|
+
completion_criteria: List[str] = field(default_factory=list)
|
|
160
|
+
phased_execution: List[Dict[str, Any]] = field(default_factory=list)
|
|
161
|
+
diff: PromptDiff = field(default_factory=PromptDiff)
|
|
162
|
+
depth: int = 1
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mahmoud Abdelhameid (Develper.net@gmail.com). All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
from .semantic_pass import SemanticPass
|
|
5
|
+
from .execution_pass import ExecutionPass
|
|
6
|
+
from .optimizer import TwoPassOptimizer
|
|
7
|
+
|
|
8
|
+
__all__ = ["SemanticPass", "ExecutionPass", "TwoPassOptimizer"]
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mahmoud Abdelhameid (Develper.net@gmail.com). All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Pass 2 — Execution Optimization
|
|
6
|
+
===============================
|
|
7
|
+
Binds selected capabilities, discovered tools, phased execution milestones,
|
|
8
|
+
and repository-aware verification directives.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from typing import List, Dict, Any
|
|
12
|
+
from ..models import PromptIR, Resource
|
|
13
|
+
|
|
14
|
+
class ExecutionPass:
|
|
15
|
+
|
|
16
|
+
@classmethod
|
|
17
|
+
def execute(cls, prompt_ir: PromptIR, selected_resources: List[Resource], verification_cmds: List[str]) -> PromptIR:
|
|
18
|
+
prompt_ir.selected_resources = selected_resources
|
|
19
|
+
prompt_ir.diff.selected_capabilities = [r.name for r in selected_resources]
|
|
20
|
+
|
|
21
|
+
# 1. Bind Verification Commands
|
|
22
|
+
prompt_ir.verification_directives = verification_cmds
|
|
23
|
+
prompt_ir.diff.added_verification = verification_cmds
|
|
24
|
+
|
|
25
|
+
# 2. Build Phased Milestones (for Level >= 2)
|
|
26
|
+
if prompt_ir.depth >= 2:
|
|
27
|
+
prompt_ir.phased_execution = [
|
|
28
|
+
{
|
|
29
|
+
"phase": 1,
|
|
30
|
+
"title": "Baseline Inspection",
|
|
31
|
+
"goal": "Verify existing tests and repository conventions prior to modification."
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
"phase": 2,
|
|
35
|
+
"title": "Contract & Schema Definition",
|
|
36
|
+
"goal": "Establish immutable interfaces, DTOs, and validation boundaries."
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
"phase": 3,
|
|
40
|
+
"title": "Core Implementation",
|
|
41
|
+
"goal": "Implement business logic following additive change standards."
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
"phase": 4,
|
|
45
|
+
"title": "Verification & Static Analysis",
|
|
46
|
+
"goal": "Run typechecking, unit/e2e tests, and regression verification."
|
|
47
|
+
}
|
|
48
|
+
]
|
|
49
|
+
else:
|
|
50
|
+
prompt_ir.phased_execution = []
|
|
51
|
+
|
|
52
|
+
return prompt_ir
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mahmoud Abdelhameid (Develper.net@gmail.com). All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Two-Pass Optimizer Orchestrator
|
|
6
|
+
===============================
|
|
7
|
+
Coordinates semantic and execution passes, formats final structured prompts,
|
|
8
|
+
and renders concise prompt diffs.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from typing import List, Dict, Any
|
|
12
|
+
from ..models import PromptIR, Resource, ClassificationReport
|
|
13
|
+
from .semantic_pass import SemanticPass
|
|
14
|
+
from .execution_pass import ExecutionPass
|
|
15
|
+
|
|
16
|
+
class TwoPassOptimizer:
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
def optimize(
|
|
20
|
+
cls,
|
|
21
|
+
raw_prompt: str,
|
|
22
|
+
classification: ClassificationReport,
|
|
23
|
+
selected_resources: List[Resource],
|
|
24
|
+
verification_cmds: List[str]
|
|
25
|
+
) -> PromptIR:
|
|
26
|
+
# Initialize PromptIR
|
|
27
|
+
prompt_ir = PromptIR(
|
|
28
|
+
raw_prompt=raw_prompt,
|
|
29
|
+
objective=raw_prompt.strip(),
|
|
30
|
+
depth=classification.level
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
# Pass 1: Semantic Clarification
|
|
34
|
+
prompt_ir = SemanticPass.execute(prompt_ir, classification)
|
|
35
|
+
|
|
36
|
+
# Pass 2: Execution Binding
|
|
37
|
+
prompt_ir = ExecutionPass.execute(prompt_ir, selected_resources, verification_cmds)
|
|
38
|
+
|
|
39
|
+
return prompt_ir
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def render_prompt(cls, ir: PromptIR) -> str:
|
|
43
|
+
"""
|
|
44
|
+
Renders PromptIR into canonical prompt format.
|
|
45
|
+
"""
|
|
46
|
+
lines = []
|
|
47
|
+
lines.append(f"ROLE:\n{ir.role}\n")
|
|
48
|
+
lines.append(f"OBJECTIVE:\n{ir.objective}\n")
|
|
49
|
+
|
|
50
|
+
if ir.context:
|
|
51
|
+
lines.append(f"CONTEXT & REPO STATE:\n{ir.context}\n")
|
|
52
|
+
|
|
53
|
+
if ir.constraints or ir.negative_constraints:
|
|
54
|
+
lines.append("CONSTRAINTS & NON-NEGOTIABLES:")
|
|
55
|
+
for c in ir.constraints:
|
|
56
|
+
lines.append(f"- {c}")
|
|
57
|
+
for nc in ir.negative_constraints:
|
|
58
|
+
lines.append(f"- {nc}")
|
|
59
|
+
lines.append("")
|
|
60
|
+
|
|
61
|
+
if ir.selected_resources:
|
|
62
|
+
lines.append("REQUIRED CAPABILITIES & TOOLS:")
|
|
63
|
+
for r in ir.selected_resources:
|
|
64
|
+
lines.append(f"- {r.name} ({r.type.value} from {r.source})")
|
|
65
|
+
lines.append("")
|
|
66
|
+
|
|
67
|
+
if ir.phased_execution:
|
|
68
|
+
lines.append("PHASED EXECUTION PLAN:")
|
|
69
|
+
for p in ir.phased_execution:
|
|
70
|
+
lines.append(f"Phase {p['phase']} — {p['title']}: {p['goal']}")
|
|
71
|
+
lines.append("")
|
|
72
|
+
|
|
73
|
+
if ir.verification_directives:
|
|
74
|
+
lines.append("VERIFICATION & TESTING DIRECTIVES:")
|
|
75
|
+
for v in ir.verification_directives:
|
|
76
|
+
lines.append(f"- {v}")
|
|
77
|
+
lines.append("")
|
|
78
|
+
|
|
79
|
+
if ir.completion_criteria:
|
|
80
|
+
lines.append("COMPLETION CRITERIA:")
|
|
81
|
+
for cc in ir.completion_criteria:
|
|
82
|
+
lines.append(f"- {cc}")
|
|
83
|
+
lines.append("")
|
|
84
|
+
|
|
85
|
+
return "\n".join(lines).strip()
|