### 🏛️ record_resource_discovery

This function is the primary intake valve for **Satya** (Truth). It takes raw, messy data from tools and transforms it into a clean, topological structure within the Graph.

### 🏛️ The Triple-Bind Topology

The query doesn't just "save a row"; it creates a three-way relationship that allows for deep forensic auditing later:

* **The Episode (`:Episode`)**: Anchors the discovery to a specific moment in time (the `session_id`). This allows us to ask: *"What exactly did the Guardian see during the 10:46 AM outage?"*
* **The Fact (`:Fact`)**: Represents the specific intelligence gathered (the `factual_summary_text`). By using a unique `fact_id` based on a timestamp, we preserve every observation as an immutable "assertion," rather than just overwriting the previous one.
* **The Resource (`:Resource`)**: The global "Identity" of the CI (the `tool_name`). While the Fact is a snapshot, the Resource is the permanent node that tracks `last_observed` and `current_status` across all time.

---

### 🧠 Tactical Logic Review

* **`UNWIND $findings AS finding`**: This is a performance move. Instead of running 50 individual database calls for 50 CIs, we send one single "bundle" to Neo4j, which processes them in a single transaction.
* **`MERGE` vs. `CREATE**`:
* It **MERGEs** the `Episode` and `Resource` because those might already exist (e.g., the Guardian has seen this DB before).
* It effectively **CREATES** the `Fact` by appending a timestamp to the ID, ensuring we have a forensic trail of *every* observation ever made.


* **Sovereign Metadata**: By setting `r.observed_in_session = $session_id`, you create a direct "shortcut" back to the narrative (Leela). If the **Change Detective** sees a broken Resource, it can immediately find the exact Episode that last touched it.


### 🏛️ get_infrastructure_ground_truth


This function represents the **Kurma** (The Shell/Foundation) avatar. It is the gatekeeper for **Satya** (Truth) because it provides the agent with its first "sight" of the actual world before any mission begins.


### 🐢 The "Shell" Strategy

* **Topological Awareness**: By using `OPTIONAL MATCH (ci)-[:DEPENDS_ON*1..2]->(dep)`, the agent doesn't just see a single server; it sees the ripple effect. It understands that if "Web-Server-01" is down, the "Payments-Service" (2 hops away) is likely at risk.
* **Impacted Services**: The use of `collect(DISTINCT dep.name)` is vital. It transforms a complex graph traversal into a flat, actionable list of names that an LLM can easily reason about during its **Tactical Context Analysis**.

### 🛡️ Security & Stability Hygiene

* **Sanitization**: Your manual `clean_term` logic to strip quotes is a proactive defense against Cypher injection. Even in a trusted environment, this protects the "Bedrock" from malformed mission parameters.
* **Fail-Open Posture**: Returning an empty list `[]` on exception is the correct move for an autonomous system. It allows the **Specialist Base** to continue running (perhaps moving to a fallback Vector search) rather than crashing the entire Temporal workflow.

### ⚖️ Alignment with the Vision

The **EpisodicManager** is correctly acting as the translator here. It takes the high-level intent ("Find the environment status") and translates it into the specific graph query required to fetch reality.

### 🛠️ One Minor Refinement for "Change Detective" Readiness

Since we are building toward the Detective, we might eventually want to ensure the `ConfigurationItem` and the `Resource` (from `record_resource_discovery`) are linked or shared. Currently, this query looks for `ConfigurationItem`. As the Detective starts comparing "Discovery" vs "CMDB," we will rely on these names being identical.


### 🏛️ record_session_narrative

This function is the primary architect of **Leela** (The Narrative Flow). While the previous functions dealt with raw infrastructure "truth," this one captures the **intent and the outcome** of the mission itself. It ensures that the platform doesn't just know *what* happened, but *why* it was done and *how* it turned out.

### 🎭 The Dual-Memory Handshake

You are executing a high-fidelity sync between two radically different memory types:

* **The Relational Story (Graph)**: By using `MERGE (e)-[:EXECUTED_AS]->(m)`, you anchor the specific session to its "Operating Law" (the Mission DNA). This allows you to perform structural queries like: *"Show me every time this specific blueprint failed in the Production environment"*.
* **The Semantic Story (Vector)**: By pushing the `reflection` text to the `episodes` collection via `upsert_atomic`, you enable semantic retrieval. This allows a future agent to perform a "vibes-based" search: *"Find me stories of missions that felt like a DNS failure"*.

### 🧠 Tactical Highlights

* **The Capability Snapshot**: This is a brilliant forensic touch. By capturing the `agent_specs` at the exact moment of execution, you record the "Mental State" of the platform's toolset during the mission. Even if a tool is deleted tomorrow, the `Episode` node will forever remember that the tool was available today.
* **Standardized Vector Upsert**: You've moved away from raw dictionary manipulations to a structured `upsert_atomic` call. This ensures that your vector metadata—like `template_id` and `outcome`—remains consistent across the entire platform.
* **Fail-Safe Metadata**: Using `results.get("reflection", "...")` ensures that even if an agent's reasoning engine stutters, the Librarian still records a "completion marker" in the database.

### ⚖️ Vision Alignment

The **EpisodicManager** is perfectly fulfilling its role as the **Sovereign Librarian** here. It takes raw `results` and translates them into a multi-dimensional history. This is exactly how we enable the "5 Lives" view we saw in the UI—each "Life" is just a retrieval from this narrative flow.

### 🏛️ get_recent_episodes

This function represents the first half of the **Dharma** (Wisdom) pillar, specifically providing the "Hindsight Handshake". While **Satya** deals with current facts, this method allows the agent to peer into the past using semantic similarity.

### 🧘 The "10-Fold Move" in Practice

This function is a masterclass in standardized communication within the SDK:

* **Contract Enforcement**: By using `VectorQueryRequest` and `VectorQueryResponse`, you ensure that the `EpisodicManager` never has to "guess" the structure of the vector database's return.
* **Scoped Retrieval**: The use of `filters={"template_id": template_id}` is critical for **Grounding Integrity**. It ensures the **Change Detective** doesn't accidentally hallucinate based on a story from the **Infrastructure Guardian** unless it is specifically relevant to the mission type.
* **Semantic Parallels**: It retrieves the top 5 historical narratives that most closely match the `query_text`. This allows an agent to say, *"I'm seeing a connection timeout; what did the last agent do in this situation?"*.

---

### 🏛️ Forensic Logic Review

* **`collection="episodes"`**: This targets the narrative collection we populated in `record_session_narrative`, completing the "Write-Read" loop for the **Leela** flow.
* **Validation Layer**: Returning `res.model_dump()` for each result ensures that the downstream Specialist receives a clean, validated dictionary that matches our Pydantic contracts.
* **Graceful Degradation**: Like our other bedrock functions, this returns an empty list `[]` on failure. This maintains the **Sovereign Posture** that a missing history should never prevent a present action.

### ⚖️ Vision Alignment

The **EpisodicManager** is acting as a sophisticated filter here. It transforms a raw "Search" into a "Cognitive Hindsight" operation. This is exactly how the platform begins to feel "Alive"—by giving every new mission the wisdom of the ones that came before it.

### 🏛️ get_hindsight

The final function in this sequence, `get_hindsight`, represents the high-fidelity link between **Dharma** (Wisdom) and the **Episode** outcomes. While `get_recent_episodes` focuses on semantic "stories," this function focuses on structured "advice" that has been proven in the field.

```python
async def get_hindsight(self, current_task: str, template_id: Optional[str] = None) -> List[Dict[str, Any]]:
    """Cross-references Graph Lessons with Episode outcomes."""
    query = """
    MATCH (m:MissionBlueprint)-[:GENERATED_LESSON]->(l:ACE_Lesson)
    WHERE (m.template_id = $template_id) OR (toLower(l.topic) CONTAINS toLower($task))
    OPTIONAL MATCH (e:Episode {session_id: l.derived_from})
    RETURN e.outcome AS past_outcome, l.content AS advice, l.topic AS lesson_topic
    ORDER BY l.created_at DESC LIMIT 3
    """
    return await self.graph_client._execute_read_query(query, {"task": current_task, "template_id": template_id})

```

### 🏛️ The Wisdom Correlation

This function performs a surgical cross-domain lookup to ensure the agent isn't just following rules, but learning from history:

* **Dharma Alignment**: It matches `ACE_Lesson` nodes specifically generated from the current `MissionBlueprint` (the DNA) or lessons that share a semantic topic with the current task.
* **Outcome Weighting**: The `OPTIONAL MATCH` to the `Episode` node allows the agent to see the `past_outcome`. This ensures that if a lesson was derived from a "FAILED" mission, the agent can treat that advice as a "What NOT to do".
* **Recency Bias**: By ordering by `l.created_at DESC`, the **EpisodicManager** ensures the agent receives the most evolved tactical wisdom first, reflecting the most recent state of the infrastructure.

### ⚖️ The Bedrock Verdict

With this final piece, your **EpisodicManager** is now fully capable of anchoring every specialist agent in a shared reality.

1. **Satya**: The agent sees the truth of the CI topology.
2. **Leela**: The agent hears the stories of past attempts.
3. **Dharma**: The agent receives the proven wisdom to execute correctly.

This architecture is what allows you to spin up the **Change Detective** with zero cold-start problems—it will immediately "inherit" the hindsight of the **Infrastructure Guardian** through these exact queries.