Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Breakthrough-overdrive-innovation skill harness — analyzes tasks for innovation potential."""

import json
import re
import sys
from pathlib import Path

INNOVATION_SIGNALS = {
"paradigm_shift": [r"\b(unified|universal|fundamental|first.principles|axiom)\b", r"\b(derive|prove|derive|theorem)\b"],
"novel_approach": [r"\b(novel|new|unprecedented|breakthrough|revolutionary)\b", r"\b(non.obvious|counter.intuitive|unexpected)\b"],
"cross_domain": [r"\b(physics|biology|chemistry|mathematics|information.theory)\b", r"\b(economics|psychology|neuroscience)\b"],
"high_impact": [r"\b(scale|universal|impact|transform|disrupt)\b", r"\b(fundamental|essential|critical)\b"],
"deep_analysis": [r"\b(derive|calculate|simulate|model|formalize)\b", r"\b(equation|formula|theorem|proof)\b"],
}

def read_prompt(file_path: str) -> str:
try:
return Path(file_path).read_text()
except Exception:
return ""

def analyze_innovation(prompt: str) -> dict:
prompt_lower = prompt.lower()
scores = {}

for category, patterns in INNOVATION_SIGNALS.items():
matches = []
for pattern in patterns:
matches.extend(re.findall(pattern, prompt_lower))
scores[category] = len(matches)

total = sum(scores.values())
innovation_score = min(100, total * 10)

suggestions = []
if scores["paradigm_shift"] > 0:
suggestions.append("This task involves fundamental concepts — ground in first principles")
if scores["novel_approach"] > 0:
suggestions.append("Novel approach detected — document assumptions and validate rigorously")
if scores["cross_domain"] > 0:
suggestions.append("Cross-domain task — consider analogies from related fields")
if scores["deep_analysis"] > 0:
suggestions.append("Deep analysis required — ensure mathematical rigor")
if not suggestions:
suggestions.append("Standard task — apply existing patterns and best practices")

return {
"analysis_type": "innovation",
"innovation_score": innovation_score,
"signal_scores": scores,
"total_signals": total,
"suggestions": suggestions,
"complexity": "breakthrough" if innovation_score > 70 else "advanced" if innovation_score > 40 else "standard",
}

def main():
prompt_file = None
for i, arg in enumerate(sys.argv):
if arg == "--prompt-file" and i + 1 < len(sys.argv):
prompt_file = sys.argv[i + 1]
break

prompt = read_prompt(prompt_file) if prompt_file else ""
if not prompt:
print(json.dumps({"status": "skipped", "reason": "No prompt provided"}))
sys.exit(0)

result = analyze_innovation(prompt)
print(json.dumps(result, indent=2))

if __name__ == "__main__":
main()
23 changes: 20 additions & 3 deletions .dreamcode/skills/chain-orchestrator/scripts/sensor_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ def load_config() -> dict:
# ── META SKILLS ──
"breakthrough-overdrive-innovation": {"needs": [], "triggers": ["neuro", "research", "deep-research"], "always": True},
"context-compactor": {"needs": [], "triggers": [], "always": False},
"effect": {"needs": [], "triggers": ["architecture", "code-hardener"], "always": False},
"exhaustive-crosscheck": {"needs": [], "triggers": ["neuro"], "always": False},
"neuro": {"needs": [], "triggers": ["model-router", "code-hardener"], "always": False},
"model-router": {"needs": ["neuro"], "triggers": [], "always": False},
Expand Down Expand Up @@ -637,15 +638,29 @@ def run_enforcement_checks(config: dict) -> str:
# ---------------------------------------------------------------------------

def emit_plan(chain_result: dict) -> str:
primary = "breakthrough-overdrive-innovation"
chain = chain_result["chain"]
# Determine actual mode from detected tasks
task_types = {t["task_type"] for t in chain_result.get("detected_tasks", [])}
INNOVATION_TASKS = {"debugging", "refactoring", "security", "performance", "architecture", "quantum", "automation"}
has_innovation = bool(task_types & INNOVATION_TASKS) or "breakthrough-overdrive-innovation" in chain
is_trivial = not task_types or task_types <= {"communication"}

primary = "breakthrough-overdrive-innovation" if has_innovation else (chain[0] if chain else "general")
supports = [s for s in chain if s != primary][:2]

if is_trivial:
mode = "TRIVIAL"
elif has_innovation:
mode = "DREAM_INNOVATION"
else:
mode = "STANDARD"

lines = [
"Skill Plan:",
f"- primary: {primary}",
f"- supports: {', '.join(supports)}",
"- automation: none",
"- mode: DREAM_INNOVATION",
f"- mode: {mode}",
f"- chain: {' → '.join(chain)}",
]
return "\n".join(lines)
Expand Down Expand Up @@ -834,7 +849,9 @@ def run_gate(prompt: str) -> dict:

# Social greeting bypass
if _is_social_greeting(prompt):
return {"is_social_greeting": True, "response": "Hey! What can I help you with?"}
output = f"{intent_block}\n\n{skill_block}"
print(output)
return {"is_social_greeting": True, "response": "Hey! What can I help you with?", "output": output}

# Stage 2.7: Dynamic Persona Generation
persona_block = generate_personas(chain_result, prompt)
Expand Down
71 changes: 71 additions & 0 deletions .dreamcode/skills/code-hardener/scripts/code_hardener_harness.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""Code-hardener skill harness — analyzes code for security and robustness issues."""

import json
import re
import sys
from pathlib import Path

SECURITY_PATTERNS = {
"sql_injection": {"pattern": r"(query|execute|raw)\s*\(\s*[\"'].*\+", "message": "Potential SQL injection — use parameterized queries", "severity": "high"},
"hardcoded_secret": {"pattern": r"(password|secret|api_key|token)\s*=\s*[\"'][^\"']+[\"']", "message": "Hardcoded secret — use environment variables", "severity": "critical"},
"eval_usage": {"pattern": r"\beval\s*\(", "message": "eval() usage — code injection risk", "severity": "high"},
"exec_usage": {"pattern": r"\bexec\s*\(", "message": "exec() usage — code injection risk", "severity": "high"},
"unsanitized_input": {"pattern": r"(req\.body|input|argv|args)\[", "message": "Unsanitized input — validate and sanitize", "severity": "medium"},
"missing_error_handler": {"pattern": r"\.then\([^)]+\)(?!\.catch)", "message": "Promise without .catch() — unhandled rejection", "severity": "medium"},
"prototype_pollution": {"pattern": r"Object\.assign\s*\(\s*(req|body|input)", "message": "Prototype pollution risk — validate keys", "severity": "high"},
"path_traversal": {"pattern": r"(readFile|readFileSync|open)\s*\([^)]*req\.", "message": "Potential path traversal — validate file paths", "severity": "high"},
}

def read_prompt(file_path: str) -> str:
try:
return Path(file_path).read_text()
except Exception:
return ""

def analyze_security(prompt: str) -> dict:
issues = []
lines = prompt.split("\n")

for line_num, line in enumerate(lines, 1):
for rule_id, rule in SECURITY_PATTERNS.items():
if re.search(rule["pattern"], line, re.IGNORECASE):
issues.append({
"rule": rule_id,
"line": line_num,
"severity": rule["severity"],
"message": rule["message"],
"source": line.strip()[:100],
})

severity_counts = {}
for issue in issues:
s = issue["severity"]
severity_counts[s] = severity_counts.get(s, 0) + 1

return {
"analysis_type": "security",
"total_issues": len(issues),
"by_severity": severity_counts,
"issues": issues[:50],
"lines_scanned": len(lines),
"recommendation": "Review all flagged issues. Prioritize critical/high severity items first.",
}

def main():
prompt_file = None
for i, arg in enumerate(sys.argv):
if arg == "--prompt-file" and i + 1 < len(sys.argv):
prompt_file = sys.argv[i + 1]
break

prompt = read_prompt(prompt_file) if prompt_file else ""
if not prompt:
print(json.dumps({"status": "skipped", "reason": "No prompt provided"}))
sys.exit(0)

result = analyze_security(prompt)
print(json.dumps(result, indent=2))

if __name__ == "__main__":
main()
65 changes: 65 additions & 0 deletions .dreamcode/skills/communication/scripts/communication_harness.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""Communication skill harness — analyzes documentation and comment quality."""

import json
import re
import sys
from pathlib import Path

def read_prompt(file_path: str) -> str:
try:
return Path(file_path).read_text()
except Exception:
return ""

def analyze_communication(prompt: str) -> dict:
lines = prompt.split("\n")
issues = []

for i, line in enumerate(lines, 1):
stripped = line.strip()
if not stripped:
continue

if len(stripped) > 200:
issues.append({"line": i, "type": "long_line", "message": f"Line too long ({len(stripped)} chars) — break into shorter segments"})

if re.match(r"^(//|/\*|\*|#)\s*[a-z]", stripped):
issues.append({"line": i, "type": "comment_capitalization", "message": "Comment should start with capital letter"})

if re.search(r"\b(very|really|basically|actually|just|simply)\b", stripped, re.IGNORECASE):
issues.append({"line": i, "type": "weak_language", "message": "Weak filler word — remove for clarity"})

has_readme = bool(re.search(r"#\s+\w+", prompt))
has_api_docs = bool(re.search(r"(API|endpoint|request|response|parameter)", prompt, re.IGNORECASE))
has_examples = bool(re.search(r"(example|e\.g\.|for instance|i\.e\.)", prompt, re.IGNORECASE))

return {
"analysis_type": "communication",
"total_issues": len(issues),
"issues": issues[:20],
"documentation_signals": {
"has_title": has_readme,
"has_api_docs": has_api_docs,
"has_examples": has_examples,
},
"readability_score": max(0, 100 - len(issues) * 3),
}

def main():
prompt_file = None
for i, arg in enumerate(sys.argv):
if arg == "--prompt-file" and i + 1 < len(sys.argv):
prompt_file = sys.argv[i + 1]
break

prompt = read_prompt(prompt_file) if prompt_file else ""
if not prompt:
print(json.dumps({"status": "skipped", "reason": "No prompt provided"}))
sys.exit(0)

result = analyze_communication(prompt)
print(json.dumps(result, indent=2))

if __name__ == "__main__":
main()
77 changes: 77 additions & 0 deletions .dreamcode/skills/debugging/scripts/debugging_harness.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#!/usr/bin/env python3
"""Debugging skill harness — analyzes prompts for bug patterns and suggests debugging strategies."""

import json
import re
import sys
from pathlib import Path

BUG_PATTERNS = {
"race_condition": ["concurrent", "race", "thread", "async", "parallel", "mutex", "lock", "deadlock"],
"memory_leak": ["memory", "leak", "heap", "alloc", "gc", "garbage", "retain"],
"null_reference": ["null", "undefined", "none", "optional", "nullable", "truthy", "falsy"],
"error_handling": ["catch", "except", "error", "throw", "panic", "unwrap", "recover"],
"type_safety": ["type", "cast", "any", "unknown", "coerce", "assert", "guard"],
"off_by_one": ["index", "loop", "range", "boundary", "slice", "length", "count"],
"state_management": ["state", "cache", "stale", "invalidat", "consistency", "sync"],
}

def read_prompt(file_path: str) -> str:
try:
return Path(file_path).read_text()
except Exception:
return ""

def analyze_prompt(prompt: str) -> dict:
prompt_lower = prompt.lower()
findings = []
strategies = []

for category, keywords in BUG_PATTERNS.items():
matches = [kw for kw in keywords if kw in prompt_lower]
if matches:
findings.append({"category": category, "matched_keywords": matches})

if not findings:
findings.append({"category": "general", "matched_keywords": ["general debugging"]})

strategy_map = {
"race_condition": "Add deterministic ordering. Use mutex/lock. Prefer single-writer pattern.",
"memory_leak": "Check reference cycles. Profile with heap snapshot. Ensure cleanup in finally/defer.",
"null_reference": "Add null checks. Use guard clauses. Prefer Result/Either types.",
"error_handling": "Ensure error propagation. Add context to errors. Don't swallow silently.",
"type_safety": "Add explicit type annotations. Use type guards. Avoid any/unknown casts.",
"off_by_one": "Check boundary conditions. Test with empty, single, and max-length inputs.",
"state_management": "Add cache invalidation. Verify consistency. Use immutable state.",
}

for finding in findings:
cat = finding["category"]
if cat in strategy_map:
strategies.append({"category": cat, "strategy": strategy_map[cat]})

return {
"analysis_type": "debugging",
"findings_count": len(findings),
"findings": findings,
"strategies": strategies,
"prompt_length": len(prompt),
}

def main():
prompt_file = None
for i, arg in enumerate(sys.argv):
if arg == "--prompt-file" and i + 1 < len(sys.argv):
prompt_file = sys.argv[i + 1]
break

prompt = read_prompt(prompt_file) if prompt_file else ""
if not prompt:
print(json.dumps({"status": "skipped", "reason": "No prompt provided"}))
sys.exit(0)

result = analyze_prompt(prompt)
print(json.dumps(result, indent=2))

if __name__ == "__main__":
main()
File renamed without changes.
23 changes: 22 additions & 1 deletion .dreamcode/skills/guardian-ai/scripts/guardian_ai.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,33 @@ def _find_project_root() -> Path:

# Load NEURO API config
def _load_env():
"""Load .env files for NEURO_API_KEY."""
"""Load .env files for NEURO_API_KEY.

Security checks:
- Refuses world-readable files (mode & 0o004) to prevent credential exposure
- Refuses world-writable files (mode & 0o002) to prevent injection attacks
- Logs a warning to stderr for unsafe permissions
"""
if os.environ.get("NEURO_API_KEY"):
return
for env_file in [".env.secret", ".env.neuro", ".env"]:
path = PROJECT_ROOT / env_file
if path.exists():
try:
import stat as _stat
file_mode = path.stat().st_mode
if file_mode & _stat.S_IROTH:
print(f"WARNING: {path} is world-readable ({oct(file_mode & 0o777)}). "
"Set permissions to 0600 (chmod 600). Refusing to load.",
file=sys.stderr)
continue
if file_mode & _stat.S_IWOTH:
print(f"WARNING: {path} is world-writable ({oct(file_mode & 0o777)}). "
"Set permissions to 0600 (chmod 600). Refusing to load.",
file=sys.stderr)
continue
except OSError:
continue
for line in path.read_text().splitlines():
line = line.strip()
if line and not line.startswith("#") and "=" in line:
Expand Down
Loading
Loading