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,113 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mahmoud Abdelhameid (Develper.net@gmail.com). All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Pass 1 — Semantic Optimization & Intent Preservation
|
|
6
|
+
====================================================
|
|
7
|
+
Infers accurate personas from actual task content rather than arbitrary level numbers.
|
|
8
|
+
Categorizes requirements into USER_EXPLICIT, PROJECT_CONSTRAINT, SECURITY_REQUIREMENT,
|
|
9
|
+
and OPTIONAL_RECOMMENDATION without inventing unrequested mandatory burdens.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from typing import Dict, Any, List
|
|
14
|
+
from ..models import PromptIR, ClassificationReport, ClassifiedRequirement, RequirementCategory
|
|
15
|
+
|
|
16
|
+
class SemanticPass:
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
def infer_task_role(cls, prompt_text: str, level: int) -> str:
|
|
20
|
+
"""
|
|
21
|
+
Derives an appropriate role from actual task content instead of arbitrary level tier.
|
|
22
|
+
"""
|
|
23
|
+
lower = prompt_text.lower()
|
|
24
|
+
|
|
25
|
+
# Beginner or educational queries
|
|
26
|
+
if re.search(r"\b(?:beginner|explain|tutorial|what is|how does)\b", lower):
|
|
27
|
+
return "Technical Mentor & Software Specialist"
|
|
28
|
+
|
|
29
|
+
# Security & Auth domains
|
|
30
|
+
if re.search(r"\b(?:auth|authentication|oauth|jwt|security|crypto|asvs|penetration)\b", lower):
|
|
31
|
+
return "Application Security & Authentication Specialist"
|
|
32
|
+
|
|
33
|
+
# Performance & Memory
|
|
34
|
+
if re.search(r"\b(?:memory leak|profiling|heap|garbage collect|latency|optimization)\b", lower):
|
|
35
|
+
return "Runtime Performance & Diagnostics Specialist"
|
|
36
|
+
|
|
37
|
+
# Frontend & UI
|
|
38
|
+
if re.search(r"\b(?:react|vue|ui|frontend|css|tailwind|playwright|cypress)\b", lower):
|
|
39
|
+
return "Frontend Systems & QA Automation Engineer"
|
|
40
|
+
|
|
41
|
+
# Backend & APIs
|
|
42
|
+
if re.search(r"\b(?:nestjs|fastify|express|rest api|graphql|grpc|endpoint|microservices)\b", lower):
|
|
43
|
+
return "Backend Services & API Architect"
|
|
44
|
+
|
|
45
|
+
# Multi-System SaaS
|
|
46
|
+
if level >= 4 or "saas" in lower or "multi-tenant" in lower:
|
|
47
|
+
return "Distributed Systems & Cloud Architect"
|
|
48
|
+
|
|
49
|
+
# General engineering default
|
|
50
|
+
return "Senior Software Engineer"
|
|
51
|
+
|
|
52
|
+
@classmethod
|
|
53
|
+
def execute(cls, prompt_ir: PromptIR, classification: ClassificationReport) -> PromptIR:
|
|
54
|
+
# 1. Assign specialized persona based on actual task domain
|
|
55
|
+
prompt_ir.role = cls.infer_task_role(prompt_ir.raw_prompt, classification.level)
|
|
56
|
+
prompt_ir.depth = classification.level
|
|
57
|
+
|
|
58
|
+
# 2. Extract and categorize requirements
|
|
59
|
+
classified_reqs: List[ClassifiedRequirement] = []
|
|
60
|
+
|
|
61
|
+
# A. USER_EXPLICIT
|
|
62
|
+
classified_reqs.append(ClassifiedRequirement(
|
|
63
|
+
text=prompt_ir.objective,
|
|
64
|
+
category=RequirementCategory.USER_EXPLICIT
|
|
65
|
+
))
|
|
66
|
+
|
|
67
|
+
# B. PROJECT_CONSTRAINT (respecting existing repo language and style)
|
|
68
|
+
repo_rule = "Follow the repository's existing language standards, compiler settings, and architectural patterns."
|
|
69
|
+
classified_reqs.append(ClassifiedRequirement(
|
|
70
|
+
text=repo_rule,
|
|
71
|
+
category=RequirementCategory.PROJECT_CONSTRAINT
|
|
72
|
+
))
|
|
73
|
+
if repo_rule not in prompt_ir.constraints:
|
|
74
|
+
prompt_ir.constraints.append(repo_rule)
|
|
75
|
+
prompt_ir.diff.added_constraints.append(repo_rule)
|
|
76
|
+
|
|
77
|
+
additive_rule = "Additive Change Policy: Preserve existing working functionality and public contracts."
|
|
78
|
+
classified_reqs.append(ClassifiedRequirement(
|
|
79
|
+
text=additive_rule,
|
|
80
|
+
category=RequirementCategory.PROJECT_CONSTRAINT
|
|
81
|
+
))
|
|
82
|
+
if additive_rule not in prompt_ir.constraints:
|
|
83
|
+
prompt_ir.constraints.append(additive_rule)
|
|
84
|
+
prompt_ir.diff.added_constraints.append(additive_rule)
|
|
85
|
+
|
|
86
|
+
# C. SECURITY_REQUIREMENT
|
|
87
|
+
if classification.level >= 3 or any(w in prompt_ir.raw_prompt.lower() for w in ["auth", "security", "token", "password", "payment"]):
|
|
88
|
+
sec_rule = "Security: Sanitize all untrusted inputs, parameterize queries, and prevent credential exposure."
|
|
89
|
+
classified_reqs.append(ClassifiedRequirement(
|
|
90
|
+
text=sec_rule,
|
|
91
|
+
category=RequirementCategory.SECURITY_REQUIREMENT
|
|
92
|
+
))
|
|
93
|
+
if sec_rule not in prompt_ir.constraints:
|
|
94
|
+
prompt_ir.constraints.append(sec_rule)
|
|
95
|
+
|
|
96
|
+
# D. NEGATIVE CONSTRAINTS (Preventing unrequested scope changes)
|
|
97
|
+
negative_rules = [
|
|
98
|
+
"Do NOT introduce unapproved third-party dependencies.",
|
|
99
|
+
"Do NOT modify unrelated modules or existing configurations."
|
|
100
|
+
]
|
|
101
|
+
for nr in negative_rules:
|
|
102
|
+
if nr not in prompt_ir.negative_constraints:
|
|
103
|
+
prompt_ir.negative_constraints.append(nr)
|
|
104
|
+
|
|
105
|
+
# E. COMPLETION CRITERIA (emphasizing baseline regression prevention)
|
|
106
|
+
prompt_ir.completion_criteria = [
|
|
107
|
+
"All targeted functionality behaves as requested with zero regression against pre-existing baseline.",
|
|
108
|
+
"Code adheres strictly to project linting, typechecking, and formatting rules."
|
|
109
|
+
]
|
|
110
|
+
|
|
111
|
+
prompt_ir.categorized_requirements = classified_reqs
|
|
112
|
+
prompt_ir.diff.preserved_intent_summary = f"Preserved user intent: '{prompt_ir.objective}'"
|
|
113
|
+
return prompt_ir
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mahmoud Abdelhameid (Develper.net@gmail.com). All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
from .scoring_engine import ScoringEngine
|
|
5
|
+
from .deduplicator import CapabilityDeduplicator
|
|
6
|
+
|
|
7
|
+
__all__ = ["ScoringEngine", "CapabilityDeduplicator"]
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mahmoud Abdelhameid (Develper.net@gmail.com). All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Capability Deduplicator & Context Budgeter
|
|
6
|
+
==========================================
|
|
7
|
+
Eliminates overlapping capabilities and selects the most specialized, trusted candidates
|
|
8
|
+
under strict token and context budgets.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from typing import List, Set
|
|
12
|
+
from ..models import Resource
|
|
13
|
+
from .scoring_engine import ScoringEngine
|
|
14
|
+
|
|
15
|
+
class CapabilityDeduplicator:
|
|
16
|
+
|
|
17
|
+
@classmethod
|
|
18
|
+
def deduplicate(cls, candidates: List[Resource], max_count: int = 3, min_utility: float = 5.0) -> List[Resource]:
|
|
19
|
+
"""
|
|
20
|
+
Filters candidates below minimum utility threshold, sorts by rank,
|
|
21
|
+
and prevents activating multiple tools covering the exact same primary capability.
|
|
22
|
+
"""
|
|
23
|
+
ranked = ScoringEngine.rank_resources(candidates)
|
|
24
|
+
selected: List[Resource] = []
|
|
25
|
+
covered_capabilities: Set[str] = set()
|
|
26
|
+
|
|
27
|
+
for res in ranked:
|
|
28
|
+
if res.utility_score < min_utility:
|
|
29
|
+
continue
|
|
30
|
+
|
|
31
|
+
# Check overlap: does this resource provide already covered capabilities?
|
|
32
|
+
overlap = False
|
|
33
|
+
for cap in res.capabilities:
|
|
34
|
+
if cap in covered_capabilities:
|
|
35
|
+
overlap = True
|
|
36
|
+
break
|
|
37
|
+
|
|
38
|
+
# If not overlapping or if it provides significant new capability
|
|
39
|
+
if not overlap or len(selected) == 0:
|
|
40
|
+
selected.append(res)
|
|
41
|
+
covered_capabilities.update(res.capabilities)
|
|
42
|
+
|
|
43
|
+
if len(selected) >= max_count:
|
|
44
|
+
break
|
|
45
|
+
|
|
46
|
+
return selected
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mahmoud Abdelhameid (Develper.net@gmail.com). All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Authoritative Scoring Engine
|
|
6
|
+
============================
|
|
7
|
+
The SINGLE source of truth for capability utility calculations, directly implementing
|
|
8
|
+
the mathematical formula established in references/scoring_rubric.md.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from typing import List
|
|
12
|
+
from ..models import Resource
|
|
13
|
+
|
|
14
|
+
class ScoringEngine:
|
|
15
|
+
|
|
16
|
+
@classmethod
|
|
17
|
+
def calculate_utility(cls, resource: Resource) -> float:
|
|
18
|
+
"""
|
|
19
|
+
Formula:
|
|
20
|
+
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)
|
|
21
|
+
"""
|
|
22
|
+
return resource.utility_score
|
|
23
|
+
|
|
24
|
+
@classmethod
|
|
25
|
+
def rank_resources(cls, resources: List[Resource]) -> List[Resource]:
|
|
26
|
+
"""
|
|
27
|
+
Sorts candidates by utility score descending.
|
|
28
|
+
Tie-breaking: Higher Trust -> Higher Quality -> Lower Overhead.
|
|
29
|
+
"""
|
|
30
|
+
return sorted(
|
|
31
|
+
resources,
|
|
32
|
+
key=lambda r: (r.utility_score, r.trust, r.quality, -r.overhead),
|
|
33
|
+
reverse=True
|
|
34
|
+
)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mahmoud Abdelhameid (Develper.net@gmail.com). All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
from .trust_engine import TrustEngine
|
|
5
|
+
from .injection_detector import PromptInjectionDetector
|
|
6
|
+
from .secret_protector import SecretProtector
|
|
7
|
+
from .governance import InstallationGovernance
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"TrustEngine",
|
|
11
|
+
"PromptInjectionDetector",
|
|
12
|
+
"SecretProtector",
|
|
13
|
+
"InstallationGovernance"
|
|
14
|
+
]
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mahmoud Abdelhameid (Develper.net@gmail.com). All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Installation Governance & Permission Gate
|
|
6
|
+
=========================================
|
|
7
|
+
Enforces the 'Never Install Blindly' mandate and governs tool invocation side-effects.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from typing import Dict, Any, Optional
|
|
11
|
+
from ..models import Resource, RiskLevel
|
|
12
|
+
|
|
13
|
+
class InstallationGovernance:
|
|
14
|
+
|
|
15
|
+
@classmethod
|
|
16
|
+
def evaluate_installation(cls, resource: Resource) -> Dict[str, Any]:
|
|
17
|
+
"""
|
|
18
|
+
Calculates whether a discovered external capability may be recommended or installed.
|
|
19
|
+
Decision rule: Expected Value > (Risk + Overhead)
|
|
20
|
+
"""
|
|
21
|
+
expected_value = (resource.capability_match * 0.4) + (resource.quality * 0.3) + (resource.relevance * 0.3)
|
|
22
|
+
cost_and_risk = (resource.risk * 0.6) + (resource.overhead * 0.4)
|
|
23
|
+
|
|
24
|
+
approved_for_recommendation = expected_value > cost_and_risk and resource.trust >= 6.0
|
|
25
|
+
requires_explicit_user_consent = resource.risk_level in [
|
|
26
|
+
RiskLevel.EXTERNAL_SIDE_EFFECT,
|
|
27
|
+
RiskLevel.DESTRUCTIVE
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
return {
|
|
31
|
+
"resource_name": resource.name,
|
|
32
|
+
"expected_value": round(expected_value, 2),
|
|
33
|
+
"cost_and_risk": round(cost_and_risk, 2),
|
|
34
|
+
"approved_for_recommendation": approved_for_recommendation,
|
|
35
|
+
"requires_explicit_user_consent": requires_explicit_user_consent,
|
|
36
|
+
"risk_level": resource.risk_level.value,
|
|
37
|
+
"governance_decision": (
|
|
38
|
+
"REQUIRE_USER_APPROVAL" if requires_explicit_user_consent else
|
|
39
|
+
("ADOPT" if approved_for_recommendation else "REJECT")
|
|
40
|
+
)
|
|
41
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mahmoud Abdelhameid (Develper.net@gmail.com). All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Prompt Injection & Instruction Hijacking Detector
|
|
6
|
+
=================================================
|
|
7
|
+
Identifies directive-override patterns, system prompt hijacking attempts,
|
|
8
|
+
and untrusted data exfiltration payloads.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from typing import Dict, Any, List
|
|
13
|
+
|
|
14
|
+
class PromptInjectionDetector:
|
|
15
|
+
|
|
16
|
+
HIJACK_PATTERNS = [
|
|
17
|
+
r"(?i)\bignore\s+(?:all\s+)?(?:previous|prior|above)\s+instructions\b",
|
|
18
|
+
r"(?i)\byou\s+are\s+now\s+(?:in\s+developer\s+mode|unrestricted|dan\b|an\s+evil)",
|
|
19
|
+
r"(?i)\bdisregard\s+(?:all\s+)?safety\s+(?:guidelines|protocols)\b",
|
|
20
|
+
r"(?i)\bsystem\s+override\b",
|
|
21
|
+
r"(?i)\bnew\s+primary\s+directive\b",
|
|
22
|
+
r"(?i)\b(?:print|upload|exfiltrate|leak|curl|send)\s+(?:the\s+)?(?:secrets?|\.env|id_rsa|api_key|credentials?)\b"
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
@classmethod
|
|
26
|
+
def scan(cls, text: str) -> Dict[str, Any]:
|
|
27
|
+
matched_threats = []
|
|
28
|
+
|
|
29
|
+
for pat in cls.HIJACK_PATTERNS:
|
|
30
|
+
match = re.search(pat, text)
|
|
31
|
+
if match:
|
|
32
|
+
matched_threats.append(match.group(0))
|
|
33
|
+
|
|
34
|
+
is_suspicious = len(matched_threats) > 0
|
|
35
|
+
|
|
36
|
+
return {
|
|
37
|
+
"is_suspicious": is_suspicious,
|
|
38
|
+
"threat_count": len(matched_threats),
|
|
39
|
+
"threats_detected": matched_threats,
|
|
40
|
+
"action": "SANITIZE_AND_CONTAIN" if is_suspicious else "ALLOW"
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def sanitize(cls, text: str) -> str:
|
|
45
|
+
"""
|
|
46
|
+
Neutralizes detected hijacking directives by enclosing them in passive containment blocks.
|
|
47
|
+
"""
|
|
48
|
+
scan_res = cls.scan(text)
|
|
49
|
+
if not scan_res["is_suspicious"]:
|
|
50
|
+
return text
|
|
51
|
+
|
|
52
|
+
sanitized = text
|
|
53
|
+
for threat in scan_res["threats_detected"]:
|
|
54
|
+
sanitized = re.sub(
|
|
55
|
+
re.escape(threat),
|
|
56
|
+
f"[REDACTED_ADVERSARIAL_DIRECTIVE: '{threat}']",
|
|
57
|
+
sanitized,
|
|
58
|
+
flags=re.IGNORECASE
|
|
59
|
+
)
|
|
60
|
+
return sanitized
|
|
@@ -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
|
+
Secret & Credential Protector
|
|
6
|
+
=============================
|
|
7
|
+
Detects plaintext secrets, API keys, private tokens, and database passwords
|
|
8
|
+
using strict regex patterns and entropy analysis.
|
|
9
|
+
CRITICAL SAFETY INVARIANT: Never retains or serializes plaintext secret values.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from typing import Dict, Any, List
|
|
14
|
+
|
|
15
|
+
class SecretProtector:
|
|
16
|
+
|
|
17
|
+
SECRET_PATTERNS = [
|
|
18
|
+
# AWS Access Key
|
|
19
|
+
(r"\b(AKIA[0-9A-Z]{16})\b", "AWS_ACCESS_KEY"),
|
|
20
|
+
# GitHub Personal Access Token
|
|
21
|
+
(r"\b(gh[pousr]_[A-Za-z0-9_]{36,255})\b", "GITHUB_TOKEN"),
|
|
22
|
+
# OpenAI / Standard Bearer sk- keys
|
|
23
|
+
(r"\b(sk-[a-zA-Z0-9]{20,64})\b", "API_SECRET_KEY"),
|
|
24
|
+
# JWT Token pattern (three base64 chunks)
|
|
25
|
+
(r"\b(ey[A-Za-z0-9_-]{10,}\.ey[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})\b", "JWT_TOKEN"),
|
|
26
|
+
# Database connection strings with credentials
|
|
27
|
+
(r"(?i)\b([a-z]+:\/\/[a-zA-Z0-9_\-\.]+:[^@\s\/]+@[a-zA-Z0-9_\-\.]+:[0-9]+\/[a-zA-Z0-9_\-\.]+)\b", "DATABASE_CREDENTIALS"),
|
|
28
|
+
# Generic private key headers
|
|
29
|
+
(r"-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----[\s\S]+?-----END\s+(?:RSA\s+)?PRIVATE\s+KEY-----", "PRIVATE_KEY"),
|
|
30
|
+
# Generic password assignment
|
|
31
|
+
(r"(?i)\b(?:password|passwd|secret)\s*[:=]\s*['\"]([^'\"]{6,})['\"]", "PLAINTEXT_PASSWORD")
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
@classmethod
|
|
35
|
+
def find_secrets(cls, text: str) -> List[Dict[str, Any]]:
|
|
36
|
+
"""
|
|
37
|
+
Detects secrets and returns sanitized descriptor objects.
|
|
38
|
+
NEVER stores or leaks the raw plaintext secret string.
|
|
39
|
+
"""
|
|
40
|
+
found = []
|
|
41
|
+
for pattern, label in cls.SECRET_PATTERNS:
|
|
42
|
+
for match in re.finditer(pattern, text):
|
|
43
|
+
matched_val = match.group(1) if match.groups() else match.group(0)
|
|
44
|
+
# Form secure masked preview without retaining original payload
|
|
45
|
+
preview = matched_val[:3] + "..." + matched_val[-3:] if len(matched_val) > 6 else "***"
|
|
46
|
+
found.append({
|
|
47
|
+
"label": label,
|
|
48
|
+
"preview": preview,
|
|
49
|
+
"length": len(matched_val),
|
|
50
|
+
"redacted": True
|
|
51
|
+
})
|
|
52
|
+
return found
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def redact(cls, text: str) -> str:
|
|
56
|
+
redacted = text
|
|
57
|
+
for pattern, label in cls.SECRET_PATTERNS:
|
|
58
|
+
def _replace(match):
|
|
59
|
+
return f"[REDACTED_{label}]"
|
|
60
|
+
redacted = re.sub(pattern, _replace, redacted)
|
|
61
|
+
return redacted
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mahmoud Abdelhameid (Develper.net@gmail.com). All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Trust & Provenance Engine
|
|
6
|
+
=========================
|
|
7
|
+
Separates reputation signals (stars/downloads) from verified security/trust metrics.
|
|
8
|
+
Evaluates requested permissions, publisher domain provenance, and metadata.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from typing import Dict, Any, List
|
|
12
|
+
from ..models import Resource, RiskLevel, ResourceType
|
|
13
|
+
|
|
14
|
+
class TrustEngine:
|
|
15
|
+
|
|
16
|
+
VERIFIED_PUBLISHERS = {
|
|
17
|
+
"anthropics", "vercel-labs", "google", "microsoft", "github",
|
|
18
|
+
"nestjs", "facebook", "aws", "docker", "composiohq"
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
TRUSTED_DOMAINS = {
|
|
22
|
+
"docs.nestjs.com", "owasp.org", "react.dev", "go.dev", "python.org",
|
|
23
|
+
"typescriptlang.org", "nodejs.org", "postgresql.org", "redis.io",
|
|
24
|
+
"kafka.apache.org", "temporal.io", "neon.tech", "prisma.io"
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
@classmethod
|
|
28
|
+
def evaluate_resource_trust(cls, resource: Resource) -> Dict[str, Any]:
|
|
29
|
+
"""
|
|
30
|
+
Calculates distinct Reputation vs. Trust/Security scores using domain provenance and metadata.
|
|
31
|
+
"""
|
|
32
|
+
trust_factors = []
|
|
33
|
+
risk_flags = []
|
|
34
|
+
provenance_score = 5.0
|
|
35
|
+
|
|
36
|
+
# 1. Provenance from official domains (for Web Documentation)
|
|
37
|
+
domain = resource.metadata.get("domain", "")
|
|
38
|
+
if not domain and resource.location:
|
|
39
|
+
import urllib.parse
|
|
40
|
+
try:
|
|
41
|
+
domain = urllib.parse.urlparse(resource.location).hostname or ""
|
|
42
|
+
except Exception:
|
|
43
|
+
domain = ""
|
|
44
|
+
|
|
45
|
+
if domain in cls.TRUSTED_DOMAINS or any(domain.endswith(f".{td}") for td in cls.TRUSTED_DOMAINS):
|
|
46
|
+
trust_factors.append(f"Verified authoritative technical domain ({domain})")
|
|
47
|
+
provenance_score = 9.8
|
|
48
|
+
elif resource.type == ResourceType.DOCUMENTATION:
|
|
49
|
+
if domain.endswith(".org") or domain.endswith(".dev") or domain.endswith(".io"):
|
|
50
|
+
provenance_score = 8.5
|
|
51
|
+
else:
|
|
52
|
+
provenance_score = 7.0
|
|
53
|
+
|
|
54
|
+
# 2. Provenance from publisher names (for skills/packages)
|
|
55
|
+
publisher = resource.name.split("/")[0] if "/" in resource.name else ""
|
|
56
|
+
if publisher.lower() in cls.VERIFIED_PUBLISHERS:
|
|
57
|
+
trust_factors.append(f"Verified official ecosystem publisher ({publisher})")
|
|
58
|
+
provenance_score = max(provenance_score, 9.5)
|
|
59
|
+
|
|
60
|
+
if resource.source.startswith("local_builtin"):
|
|
61
|
+
trust_factors.append("Host agent built-in capability")
|
|
62
|
+
provenance_score = 10.0
|
|
63
|
+
elif resource.source.startswith("local"):
|
|
64
|
+
trust_factors.append("Local project/user verified file")
|
|
65
|
+
provenance_score = max(provenance_score, 8.5)
|
|
66
|
+
|
|
67
|
+
# 3. Permission and side-effect review
|
|
68
|
+
if any("write" in p.lower() or "exec" in p.lower() or "install" in p.lower() for p in resource.permissions):
|
|
69
|
+
risk_flags.append("Demands write/exec/install permissions")
|
|
70
|
+
permission_penalty = 1.5
|
|
71
|
+
else:
|
|
72
|
+
permission_penalty = 0.0
|
|
73
|
+
|
|
74
|
+
# Composite security trust score (0.0 to 10.0)
|
|
75
|
+
final_trust = max(1.0, min(10.0, provenance_score - permission_penalty))
|
|
76
|
+
|
|
77
|
+
# Determine strict RiskLevel
|
|
78
|
+
if "install_required" in resource.permissions:
|
|
79
|
+
risk_level = RiskLevel.EXTERNAL_SIDE_EFFECT
|
|
80
|
+
elif permission_penalty > 0:
|
|
81
|
+
risk_level = RiskLevel.LOW_RISK
|
|
82
|
+
else:
|
|
83
|
+
risk_level = RiskLevel.NO_SIDE_EFFECT
|
|
84
|
+
|
|
85
|
+
resource.trust = round(final_trust, 2)
|
|
86
|
+
resource.risk_level = risk_level
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
"resource_id": resource.id,
|
|
90
|
+
"provenance_score": provenance_score,
|
|
91
|
+
"security_trust_score": final_trust,
|
|
92
|
+
"reputation_score": resource.reputation,
|
|
93
|
+
"risk_level": risk_level.value,
|
|
94
|
+
"trust_factors": trust_factors,
|
|
95
|
+
"risk_flags": risk_flags
|
|
96
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# Copyright (c) 2026 Mahmoud Abdelhameid (Develper.net@gmail.com). All rights reserved.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Repository-Aware Verification Engine
|
|
6
|
+
====================================
|
|
7
|
+
Dynamically derives concrete test, build, lint, and typecheck commands from
|
|
8
|
+
actual repository configuration files, lockfiles, and declared scripts.
|
|
9
|
+
Prioritizes project-declared commands and guards against hallucinated toolchains.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import json
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import List, Dict, Any, Optional
|
|
16
|
+
|
|
17
|
+
class VerificationEngine:
|
|
18
|
+
|
|
19
|
+
@classmethod
|
|
20
|
+
def detect_package_manager(cls, root: Path) -> str:
|
|
21
|
+
# Check modern lockfiles in order of precedence
|
|
22
|
+
if (root / "bun.lockb").exists() or (root / "bun.lock").exists():
|
|
23
|
+
return "bun"
|
|
24
|
+
if (root / "pnpm-lock.yaml").exists():
|
|
25
|
+
return "pnpm"
|
|
26
|
+
if (root / "yarn.lock").exists():
|
|
27
|
+
return "yarn"
|
|
28
|
+
return "npm"
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
def derive_verification_directives(cls, workspace_root: Optional[Path] = None) -> List[str]:
|
|
32
|
+
root = workspace_root or Path.cwd()
|
|
33
|
+
directives: List[str] = []
|
|
34
|
+
|
|
35
|
+
# 1. Node.js / JavaScript / TypeScript Projects
|
|
36
|
+
pkg_json = root / "package.json"
|
|
37
|
+
if pkg_json.exists() and pkg_json.is_file():
|
|
38
|
+
try:
|
|
39
|
+
data = json.loads(pkg_json.read_text(encoding="utf-8", errors="replace"))
|
|
40
|
+
scripts = data.get("scripts", {})
|
|
41
|
+
pm = cls.detect_package_manager(root)
|
|
42
|
+
|
|
43
|
+
if "test" in scripts:
|
|
44
|
+
directives.append(f"Execute project test runner: {pm} test")
|
|
45
|
+
elif "test:unit" in scripts:
|
|
46
|
+
directives.append(f"Execute unit tests: {pm} run test:unit")
|
|
47
|
+
|
|
48
|
+
if "test:e2e" in scripts:
|
|
49
|
+
directives.append(f"Execute e2e integration suite: {pm} run test:e2e")
|
|
50
|
+
|
|
51
|
+
if "lint" in scripts:
|
|
52
|
+
directives.append(f"Run code linter: {pm} run lint")
|
|
53
|
+
|
|
54
|
+
if "build" in scripts:
|
|
55
|
+
directives.append(f"Run compilation build: {pm} run build")
|
|
56
|
+
|
|
57
|
+
# Only require typecheck if tsconfig exists AND typescript is installed/scripted
|
|
58
|
+
if (root / "tsconfig.json").exists():
|
|
59
|
+
if "typecheck" in scripts:
|
|
60
|
+
directives.append(f"Validate types: {pm} run typecheck")
|
|
61
|
+
else:
|
|
62
|
+
directives.append("Validate TypeScript types: npx tsc --noEmit")
|
|
63
|
+
except Exception:
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
# 2. Python Projects
|
|
67
|
+
pyproject = root / "pyproject.toml"
|
|
68
|
+
poetry_lock = root / "poetry.lock"
|
|
69
|
+
requirements = root / "requirements.txt"
|
|
70
|
+
|
|
71
|
+
if pyproject.exists() or requirements.exists() or poetry_lock.exists() or any(root.glob("*.py")):
|
|
72
|
+
if poetry_lock.exists():
|
|
73
|
+
directives.append("Execute Python tests: poetry run pytest")
|
|
74
|
+
elif pyproject.exists():
|
|
75
|
+
text = pyproject.read_text(encoding="utf-8", errors="replace")
|
|
76
|
+
if "pytest" in text:
|
|
77
|
+
directives.append("Execute Python tests: pytest")
|
|
78
|
+
else:
|
|
79
|
+
directives.append("Execute Python tests: python -m unittest discover")
|
|
80
|
+
else:
|
|
81
|
+
directives.append("Execute Python test suite: python -m unittest discover")
|
|
82
|
+
|
|
83
|
+
directives.append("Verify Python syntax and imports with standard compiler")
|
|
84
|
+
|
|
85
|
+
# 3. Rust Projects
|
|
86
|
+
cargo = root / "Cargo.toml"
|
|
87
|
+
if cargo.exists():
|
|
88
|
+
directives.append("Execute Rust test suite: cargo test")
|
|
89
|
+
directives.append("Run static analysis: cargo clippy -- -D warnings")
|
|
90
|
+
directives.append("Verify compilation: cargo check")
|
|
91
|
+
|
|
92
|
+
# 4. Go Projects
|
|
93
|
+
gomod = root / "go.mod"
|
|
94
|
+
if gomod.exists():
|
|
95
|
+
directives.append("Execute Go test suite: go test -v ./...")
|
|
96
|
+
directives.append("Verify package compilation: go build ./...")
|
|
97
|
+
|
|
98
|
+
# Baseline regression guard
|
|
99
|
+
directives.append("Verify zero new regressions introduced against pre-existing repository baseline")
|
|
100
|
+
|
|
101
|
+
return directives
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Capability Graph & Taxonomy Specification
|
|
2
|
+
|
|
3
|
+
This document formalizes the **Capability Graph** engine of `prompt-capability-optimizer`. Rather than matching keywords superficially, the engine decomposes user tasks into an ontology of technical capabilities, then maps those capabilities to the optimal combination of local skills, MCP tools, and engineering patterns.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## 1. Capability Ontology Hierarchy
|
|
8
|
+
|
|
9
|
+
All software engineering tasks decompose into five primary capability domains:
|
|
10
|
+
|
|
11
|
+
```text
|
|
12
|
+
TASK INTENT
|
|
13
|
+
│
|
|
14
|
+
┌──────────────┬─────────────┼─────────────┬──────────────┐
|
|
15
|
+
▼ ▼ ▼ ▼ ▼
|
|
16
|
+
[ Architecture ] [ Operations ] [ Security ] [ Data/State ] [ Quality/Test ]
|
|
17
|
+
│ │ │ │ │
|
|
18
|
+
├─ Framework ├─ CI/CD ├─ Auth/RBAC ├─ Relational ├─ Unit tests
|
|
19
|
+
├─ Patterns ├─ Docker ├─ Encryption ├─ Key-Value ├─ E2E/Integ
|
|
20
|
+
├─ Contracts ├─ Cloud/IaC ├─ Injection ├─ Migrations ├─ Static/Lint
|
|
21
|
+
└─ Boundaries └─ Monitor └─ Audit └─ Caching └─ Benchmark
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## 2. Dynamic Decomposition Rules
|
|
27
|
+
|
|
28
|
+
When a prompt is evaluated, the optimizer traverses the graph:
|
|
29
|
+
|
|
30
|
+
### Example Decomposition: "Build a real-time collaborative whiteboarding API"
|
|
31
|
+
```text
|
|
32
|
+
Goal: Real-time Whiteboarding API
|
|
33
|
+
├── [Data & State]
|
|
34
|
+
│ ├── Capability: Ephemeral state synchronization
|
|
35
|
+
│ │ └── Candidate: Redis Pub/Sub, WebSockets
|
|
36
|
+
│ └── Capability: Durable board storage
|
|
37
|
+
│ └── Candidate: PostgreSQL + JSONB or MongoDB
|
|
38
|
+
├── [Architecture & Protocol]
|
|
39
|
+
│ ├── Capability: Bidirectional socket streaming
|
|
40
|
+
│ │ └── Candidate: Socket.io, ws, or WebTransport
|
|
41
|
+
│ └── Capability: Operational Transformation / CRDT
|
|
42
|
+
│ └── Candidate: Yjs or Automerge algorithms
|
|
43
|
+
├── [Security]
|
|
44
|
+
│ ├── Capability: Room-level authorization
|
|
45
|
+
│ │ └── Candidate: JWT claims, tenant scoping
|
|
46
|
+
│ └── Capability: DoS & Message flood protection
|
|
47
|
+
│ └── Candidate: Token-bucket rate limiting
|
|
48
|
+
└── [Quality Assurance]
|
|
49
|
+
└── Capability: Concurrent socket load testing
|
|
50
|
+
└── Candidate: Artillery or k6
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## 3. Capability Matching & Graph Resolution
|
|
56
|
+
|
|
57
|
+
Once the capability nodes are extracted, the engine maps each node to available resources:
|
|
58
|
+
|
|
59
|
+
```text
|
|
60
|
+
Capability Node ───► 1. Exact Local Skill Match (Score: 10/10)
|
|
61
|
+
───► 2. Active MCP Tool Match (Score: 9/10)
|
|
62
|
+
───► 3. Verified Online Skill Registry Match (Score: 8/10)
|
|
63
|
+
───► 4. Official Upstream Documentation Pattern (Score: 7/10)
|
|
64
|
+
───► 5. Base LLM In-Context Domain Instruction (Score: 6/10)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
## 4. Conflict Resolution & Dependency Graph
|
|
70
|
+
|
|
71
|
+
Tasks often involve mutually exclusive technical options (e.g., REST vs. gRPC, TypeORM vs. Prisma).
|
|
72
|
+
|
|
73
|
+
1. **Resolution Precedence**:
|
|
74
|
+
- **User Explicit Choice**: Always honored as primary constraint.
|
|
75
|
+
- **Existing Repository Dependency**: If `package.json` has `prisma`, do not introduce `typeorm`.
|
|
76
|
+
- **Official Ecosystem Standard**: If starting from scratch, select the standard community tool (e.g., Fastify + Zod for high-throughput Node.js).
|
|
77
|
+
|
|
78
|
+
2. **Graph Pruning**:
|
|
79
|
+
- Capabilities that add zero value to the primary objective are pruned.
|
|
80
|
+
- Example: A request to "write an algorithmic sorter" does not need Docker, Kubernetes, or JWT auth capabilities.
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
**Author**: Mahmoud Abdelhameid ([LinkedIn](https://www.linkedin.com/in/mahmoud-abdelhameid-dev/) | [Email](mailto:Develper.net@gmail.com)) | **Copyright**: © 2026 Mahmoud Abdelhameid. All rights reserved. | **License**: MIT License
|