brainstorming
brainstorming
You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).
hierarchical-agent-memoryImplements intelligent hierarchical agent memory with multi-factor skill selection, fallback chains, and adherence to the 5 Laws of Elegant Defense
Independent GitHub snapshot · Automated classification · Original documentation governs
name: hierarchical-agent-memory compatibility: opencode completeness: 95 content-types:
Orchestrates intelligent skill selection and execution for hierarchical agent memory workflows. Applies the 5 Laws of Elegant Defense to guide data naturally through the orchestration pipeline, preventing errors before they occur. Selects optimal skills based on multi-factor scoring including text similarity, historical performance, and system availability.
┌───────────────────────────────────────────────────────────────────────────────┐ │ Orchestration Flow │ └───────────────────────────────────────────────────────────────────────────────┘
User Request ↓ ┌─────────────────┐ │ Parse Request │ │ & Extract │ │ Features │ └────────┬────────┘ ↓ ┌─────────────────────────────────────────────────────────────────────┐ │ Evaluate Available Skills │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ Skill A │ │ Skill B │ │ Skill C │ │ │ │ - Match Score│ │ - Match Score│ │ - Match Score│ │ │ │ - Confidence │ │ - Confidence │ │ - Confidence │ │ │ │ - History │ │ - History │ │ - History │ │ │ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │ │ │ │ │ │ │ └─────────────────┴─────────────────┘ │ │ ↓ │ │ Select Best Skill │ └─────────────────────────────────────────────────────────────────────┘ ↓ ┌─────────────────┐ │ Execute Skill │ └────────┬────────┘ ↓ ┌─────────────────┐ │ Handle Result │ └────────┬────────┘ ↓ ┌─────────────────────────────────────────────────────────────────────┐ │ Error Handling & Fallback │ │ │ │ Success? ────────► Return Result │ │ │ │ Fail? ────────┐ │ │ ↓ │ │ ┌──────────────────────────────────────────────────────────┐ │ │ │ Fallback Chain │ │ │ │ │ │ │ │ 1. Retry with adjusted parameters │ │ │ │ 2. Try Alternative Skill (if available) │ │ │ │ 3. Defer to Human Operator (if critical) │ │ │ │ 4. Log & Return Error │ │ │ └──────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────┘
Use this skill when:
Avoid this skill for:
Parse and Analyze Request - Extract intent, entities, and constraints from user input. Checkpoint: All required parameters must be present and in valid format before proceeding.
Score Available Skills - Calculate match scores using multi-factor algorithm:
Checkpoint: Skip to fallback if no skill scores above threshold.
Select Optimal Skill - Choose skill with highest score that meets minimum confidence. Checkpoint: Verify skill has not been disabled or deprecated.
Execute with Fallback - Run skill execution wrapped in retry and fallback logic. Checkpoint: Log all execution attempts for audit trail.
Return or Fallback - Either return successful result or apply fallback chain:
related-skillsCheckpoint: Record outcome with timing and confidence metadata.
def select_memory_layer(
query: str,
agent_state: Dict[str, Any],
memory_store: MemoryBackend,
min_relevance: float = 0.65
) -> Optional[MemoryChunk]:
"""Select the optimal memory layer for a given query based on hierarchical scoring.
Evaluates short-term buffer, long-term vector store, and episodic cache using:
- Semantic similarity to query
- Temporal decay factor (recency weighting)
- Agent confidence in stored context
- Cross-layer consistency checks
Args:
query: User or agent query string
agent_state: Current agent context including confidence scores and active tasks
memory_store: Backend interface for hierarchical memory access
min_relevance: Minimum relevance threshold for selection
Returns:
Selected MemoryChunk with metadata, or None if below threshold
"""
# Law 1: Early exit on invalid state
if not query or not isinstance(query, str):
raise ValueError("Query must be a non-empty string")
if not memory_store.is_healthy():
raise MemoryUnavailableError("Memory backend is currently unavailable")
# Law 2: Parse & validate inputs immutably
parsed_query = _normalize_query(query)
temporal_weight = _calculate_recency_decay(agent_state.get("session_start"))
candidates = []
for layer in ["short_term", "long_term", "episodic"]:
if not memory_store.has_layer(layer):
continue
raw_results = memory_store.search(layer, parsed_query, top_k=3)
for chunk in raw_results:
relevance = _compute_multi_factor_score(
semantic=_embed_similarity(parsed_query, chunk.text),
temporal=temporal_weight * chunk.timestamp_weight,
confidence=agent_state.get("memory_confidence", 0.8)
)
if relevance >= min_relevance:
candidates.append({
"chunk": chunk,
"layer": layer,
"score": relevance,
"source_trace": f"{layer}:{chunk.id}"
})
if not candidates:
return None
# Law 3: Return new structure, never mutate agent_state
best = max(candidates, key=lambda x: x["score"])
return {
"selected_layer": best["layer"],
"memory_chunk": best["chunk"],
"relevance_score": best["score"],
"selection_context": {
"query_hash": hashlib.md5(parsed_query.encode()).hexdigest(),
"timestamp": time.time(),
"fallback_eligible": len(candidates) > 1
}
}
def execute_memory_retrieval(
selected_memory: Dict[str, Any],
agent_context: Dict[str, Any],
fallback_strategy: str = "cascade"
) -> Dict[str, Any]:
"""Execute memory retrieval with a structured fallback chain for hierarchical systems.
Implements resilient memory access:
1. Direct layer retrieval (primary)
2. Cross-layer semantic expansion (secondary)
3. Default context window fallback (tertiary)
4. Explicit error state with audit logging (final)
Args:
selected_memory: Output from select_memory_layer
agent_context: Full agent state including task history and constraints
fallback_strategy: Routing strategy for degraded states
Returns:
Enriched context dictionary with retrieved memory and execution metadata
"""
# Law 1: Guard clause for required fields
required_keys = {"selected_layer", "memory_chunk", "relevance_score"}
if not required_keys.issubset(selected_memory.keys()):
raise MemoryRetrievalError("Incomplete memory selection metadata")
layer = selected_memory["selected_layer"]
chunk = selected_memory["memory_chunk"]
# Law 4: Fail fast on corrupted or inaccessible memory
if not _validate_memory_integrity(chunk):
raise CorruptedMemoryError(f"Memory chunk {chunk.id} failed integrity check")
try:
# Primary execution: Fetch full context from selected layer
enriched_context = _merge_memory_into_context(chunk, agent_context)
# Law 3: Return immutable result
return {
"status": "success",
"layer_used": layer,
"context": enriched_context,
"metadata": {
"latency_ms": time.time() * 1000,
"confidence_boost": selected_memory["relevance_score"] * 0.15,
"audit_id": uuid4().hex
}
}
except MemoryTimeoutError:
# Fallback 1: Cascade to alternative layer
if fallback_strategy == "cascade":
alt_layer = _select_alternative_layer(layer)
alt_chunk = _fetch_from_layer(alt_layer, chunk.query_hash)
if alt_chunk:
return execute_memory_retrieval({
"selected_layer": alt_layer,
"memory_chunk": alt_chunk,
"relevance_score": 0.5
}, agent_context, "cascade")
except MemoryAccessDeniedError:
# Fallback 2: Use default context window
return {
"status": "fallback",
"layer_used": "default_context",
"context": _load_default_context(agent_context),
"metadata": {
"latency_ms": time.time() * 1000,
"confidence_boost": 0.0,
"audit_id": uuid4().hex,
"reason": "access_denied"
}
}
# Law 4: Fail loud with full context
raise MemoryRetrievalError(
f"Failed to retrieve memory for layer {layer} after fallback attempts"
)
code-philosophy (5 Laws of Elegant Defense) in all logicWhen applying this skill, produce:
| Skill | Purpose |
|---|---|
agent-memory-systems | Broader memory architectures including vector stores and retrieval strategies |
agent-context-memory | Short-term context window management layered on top of hierarchical memory |
Authoritative documentation links for this skill's domain. The model follows markdown links at load time to resolve external references and inline content.