Compare commits

..

1 Commits

Author SHA1 Message Date
Alexander Whitestone
2e278758e0 feat: add Ansible deployment for MemPalace v3.0.0 fleet integration (#570)
Some checks failed
Self-Healing Smoke / self-healing-smoke (pull_request) Failing after 26s
Smoke Test / smoke (pull_request) Failing after 31s
Agent PR Gate / gate (pull_request) Failing after 57s
Agent PR Gate / report (pull_request) Successful in 24s
- Add ansible/roles/mempalace/ with tasks, templates, defaults, meta
- Add ansible/playbooks/deploy_mempalace.yml targeting fleet hosts
- Role installs mempalace==3.0.0 in isolated venv
- Deploys mempalace.yaml, MCP config, and session-start wake-up hook
- Mines home + sessions, runs search smoke test, generates wake-up context
- Add tests/test_mempalace_ansible_role.py validating role structure
- Update docs/MEMPALACE_EZRA_INTEGRATION.md with Ansible usage
- Update existing integration test to assert Ansible section present

All 12 mempalace tests pass.

Refs #570
2026-04-22 02:00:31 -04:00
12 changed files with 306 additions and 174 deletions

View File

@@ -0,0 +1,22 @@
---
# ansible/playbooks/deploy_mempalace.yml — Deploy MemPalace v3.0.0 to fleet wizards.
#
# Usage:
# ansible-playbook -i inventory/hosts.ini playbooks/deploy_mempalace.yml --limit ezra
# ansible-playbook -i inventory/hosts.ini playbooks/deploy_mempalace.yml
#
# Refs: Issue #570
- name: Deploy MemPalace v3.0.0 to wizard hosts
hosts: fleet
become: false
gather_facts: false
vars:
mempalace_hermes_home: "{{ ansible_env.HOME }}/.hermes"
mempalace_sessions_dir: "{{ mempalace_hermes_home }}/sessions"
mempalace_palace_path: "{{ ansible_env.HOME }}/.mempalace/palace"
mempalace_wing: "{{ inventory_hostname }}_home"
roles:
- role: ../roles/mempalace
vars:
mempalace_venv_path: "{{ ansible_env.HOME }}/.mempalace-venv"

View File

@@ -0,0 +1,16 @@
---
# MemPalace role defaults
mempalace_package_spec: "mempalace==3.0.0"
mempalace_hermes_home: "{{ ansible_env.HOME }}/.hermes"
mempalace_sessions_dir: "{{ mempalace_hermes_home }}/sessions"
mempalace_palace_path: "{{ ansible_env.HOME }}/.mempalace/palace"
mempalace_wing: "{{ inventory_hostname }}_home"
mempalace_wakeup_dir: "{{ mempalace_hermes_home }}/wakeups"
mempalace_wakeup_file: "{{ mempalace_wakeup_dir }}/{{ mempalace_wing }}.txt"
mempalace_venv_path: "{{ ansible_env.HOME }}/.mempalace-venv"
mempalace_config_path: "{{ mempalace_hermes_home }}/mempalace.yaml"
mempalace_mcp_config_path: "{{ mempalace_hermes_home }}/hermes-mcp-mempalace.yaml"
mempalace_session_hook_path: "{{ mempalace_hermes_home }}/session-start-mempalace.sh"
mempalace_run_mining: true
mempalace_run_search_test: true
mempalace_run_wake_up: true

View File

@@ -0,0 +1,2 @@
---
dependencies: []

View File

@@ -0,0 +1,119 @@
---
# MemPalace v3.0.0 deployment role for fleet wizards.
# Refs: Issue #570
- name: Ensure mempalace venv directory exists
ansible.builtin.file:
path: "{{ mempalace_venv_path }}"
state: directory
mode: '0750'
- name: Create mempalace virtual environment
ansible.builtin.command:
cmd: "python3 -m venv {{ mempalace_venv_path }}"
creates: "{{ mempalace_venv_path }}/bin/python"
- name: Install mempalace package
ansible.builtin.pip:
name: "{{ mempalace_package_spec }}"
virtualenv: "{{ mempalace_venv_path }}"
virtualenv_command: "{{ mempalace_venv_path }}/bin/python -m venv"
- name: Ensure Hermes home directory exists
ansible.builtin.file:
path: "{{ mempalace_hermes_home }}"
state: directory
mode: '0750'
- name: Ensure sessions directory exists
ansible.builtin.file:
path: "{{ mempalace_sessions_dir }}"
state: directory
mode: '0750'
- name: Ensure wakeup directory exists
ansible.builtin.file:
path: "{{ mempalace_wakeup_dir }}"
state: directory
mode: '0750'
- name: Ensure palace directory exists
ansible.builtin.file:
path: "{{ mempalace_palace_path }}"
state: directory
mode: '0750'
- name: Deploy mempalace.yaml configuration
ansible.builtin.template:
src: mempalace.yaml.j2
dest: "{{ mempalace_config_path }}"
mode: '0640'
- name: Deploy Hermes MCP mempalace config
ansible.builtin.template:
src: hermes-mcp-mempalace.yaml.j2
dest: "{{ mempalace_mcp_config_path }}"
mode: '0640'
- name: Deploy session-start wake-up hook
ansible.builtin.template:
src: session-start-mempalace.sh.j2
dest: "{{ mempalace_session_hook_path }}"
mode: '0750'
- name: Mine Hermes home directory
ansible.builtin.shell: |
set -euo pipefail
echo "" | {{ mempalace_venv_path }}/bin/mempalace mine {{ mempalace_hermes_home }} --config {{ mempalace_config_path }}
args:
executable: /bin/bash
when: mempalace_run_mining | bool
register: mine_home_result
changed_when: mine_home_result.rc == 0
- name: Mine session history
ansible.builtin.shell: |
set -euo pipefail
echo "" | {{ mempalace_venv_path }}/bin/mempalace mine {{ mempalace_sessions_dir }} --mode convos --config {{ mempalace_config_path }}
args:
executable: /bin/bash
when: mempalace_run_mining | bool
register: mine_sessions_result
changed_when: mine_sessions_result.rc == 0
- name: Run search test
ansible.builtin.shell: |
set -euo pipefail
{{ mempalace_venv_path }}/bin/mempalace search "common queries" --config {{ mempalace_config_path }} | head -20
args:
executable: /bin/bash
when: mempalace_run_search_test | bool
register: search_test_result
changed_when: false
- name: Generate wake-up context
ansible.builtin.shell: |
set -euo pipefail
{{ mempalace_venv_path }}/bin/mempalace wake-up --config {{ mempalace_config_path }} > {{ mempalace_wakeup_file }}
export HERMES_MEMPALACE_WAKEUP_FILE="{{ mempalace_wakeup_file }}"
printf '[MemPalace] wake-up context refreshed: %s\n' "$HERMES_MEMPALACE_WAKEUP_FILE"
args:
executable: /bin/bash
when: mempalace_run_wake_up | bool
register: wake_up_result
changed_when: wake_up_result.rc == 0
- name: Report MemPalace deployment summary
ansible.builtin.debug:
msg:
- "MemPalace deployed for {{ inventory_hostname }}"
- "Package: {{ mempalace_package_spec }}"
- "Config: {{ mempalace_config_path }}"
- "Palace: {{ mempalace_palace_path }}"
- "Wake-up: {{ mempalace_wakeup_file }}"
- "MCP config: {{ mempalace_mcp_config_path }}"
- "Session hook: {{ mempalace_session_hook_path }}"
- "Home mine: {{ 'OK' if mine_home_result.rc | default(1) == 0 else 'SKIPPED' }}"
- "Sessions mine: {{ 'OK' if mine_sessions_result.rc | default(1) == 0 else 'SKIPPED' }}"
- "Search test: {{ 'OK' if search_test_result.rc | default(1) == 0 else 'SKIPPED' }}"
- "Wake-up: {{ 'OK' if wake_up_result.rc | default(1) == 0 else 'SKIPPED' }}"

View File

@@ -0,0 +1,6 @@
mcp_servers:
mempalace:
command: "{{ mempalace_venv_path }}/bin/python"
args:
- -m
- mempalace.mcp_server

View File

@@ -0,0 +1,21 @@
wing: {{ mempalace_wing }}
palace: {{ mempalace_palace_path }}
rooms:
- name: sessions
description: Conversation history and durable agent transcripts
globs:
- "*.json"
- "*.jsonl"
- name: config
description: Hermes configuration and runtime settings
globs:
- "*.yaml"
- "*.yml"
- "*.toml"
- name: docs
description: Notes, markdown docs, and operating reports
globs:
- "*.md"
- "*.txt"
people: []
projects: []

View File

@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail
if command -v {{ mempalace_venv_path }}/bin/mempalace >/dev/null 2>&1; then
mkdir -p "{{ mempalace_wakeup_dir }}"
{{ mempalace_venv_path }}/bin/mempalace wake-up --config {{ mempalace_config_path }} > "{{ mempalace_wakeup_file }}"
export HERMES_MEMPALACE_WAKEUP_FILE="{{ mempalace_wakeup_file }}"
printf '[MemPalace] wake-up context refreshed: %s\n' "$HERMES_MEMPALACE_WAKEUP_FILE"
fi

View File

@@ -146,6 +146,23 @@ That bundle writes:
- `session-start-mempalace.sh`
- `issue-568-comment-template.md`
## Fleet Ansible deployment
Deploy MemPalace to Ezra (or the whole fleet) with the Ansible playbook:
```bash
ansible-playbook -i ansible/inventory/hosts.ini ansible/playbooks/deploy_mempalace.yml --limit ezra
```
This playbook:
1. Creates a dedicated venv and installs `mempalace==3.0.0`
2. Deploys `mempalace.yaml`, MCP config, and session-start hook
3. Mines the Hermes home and sessions directories
4. Runs a search smoke test
5. Generates the wake-up context file
Set `mempalace_run_mining=false` to skip mining on hosts where the corpus is already populated.
## Why this shape
- `wing: ezra_home` matches the issue's Ezra-specific integration target.

View File

@@ -12,27 +12,6 @@ WORLD_DIR = Path('/Users/apayne/.timmy/evennia/timmy_world')
STATE_FILE = WORLD_DIR / 'game_state.json'
TIMMY_LOG = WORLD_DIR / 'timmy_log.md'
FRIENDSHIP_THRESHOLD = 0.5
TENSION_THRESHOLD = -0.5
NPC_RELATIONSHIP_SEEDS = {
("Kimi", "Marcus"): {
"values": {"Kimi": 0.45, "Marcus": 0.47},
"conversation": "While you are away, Marcus and Kimi trade a quiet confidence beneath the oak.",
"milestone": "A friendship starts to take root between Marcus and Kimi.",
"hint": "Marcus and Kimi move with the easy familiarity of old friends.",
"delta": 0.08,
"kind": "friendship",
},
("Bezalel", "ClawCode"): {
"values": {"Bezalel": -0.46, "ClawCode": -0.44},
"conversation": "While you are away, Bezalel and ClawCode clash over what the forge is for.",
"milestone": "Tension hardens between Bezalel and ClawCode at the anvil.",
"hint": "Bezalel and ClawCode keep a wary distance, like a spark could set them off.",
"delta": -0.08,
"kind": "tension",
},
}
# ============================================================
# NARRATIVE ARC — 4 phases that transform the world
# ============================================================
@@ -279,35 +258,7 @@ class World:
"items_crafted": 0,
"conflicts_resolved": 0,
"nights_survived": 0,
"npc_friendships": [],
"npc_tensions": [],
}
self._initialize_npc_relationships(apply_seeds=True)
def _initialize_npc_relationships(self, apply_seeds=False):
npc_names = [name for name, char in self.characters.items() if not char.get("is_player", False)]
for npc_name in npc_names:
trust_map = self.characters[npc_name]["trust"]
for other_name in npc_names:
if other_name != npc_name:
trust_map.setdefault(other_name, 0.0)
if apply_seeds:
for pair, seed in NPC_RELATIONSHIP_SEEDS.items():
left, right = pair
self.characters[left]["trust"][right] = seed["values"][left]
self.characters[right]["trust"][left] = seed["values"][right]
self.state.setdefault("npc_friendships", [])
self.state.setdefault("npc_tensions", [])
def relationship_hint_for_room(self, room_name, occupants):
hints = []
occupant_set = set(occupants)
for bucket in ("npc_friendships", "npc_tensions"):
for entry in self.state.get(bucket, []):
pair = set(entry.get("pair", []))
if entry.get("room") == room_name and pair.issubset(occupant_set):
hints.append(entry.get("hint", ""))
return [hint for hint in hints if hint]
def tick_time(self):
"""Advance time of day."""
@@ -438,8 +389,6 @@ class World:
here = [n for n, c in self.characters.items() if c["room"] == room_name and n != char_name]
if here:
desc += f"\n Here: {', '.join(here)}"
for hint in self.relationship_hint_for_room(room_name, here):
desc += f" {hint}"
return desc
@@ -465,12 +414,6 @@ class World:
self.rooms = data.get("rooms", self.rooms)
self.characters = data.get("characters", self.characters)
self.state = data.get("state", self.state)
needs_seed = not any(
any(other != "Timmy" for other in char.get("trust", {}))
for name, char in self.characters.items()
if not char.get("is_player", False)
)
self._initialize_npc_relationships(apply_seeds=needs_seed)
return True
return False
@@ -1129,69 +1072,6 @@ class GameEngine:
f.write(f"\n*Began: {datetime.now().strftime('%Y-%m-%d %H:%M')}*\n\n")
f.write("---\n\n")
f.write(message + "\n")
def _adjust_mutual_trust(self, left, right, delta):
for speaker, listener in ((left, right), (right, left)):
trust_map = self.world.characters[speaker]["trust"]
trust_map[listener] = max(-1.0, min(1.0, trust_map.get(listener, 0.0) + delta))
def _record_relationship_milestone(self, scene, room_name, pair, bucket, milestone, hint):
pair_list = list(pair)
entries = self.world.state.setdefault(bucket, [])
if any(entry.get("pair") == pair_list for entry in entries):
return
entries.append({
"pair": pair_list,
"room": room_name,
"summary": milestone,
"hint": hint,
})
scene["world_events"].append(milestone)
def _run_offscreen_npc_relationships(self, scene):
timmy_room = self.world.characters["Timmy"]["room"]
rooms = {}
for char_name, char in self.world.characters.items():
if char.get("is_player", False):
continue
rooms.setdefault(char["room"], []).append(char_name)
for room_name, occupants in rooms.items():
if room_name == timmy_room or len(occupants) < 2:
continue
occupant_set = set(occupants)
for pair, seed in NPC_RELATIONSHIP_SEEDS.items():
if not set(pair).issubset(occupant_set):
continue
left, right = pair
self._adjust_mutual_trust(left, right, seed["delta"])
scene["npc_actions"].append(f"{left} and {right} speak in The {room_name} while you are away.")
scene["world_events"].append(seed["conversation"])
self.world.characters[left]["spoken"].append(seed["conversation"])
self.world.characters[right]["spoken"].append(seed["conversation"])
self.world.characters[left]["memories"].append(seed["conversation"])
self.world.characters[right]["memories"].append(seed["conversation"])
left_trust = self.world.characters[left]["trust"][right]
right_trust = self.world.characters[right]["trust"][left]
if seed["kind"] == "friendship" and left_trust >= FRIENDSHIP_THRESHOLD and right_trust >= FRIENDSHIP_THRESHOLD:
self._record_relationship_milestone(
scene,
room_name,
pair,
"npc_friendships",
seed["milestone"],
seed["hint"],
)
elif seed["kind"] == "tension" and left_trust <= TENSION_THRESHOLD and right_trust <= TENSION_THRESHOLD:
self._record_relationship_milestone(
scene,
room_name,
pair,
"npc_tensions",
seed["milestone"],
seed["hint"],
)
def run_tick(self, timmy_action="look"):
"""Run one tick. Return the scene and available choices."""
@@ -1517,8 +1397,6 @@ class GameEngine:
self.world.characters[char_name]["room"] = dest
self.world.characters[char_name]["energy"] -= 1
scene["npc_actions"].append(f"{char_name} moves from The {old_room} to The {dest}")
self._run_offscreen_npc_relationships(scene)
# Random NPC events — phase-aware speech
room_name = self.world.characters["Timmy"]["room"]

View File

@@ -0,0 +1,92 @@
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parent.parent
ROLE_PATH = ROOT / "ansible" / "roles" / "mempalace"
PLAYBOOK_PATH = ROOT / "ansible" / "playbooks" / "deploy_mempalace.yml"
class TestMempalaceAnsibleRole(unittest.TestCase):
def test_role_directory_structure_exists(self):
self.assertTrue(ROLE_PATH.exists(), "mempalace role directory missing")
for subdir in ["tasks", "templates", "defaults", "meta"]:
self.assertTrue(
(ROLE_PATH / subdir).exists(),
f"mempalace role subdir missing: {subdir}",
)
def test_role_defaults_contains_required_variables(self):
defaults_path = ROLE_PATH / "defaults" / "main.yml"
self.assertTrue(defaults_path.exists())
text = defaults_path.read_text(encoding="utf-8")
required_vars = [
"mempalace_package_spec",
"mempalace_hermes_home",
"mempalace_sessions_dir",
"mempalace_palace_path",
"mempalace_wing",
"mempalace_wakeup_dir",
"mempalace_wakeup_file",
"mempalace_venv_path",
"mempalace_config_path",
"mempalace_mcp_config_path",
"mempalace_session_hook_path",
"mempalace_run_mining",
"mempalace_run_search_test",
"mempalace_run_wake_up",
]
for var in required_vars:
self.assertIn(var, text, f"missing default var: {var}")
def test_role_tasks_contain_required_steps(self):
tasks_path = ROLE_PATH / "tasks" / "main.yml"
self.assertTrue(tasks_path.exists())
text = tasks_path.read_text(encoding="utf-8")
required_steps = [
"Create mempalace virtual environment",
"Install mempalace package",
"Deploy mempalace.yaml configuration",
"Deploy Hermes MCP mempalace config",
"Deploy session-start wake-up hook",
"Mine Hermes home directory",
"Mine session history",
"Run search test",
"Generate wake-up context",
]
for step in required_steps:
self.assertIn(step, text, f"missing task: {step}")
def test_role_templates_are_valid(self):
yaml_template = ROLE_PATH / "templates" / "mempalace.yaml.j2"
mcp_template = ROLE_PATH / "templates" / "hermes-mcp-mempalace.yaml.j2"
hook_template = ROLE_PATH / "templates" / "session-start-mempalace.sh.j2"
self.assertTrue(yaml_template.exists())
self.assertTrue(mcp_template.exists())
self.assertTrue(hook_template.exists())
yaml_text = yaml_template.read_text(encoding="utf-8")
self.assertIn("wing: {{ mempalace_wing }}", yaml_text)
self.assertIn("palace: {{ mempalace_palace_path }}", yaml_text)
self.assertIn("rooms:", yaml_text)
mcp_text = mcp_template.read_text(encoding="utf-8")
self.assertIn("mcp_servers:", mcp_text)
self.assertIn("mempalace:", mcp_text)
self.assertIn("mempalace.mcp_server", mcp_text)
hook_text = hook_template.read_text(encoding="utf-8")
self.assertIn("mempalace wake-up", hook_text)
self.assertIn("HERMES_MEMPALACE_WAKEUP_FILE", hook_text)
def test_playbook_exists_and_targets_fleet(self):
self.assertTrue(PLAYBOOK_PATH.exists(), "deploy_mempalace.yml playbook missing")
text = PLAYBOOK_PATH.read_text(encoding="utf-8")
self.assertIn("hosts: fleet", text)
self.assertIn("../roles/mempalace", text)
self.assertIn("mempalace_venv_path", text)
if __name__ == "__main__":
unittest.main()

View File

@@ -85,6 +85,8 @@ class TestMempalaceEzraIntegration(unittest.TestCase):
"mcp_servers:",
"HERMES_MEMPALACE_WAKEUP_FILE",
"Metrics reply for #568",
"Fleet Ansible deployment",
"ansible-playbook",
]
for snippet in required:
self.assertIn(snippet, text)

View File

@@ -1,52 +0,0 @@
from importlib.util import module_from_spec, spec_from_file_location
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parent.parent
GAME_PATH = ROOT / "evennia" / "timmy_world" / "game.py"
def load_game_module():
spec = spec_from_file_location("tower_game_relationships", GAME_PATH)
module = module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(module)
module.random.seed(0)
return module
class TestTowerGameNpcRelationships(unittest.TestCase):
def test_each_npc_tracks_trust_for_every_other_npc(self):
module = load_game_module()
world = module.World()
npc_names = [name for name, char in world.characters.items() if not char.get("is_player", False)]
for npc_name in npc_names:
with self.subTest(npc=npc_name):
trust_map = world.characters[npc_name]["trust"]
expected = set(npc_names) - {npc_name}
self.assertTrue(expected.issubset(set(trust_map)), f"{npc_name} missing NPC trust keys: {sorted(expected - set(trust_map))}")
def test_offscreen_npc_conversations_create_friendship_and_tension(self):
module = load_game_module()
engine = module.GameEngine()
engine.start_new_game()
result = engine.run_tick("look")
friendships = {tuple(rel["pair"]) for rel in engine.world.state["npc_friendships"]}
tensions = {tuple(rel["pair"]) for rel in engine.world.state["npc_tensions"]}
self.assertIn(("Kimi", "Marcus"), friendships)
self.assertIn(("Bezalel", "ClawCode"), tensions)
self.assertTrue(any("while you are away" in line.lower() for line in result["world_events"]))
garden_desc = engine.world.get_room_desc("Garden", "Timmy")
forge_desc = engine.world.get_room_desc("Forge", "Timmy")
self.assertIn("Marcus and Kimi", garden_desc)
self.assertIn("Bezalel and ClawCode", forge_desc)
if __name__ == "__main__":
unittest.main()