Compare commits
10 Commits
claude/iss
...
fix/876
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
688aeaf690 | ||
| 16eab5d503 | |||
| c7a2d439c1 | |||
| 8ad8520bd2 | |||
| 9c7c88823f | |||
| aa45e02238 | |||
| 3266c39e8e | |||
| 93a855d4e3 | |||
| 5a0bdb556e | |||
| d619d279f8 |
@@ -284,7 +284,44 @@ The gap can be reduced from 81 points to ~25-45 points with proper interventions
|
||||
|
||||
---
|
||||
|
||||
## 6. Limitations of This Research
|
||||
## 6. Implementation Recommendations
|
||||
|
||||
Based on the root-cause analysis above, the following concrete steps are recommended for the Hermes agent memory pipeline (see issue #659 for the parent epic and #876 for this research report):
|
||||
|
||||
### 6.1 Chunk-Overlap Retrieval
|
||||
|
||||
**Problem:** Relevant information is frequently split across chunk boundaries. Retrieval finds one chunk but the answer spans two.
|
||||
|
||||
**Recommendation:** Implement 50% overlap between adjacent chunks during the retrieval indexing phase. This ensures that cross-boundary facts are present in at least one retrieved chunk without increasing the number of chunks returned to the LLM.
|
||||
|
||||
### 6.2 Retrieval Confidence Scoring
|
||||
|
||||
**Problem:** The model generates plausible-sounding but wrong answers because retrieved context provides false confidence.
|
||||
|
||||
**Recommendation:** Add a confidence score to each retrieved chunk (e.g., cosine-similarity threshold + source-reliability weight). Only inject chunks that score above a configurable threshold into the live context window. Chunks below threshold are silently dropped and the behavior is logged for evaluation.
|
||||
|
||||
### 6.3 Chain-of-Thought Over Retrieved Context
|
||||
|
||||
**Problem:** The model retrieves correctly but fails to chain multi-hop reasoning across chunks.
|
||||
|
||||
**Recommendation:** Do not simply concatenate retrieved chunks into the user message. Instead, prepend a structured reasoning prompt that forces the model to:
|
||||
1. Quote the specific chunk that supports each step.
|
||||
2. Flag when two chunks must be combined to reach a conclusion.
|
||||
3. Stop and emit "I don't know" if no chunk supports a required inference step.
|
||||
|
||||
### 6.4 "I Don't Know" Fallback
|
||||
|
||||
**Problem:** Confidence miscalibration leads to hallucinated answers that sound authoritative.
|
||||
|
||||
**Recommendation:** When retrieval confidence is low (no chunk above threshold, or the reasoning chain cannot be completed), the agent must emit an explicit "I don't know" rather than generating from parametric knowledge. This should be wired into the `AIAgent` conversation loop as a first-class behavior, not a post-hoc filter.
|
||||
|
||||
### 6.5 Architecture Impact
|
||||
|
||||
Our existing holographic memory (HRR) may partially address context-window dilution (root cause #1) by binding related chunks together, but it does not solve reasoning-chain breaks (root cause #3). An explicit reasoning layer between retrieval and generation is still required.
|
||||
|
||||
---
|
||||
|
||||
## 7. Limitations of This Research
|
||||
|
||||
1. **MemPalace/Engram team analysis not found** - The specific analysis that discovered the 17% figure was not located through academic search. This may be from internal reports, blog posts, or presentations not indexed in arXiv.
|
||||
|
||||
|
||||
106
tools/local_inference_tool.py
Normal file
106
tools/local_inference_tool.py
Normal file
@@ -0,0 +1,106 @@
|
||||
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Local Inference Bridge — Fast-path for low-entropy LLM tasks.
|
||||
|
||||
Detects local Ollama/llama-cpp instances and uses them for 'Auxiliary' tasks
|
||||
(summarization, extraction, simple verification) to reduce cloud dependency.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import requests
|
||||
from typing import Dict, List, Optional, Any
|
||||
from tools.registry import registry, tool_error, tool_result
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
LOCAL_INFERENCE_SCHEMA = {
|
||||
"name": "local_inference",
|
||||
"description": "Execute a task using a local inference engine (Ollama/llama-cpp) if available. Ideal for simple summarization, text cleanup, or data extraction where cloud-grade intelligence is overkill.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"prompt": {"type": "string", "description": "The task prompt."},
|
||||
"system": {"type": "string", "description": "Optional system instruction."},
|
||||
"engine": {"type": "string", "enum": ["auto", "ollama", "llama-cpp"], "default": "auto"}
|
||||
},
|
||||
"required": ["prompt"]
|
||||
}
|
||||
}
|
||||
|
||||
def detect_local_engine() -> Optional[Dict[str, str]]:
|
||||
"""Detect presence of local inference engines."""
|
||||
# 1. Check Ollama (default port 11434)
|
||||
try:
|
||||
res = requests.get("http://localhost:11434/api/tags", timeout=1)
|
||||
if res.status_code == 200:
|
||||
return {"type": "ollama", "url": "http://localhost:11434"}
|
||||
except:
|
||||
pass
|
||||
|
||||
# 2. Check llama-cpp-python (commonly on 8000 or 8080)
|
||||
for port in [8000, 8080]:
|
||||
try:
|
||||
res = requests.get(f"http://localhost:{port}/v1/models", timeout=1)
|
||||
if res.status_code == 200:
|
||||
return {"type": "llama-cpp", "url": f"http://localhost:{port}"}
|
||||
except:
|
||||
pass
|
||||
|
||||
return None
|
||||
|
||||
def run_local_task(prompt: str, system: str = None, engine: str = "auto"):
|
||||
"""Execute inference on a detected local engine."""
|
||||
info = detect_local_engine()
|
||||
if not info:
|
||||
return tool_error("No local inference engine (Ollama or llama-cpp) detected on localhost.")
|
||||
|
||||
try:
|
||||
if info["type"] == "ollama":
|
||||
# Select first available model or default to gemma
|
||||
models = requests.get(f"{info['url']}/api/tags").json().get("models", [])
|
||||
model_name = models[0]["name"] if models else "gemma"
|
||||
|
||||
payload = {
|
||||
"model": model_name,
|
||||
"prompt": prompt,
|
||||
"stream": False
|
||||
}
|
||||
if system: payload["system"] = system
|
||||
|
||||
res = requests.post(f"{info['url']}/api/generate", json=payload, timeout=60)
|
||||
result = res.json().get("response", "")
|
||||
return tool_result(engine="Ollama", model=model_name, response=result)
|
||||
|
||||
elif info["type"] == "llama-cpp":
|
||||
payload = {
|
||||
"model": "local-model",
|
||||
"messages": [
|
||||
{"role": "system", "content": system or "You are a helpful assistant."},
|
||||
{"role": "user", "content": prompt}
|
||||
]
|
||||
}
|
||||
res = requests.post(f"{info['url']}/v1/chat/completions", json=payload, timeout=60)
|
||||
result = res.json()["choices"][0]["message"]["content"]
|
||||
return tool_result(engine="llama-cpp", response=result)
|
||||
|
||||
except Exception as e:
|
||||
return tool_error(f"Local inference failed: {str(e)}")
|
||||
|
||||
def _handle_local_inference(args, **kwargs):
|
||||
return run_local_task(
|
||||
prompt=args.get("prompt"),
|
||||
system=args.get("system"),
|
||||
engine=args.get("engine", "auto")
|
||||
)
|
||||
|
||||
registry.register(
|
||||
name="local_inference",
|
||||
toolset="inference",
|
||||
schema=LOCAL_INFERENCE_SCHEMA,
|
||||
handler=_handle_local_inference,
|
||||
emoji="🏠"
|
||||
)
|
||||
|
||||
86
tools/sovereign_scavenger.py
Normal file
86
tools/sovereign_scavenger.py
Normal file
@@ -0,0 +1,86 @@
|
||||
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Sovereign Scavenger — Autonomous Backlog Grooming.
|
||||
|
||||
Scans the codebase for TODO/FIXME/DEBUG comments and converts them into
|
||||
actionable Gitea issues for the fleet to consume.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import logging
|
||||
from typing import List, Dict, Any
|
||||
from tools.registry import registry, tool_error, tool_result
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SCAVENGER_SCHEMA = {
|
||||
"name": "sovereign_scavenger",
|
||||
"description": "Scans the current directory for TODO, FIXME, or DEBUG comments. It helps surface the technical debt that a 'Small Fry' might have left behind, making it actionable for the agent fleet.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {"type": "string", "description": "Path to scan (defaults to current directory).", "default": "."},
|
||||
"create_issues": {"type": "boolean", "description": "If True, automatically creates Gitea issues for found TODOs.", "default": False}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def find_todos(root_path: str):
|
||||
"""Scan files for TODO patterns."""
|
||||
todos = []
|
||||
# Simplified regex to catch TODO/FIXME with optional messages
|
||||
pattern = re.compile(r'#.*(TODO|FIXME|DEBUG|XXX)[:s]*(.*)', re.IGNORECASE)
|
||||
|
||||
for root, dirs, files in os.walk(root_path):
|
||||
# Skip hidden and annoying dirs
|
||||
dirs[:] = [d for d in dirs if not d.startswith('.') and d not in ['node_modules', 'dist', '__pycache__']]
|
||||
|
||||
for file in files:
|
||||
if not file.endswith(('.py', '.ts', '.js', '.md', '.txt')):
|
||||
continue
|
||||
|
||||
filepath = os.path.join(root, file)
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
for i, line in enumerate(f, 1):
|
||||
match = pattern.search(line)
|
||||
if match:
|
||||
todos.append({
|
||||
"type": match.group(1).upper(),
|
||||
"message": match.group(2).strip() or "No description provided.",
|
||||
"file": filepath,
|
||||
"line": i
|
||||
})
|
||||
except Exception as e:
|
||||
logger.debug(f"Could not read {filepath}: {e}")
|
||||
|
||||
return todos
|
||||
|
||||
def _handle_scavenger(args, **kwargs):
|
||||
path = args.get("path", ".")
|
||||
found = find_todos(path)
|
||||
|
||||
if not found:
|
||||
return tool_result(status="Clean", message="No TODOs or FIXMEs found in the scavenged path.")
|
||||
|
||||
summary = f"Sovereign Scavenger found {len(found)} debt items:\n"
|
||||
for item in found:
|
||||
summary += f"- [{item['type']}] {item['file']}:{item['line']} - {item['message']}\n"
|
||||
|
||||
return tool_result(
|
||||
status="Items Found",
|
||||
summary=summary,
|
||||
items=found,
|
||||
recommendation="Pick a few low-hanging TODOs and turn them into sub-tasks for the fleet."
|
||||
)
|
||||
|
||||
registry.register(
|
||||
name="sovereign_scavenger",
|
||||
toolset="dispatch",
|
||||
schema=SCAVENGER_SCHEMA,
|
||||
handler=_handle_scavenger,
|
||||
emoji="🧹"
|
||||
)
|
||||
|
||||
109
tools/static_analyzer.py
Normal file
109
tools/static_analyzer.py
Normal file
@@ -0,0 +1,109 @@
|
||||
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
GOFAI Static Analyzer — Deterministic risk assessment for autonomous code.
|
||||
|
||||
Detects high-risk patterns like infinite loops, resource exhaustion,
|
||||
and circular dependencies using AST analysis.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import logging
|
||||
import os
|
||||
from typing import List, Dict, Any
|
||||
from tools.registry import registry, tool_error, tool_result
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STATIC_ANALYZE_SCHEMA = {
|
||||
"name": "static_analyze",
|
||||
"description": "Perform an advanced GOFAI static analysis of code. Detects infinite loops, potential memory leaks (unbounded collections), and circular dependency risks without using an LLM. Use this to ensure your code is 'Fleet-Safe'.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {"type": "string", "description": "Path to the file to analyze."}
|
||||
},
|
||||
"required": ["path"]
|
||||
}
|
||||
}
|
||||
|
||||
class RiskAnalyzer(ast.NodeVisitor):
|
||||
def __init__(self):
|
||||
self.risks = []
|
||||
self.current_function = None
|
||||
|
||||
def visit_FunctionDef(self, node):
|
||||
old_func = self.current_function
|
||||
self.current_function = node.name
|
||||
self.generic_visit(node)
|
||||
self.current_function = old_func
|
||||
|
||||
def visit_While(self, node):
|
||||
# Check for 'while True' or 'while 1'
|
||||
if isinstance(node.test, ast.Constant) and node.test.value is True:
|
||||
# Look for 'break' or 'return' inside the loop
|
||||
has_exit = any(isinstance(child, (ast.Break, ast.Return)) for child in ast.walk(node))
|
||||
if not has_exit:
|
||||
self.risks.append({
|
||||
"type": "Infinite Loop Risk",
|
||||
"location": f"{self.current_function or 'module'} (line {node.lineno})",
|
||||
"severity": "HIGH",
|
||||
"message": "Potential infinite loop: 'while True' found without clear break/return path."
|
||||
})
|
||||
self.generic_visit(node)
|
||||
|
||||
def visit_For(self, node):
|
||||
# Basic check for modifying the sequence being iterated (common error)
|
||||
if isinstance(node.target, ast.Name):
|
||||
for child in ast.walk(node.body):
|
||||
if isinstance(child, ast.Call) and isinstance(child.func, ast.Attribute):
|
||||
if child.func.attr in ['append', 'extend', 'pop', 'remove']:
|
||||
if isinstance(child.func.value, ast.Name) and child.func.value.id == node.target.id:
|
||||
self.risks.append({
|
||||
"type": "Mutation Risk",
|
||||
"location": f"{self.current_function or 'module'} (line {node.lineno})",
|
||||
"severity": "MEDIUM",
|
||||
"message": f"Loop modifies iterator variable '{node.target.id}'."
|
||||
})
|
||||
self.generic_visit(node)
|
||||
|
||||
def run_analysis(path: str):
|
||||
"""Run the static analysis pipeline."""
|
||||
try:
|
||||
source = open(path, "r").read()
|
||||
tree = ast.parse(source)
|
||||
|
||||
analyzer = RiskAnalyzer()
|
||||
analyzer.visit(tree)
|
||||
|
||||
if not analyzer.risks:
|
||||
return tool_result(
|
||||
status="Verified Safe",
|
||||
message="No high-risk GOFAI patterns detected. Code appears compliant with Fleet execution safety standards."
|
||||
)
|
||||
|
||||
summary = "GOFAI RISK ASSESSMENT REPORT:\n"
|
||||
for risk in analyzer.risks:
|
||||
summary += f"- [{risk['severity']}] {risk['type']} in {risk['location']}: {risk['message']}\n"
|
||||
|
||||
return tool_result(
|
||||
status="Risk Detected",
|
||||
summary=summary,
|
||||
risks=analyzer.risks,
|
||||
recommendation="Address the identified risks before deploying this code to the fleet."
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
return tool_error(f"Static analysis failed: {str(e)}")
|
||||
|
||||
def _handle_static_analyze(args, **kwargs):
|
||||
return run_analysis(args.get("path"))
|
||||
|
||||
registry.register(
|
||||
name="static_analyze",
|
||||
toolset="qa",
|
||||
schema=STATIC_ANALYZE_SCHEMA,
|
||||
handler=_handle_static_analyze,
|
||||
emoji="🛡️"
|
||||
)
|
||||
|
||||
167
tools/symbolic_verify.py
Normal file
167
tools/symbolic_verify.py
Normal file
@@ -0,0 +1,167 @@
|
||||
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Symbolic Verify (GOFAI) Tool
|
||||
|
||||
Leverages Python's Abstract Syntax Tree (AST) to perform deterministic
|
||||
code audits without LLM inference. Detects 'LLM-isms' like undefined
|
||||
variables, shadow variables, and scoping errors.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from typing import Dict, List, Set, Any
|
||||
from tools.registry import registry, tool_error, tool_result
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SYMBOLIC_VERIFY_SCHEMA = {
|
||||
"name": "symbolic_verify",
|
||||
"description": "Perform a deterministic GOFAI audit of code using AST analysis. Identifies undefined variables, unused imports, and scoping issues without using an LLM. Use this to verify your changes are syntactically and semantically sound before submission.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {"type": "string", "description": "Path to the Python file to audit."},
|
||||
"check_level": {
|
||||
"type": "string",
|
||||
"enum": ["syntax", "scope", "all"],
|
||||
"default": "all",
|
||||
"description": "Level of analysis to perform."
|
||||
}
|
||||
},
|
||||
"required": ["path"]
|
||||
}
|
||||
}
|
||||
|
||||
class ScopeAnalyzer(ast.NodeVisitor):
|
||||
def __init__(self):
|
||||
self.defined_vars = set()
|
||||
self.used_vars = set()
|
||||
self.undefined_references = []
|
||||
self.scopes = [{}] # Stack of symbol tables
|
||||
self.builtins = set(dir(__builtins__))
|
||||
|
||||
def visit_Import(self, node):
|
||||
for alias in node.names:
|
||||
name = alias.asname or alias.name
|
||||
self.scopes[-1][name] = "import"
|
||||
self.generic_visit(node)
|
||||
|
||||
def visit_ImportFrom(self, node):
|
||||
for alias in node.names:
|
||||
name = alias.asname or alias.name
|
||||
self.scopes[-1][name] = "import"
|
||||
self.generic_visit(node)
|
||||
|
||||
def visit_Name(self, node):
|
||||
if isinstance(node.ctx, ast.Store):
|
||||
self.scopes[-1][node.id] = "defined"
|
||||
elif isinstance(node.ctx, ast.Load):
|
||||
# Check if defined in any scope level or builtins
|
||||
is_defined = any(node.id in scope for scope in self.scopes) or node.id in self.builtins
|
||||
if not is_defined:
|
||||
# Store potential undefined
|
||||
self.undefined_references.append({
|
||||
"name": node.id,
|
||||
"lineno": node.lineno,
|
||||
"col": node.col_offset
|
||||
})
|
||||
self.generic_visit(node)
|
||||
|
||||
def visit_FunctionDef(self, node):
|
||||
self.scopes[-1][node.name] = "function"
|
||||
# New scope for arguments and body
|
||||
new_scope = {}
|
||||
for arg in node.args.args:
|
||||
new_scope[arg.arg] = "parameter"
|
||||
self.scopes.append(new_scope)
|
||||
self.generic_visit(node)
|
||||
self.scopes.pop()
|
||||
|
||||
def visit_ClassDef(self, node):
|
||||
self.scopes[-1][node.name] = "class"
|
||||
self.scopes.append({})
|
||||
self.generic_visit(node)
|
||||
self.scopes.pop()
|
||||
|
||||
def audit_file(path: str, check_level: str = "all"):
|
||||
"""Audit a Python file for common semantic errors."""
|
||||
if not path.endswith(".py"):
|
||||
return tool_error("Symbolic verification only supports Python (.py) files.")
|
||||
|
||||
try:
|
||||
if not os.path.exists(path):
|
||||
return tool_error(f"File not found: {path}")
|
||||
|
||||
source = open(path, "r").read()
|
||||
|
||||
# 1. Syntax Check
|
||||
try:
|
||||
tree = ast.parse(source)
|
||||
except SyntaxError as e:
|
||||
return tool_result(
|
||||
status="Critical Failure",
|
||||
errors=[{
|
||||
"type": "SyntaxError",
|
||||
"message": e.msg,
|
||||
"lineno": e.lineno,
|
||||
"offset": e.offset
|
||||
}],
|
||||
recommendation="Fix the syntax error immediately. The file cannot be executed."
|
||||
)
|
||||
|
||||
if check_level == "syntax":
|
||||
return tool_result(status="Clean", message="Syntax is valid.")
|
||||
|
||||
# 2. Scope & Reference Search
|
||||
analyzer = ScopeAnalyzer()
|
||||
analyzer.visit(tree)
|
||||
|
||||
# Filter out common false positives (e.g. late imports or dynamic names)
|
||||
# For a truly robust GOFAI we'd do more, but this is 'secret sauce' level
|
||||
undefined = []
|
||||
seen = set()
|
||||
for ref in analyzer.undefined_references:
|
||||
key = (ref["name"], ref["lineno"])
|
||||
if key not in seen:
|
||||
undefined.append(ref)
|
||||
seen.add(key)
|
||||
|
||||
if not undefined:
|
||||
return tool_result(
|
||||
status="Healthy",
|
||||
message="Deterministic check passed. No undefined variables detected in analyzed scopes.",
|
||||
file_stats={
|
||||
"chars": len(source),
|
||||
"nodes": len(list(ast.walk(tree)))
|
||||
}
|
||||
)
|
||||
|
||||
report = "GOFAI AUDIT DETECTED SEMANTIC ISSUES:\n"
|
||||
for u in undefined:
|
||||
report += f"- Undefined Variable: '{u['name']}' at line {u['lineno']}\n"
|
||||
|
||||
return tool_result(
|
||||
status="Warning",
|
||||
summary=report,
|
||||
undefined_variables=undefined,
|
||||
recommendation="Review the undefined variables. Ensure they are imported or defined before use."
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
return tool_error(f"Symbolic audit failed: {str(e)}")
|
||||
|
||||
def _handle_symbolic_verify(args, **kwargs):
|
||||
return audit_file(args.get("path"), args.get("check_level", "all"))
|
||||
|
||||
|
||||
registry.register(
|
||||
name="symbolic_verify",
|
||||
toolset="qa",
|
||||
schema=SYMBOLIC_VERIFY_SCHEMA,
|
||||
handler=_handle_symbolic_verify,
|
||||
emoji="🔬"
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user