Move Epiphany state off JSON ledgers

This commit is contained in:
Meta Vens 2026-05-06 05:57:33 +01:00
commit 14c69bbef3
35 changed files with 2117 additions and 1703 deletions

View file

@ -10,6 +10,7 @@ from tempfile import TemporaryDirectory
from typing import Any
from epiphany_agent_memory import DEFAULT_AGENT_DIR
from epiphany_agent_memory import resolve_store_path
from epiphany_agent_memory import ROLE_TARGETS
from epiphany_agent_memory import apply_self_patch
from epiphany_agent_memory import validate_all
@ -191,18 +192,18 @@ def run_status(args: argparse.Namespace) -> dict[str, Any]:
def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
with TemporaryDirectory() as tmp:
tmp_dir = Path(tmp)
agent_dir = tmp_dir / "agents"
agent_store = tmp_dir / "agents.msgpack"
store_file = tmp_dir / "heartbeats.msgpack"
artifact_dir = tmp_dir / "artifacts"
import shutil
shutil.copytree(args.agent_dir, agent_dir)
shutil.copy2(resolve_store_path(args.agent_dir), agent_store)
native_heartbeat_command("init", "--store", str(store_file), "--target-heartbeat-rate", "1.0")
first_args = argparse.Namespace(
state_file=None,
store_file=store_file,
artifact_dir=artifact_dir,
agent_dir=agent_dir,
agent_dir=agent_store,
target_heartbeat_rate=1.0,
coordinator_action="continueImplementation",
target_role=None,
@ -230,7 +231,7 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
state_file=None,
store_file=store_file,
artifact_dir=artifact_dir,
agent_dir=agent_dir,
agent_dir=agent_store,
target_heartbeat_rate=1.0,
coordinator_action=None,
target_role=None,
@ -241,7 +242,7 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
defer_completion=False,
)
idle = run_tick(second_args)
validation_errors = validate_all(agent_dir)
validation_errors = validate_all(agent_store)
initiative_errors = [
*validate_initiative_schedule_shape(work["schedule"]),
*validate_initiative_schedule_shape(idle["schedule"]),

View file

@ -2,17 +2,25 @@ from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_AGENT_DIR = ROOT / "state" / "agents"
SCHEMA_VERSION = "ghostlight.agent_state.v0"
DEFAULT_AGENT_STORE = ROOT / "state" / "agents.msgpack"
LEGACY_AGENT_DIR = ROOT / "state" / "agents"
DEFAULT_AGENT_DIR = DEFAULT_AGENT_STORE
AGENT_MEMORY_STORE_BIN = "epiphany-agent-memory-store"
AGENT_MEMORY_STORE_EXE = (
Path(os.environ.get("CARGO_TARGET_DIR", r"C:\Users\Meta\.cargo-target-codex"))
/ "debug"
/ "epiphany-agent-memory-store.exe"
)
ROLE_TARGETS = {
"imagination": ("epiphany.imagination", "imagination.agent-state.json"),
@ -25,436 +33,55 @@ ROLE_TARGETS = {
"coordinator": ("epiphany.self", "self.agent-state.json"),
}
ALLOWED_PATCH_FIELDS = {
"agentId",
"reason",
"evidenceIds",
"semanticMemories",
"episodicMemories",
"relationshipMemories",
"goals",
"values",
"privateNotes",
}
FORBIDDEN_PATCH_FIELDS = {
"statePatch",
"objective",
"activeSubgoalId",
"subgoals",
"invariants",
"graphs",
"graphFrontier",
"graphCheckpoint",
"scratch",
"investigationCheckpoint",
"jobBindings",
"planning",
"churn",
"mode",
"codeEdits",
"files",
"authorityScope",
"backendJobId",
"rawResult",
}
def resolve_store_path(path: Path | None = None) -> Path:
if path is None:
return DEFAULT_AGENT_STORE
if path.suffix == ".msgpack":
return path
candidate = path / "agents.msgpack"
if candidate.exists():
return candidate
if path == DEFAULT_AGENT_DIR and DEFAULT_AGENT_STORE.exists():
return DEFAULT_AGENT_STORE
return candidate
def native_agent_memory_command(*args: str) -> dict[str, Any]:
if AGENT_MEMORY_STORE_EXE.exists():
command = [str(AGENT_MEMORY_STORE_EXE), *args]
else:
command = [
"cargo",
"run",
"--quiet",
"--manifest-path",
str(ROOT / "epiphany-core" / "Cargo.toml"),
"--bin",
AGENT_MEMORY_STORE_BIN,
"--",
*args,
]
completed = subprocess.run(
command,
cwd=ROOT,
text=True,
capture_output=True,
check=False,
)
if completed.returncode != 0:
message = completed.stderr.strip() or completed.stdout.strip() or f"{AGENT_MEMORY_STORE_BIN} failed"
raise ValueError(message)
try:
return json.loads(completed.stdout)
except json.JSONDecodeError as exc:
raise ValueError(f"{AGENT_MEMORY_STORE_BIN} returned non-JSON output: {completed.stdout}") from exc
def load_json(path: Path) -> Any:
return json.loads(path.read_text(encoding="utf-8"))
def write_json(path: Path, value: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, indent=2, sort_keys=False) + "\n", encoding="utf-8")
def role_target(role_id: str) -> tuple[str, Path]:
try:
agent_id, filename = ROLE_TARGETS[role_id]
except KeyError as exc:
raise ValueError(f"unknown role id: {role_id}") from exc
return agent_id, DEFAULT_AGENT_DIR / filename
def require_object(value: Any, path: str, errors: list[str]) -> dict[str, Any]:
if isinstance(value, dict):
return value
errors.append(f"{path} must be an object")
return {}
def require_array(value: Any, path: str, errors: list[str]) -> list[Any]:
if isinstance(value, list):
return value
errors.append(f"{path} must be an array")
return []
def check_unit(value: Any, path: str, errors: list[str]) -> None:
if not isinstance(value, (int, float)) or isinstance(value, bool) or not 0 <= float(value) <= 1:
errors.append(f"{path} must be a number between 0 and 1")
def check_string(value: Any, path: str, errors: list[str], *, max_len: int = 800) -> None:
if not isinstance(value, str) or not value.strip() or len(value) > max_len:
errors.append(f"{path} must be non-empty text under {max_len} characters")
def validate_memory(record: Any, path: str, errors: list[str]) -> None:
item = require_object(record, path, errors)
if not item:
return
check_string(item.get("memory_id"), f"{path}.memory_id", errors, max_len=120)
check_string(item.get("summary"), f"{path}.summary", errors, max_len=800)
check_unit(item.get("salience"), f"{path}.salience", errors)
check_unit(item.get("confidence"), f"{path}.confidence", errors)
def validate_agent_file(path: Path) -> list[str]:
errors: list[str] = []
try:
document = load_json(path)
except Exception as exc:
return [f"{path}: failed to parse JSON: {exc}"]
root = require_object(document, str(path), errors)
if root.get("schema_version") != SCHEMA_VERSION:
errors.append(f"{path}: schema_version must be {SCHEMA_VERSION!r}")
world = require_object(root.get("world"), f"{path}.world", errors)
for key in ("world_id", "setting", "canon_context"):
if key == "canon_context":
require_array(world.get(key), f"{path}.world.{key}", errors)
else:
check_string(world.get(key), f"{path}.world.{key}", errors)
time = require_object(world.get("time"), f"{path}.world.time", errors)
check_string(time.get("label"), f"{path}.world.time.label", errors, max_len=200)
agents = require_array(root.get("agents"), f"{path}.agents", errors)
if len(agents) != 1:
errors.append(f"{path}.agents must contain exactly one agent")
for index, raw_agent in enumerate(agents):
agent = require_object(raw_agent, f"{path}.agents[{index}]", errors)
check_string(agent.get("agent_id"), f"{path}.agents[{index}].agent_id", errors, max_len=120)
identity = require_object(agent.get("identity"), f"{path}.agents[{index}].identity", errors)
for key in ("name", "origin", "public_description"):
check_string(identity.get(key), f"{path}.agents[{index}].identity.{key}", errors)
require_array(identity.get("roles"), f"{path}.agents[{index}].identity.roles", errors)
canonical = require_object(
agent.get("canonical_state"), f"{path}.agents[{index}].canonical_state", errors
)
for key in (
"underlying_organization",
"stable_dispositions",
"behavioral_dimensions",
"presentation_strategy",
"voice_style",
"situational_state",
):
require_object(canonical.get(key), f"{path}.agents[{index}].canonical_state.{key}", errors)
values = require_array(
canonical.get("values"), f"{path}.agents[{index}].canonical_state.values", errors
)
for value_index, raw_value in enumerate(values):
value = require_object(
raw_value,
f"{path}.agents[{index}].canonical_state.values[{value_index}]",
errors,
)
check_string(value.get("value_id"), f"{path}.values[{value_index}].value_id", errors)
check_string(value.get("label"), f"{path}.values[{value_index}].label", errors)
check_unit(value.get("priority"), f"{path}.values[{value_index}].priority", errors)
if not isinstance(value.get("unforgivable_if_betrayed"), bool):
errors.append(f"{path}.values[{value_index}].unforgivable_if_betrayed must be boolean")
goals = require_array(agent.get("goals"), f"{path}.agents[{index}].goals", errors)
for goal_index, raw_goal in enumerate(goals):
goal = require_object(raw_goal, f"{path}.agents[{index}].goals[{goal_index}]", errors)
check_string(goal.get("goal_id"), f"{path}.goals[{goal_index}].goal_id", errors)
check_string(goal.get("description"), f"{path}.goals[{goal_index}].description", errors)
if goal.get("scope") not in {"immediate", "scene", "case", "arc", "life"}:
errors.append(f"{path}.goals[{goal_index}].scope is not a Ghostlight scope")
check_unit(goal.get("priority"), f"{path}.goals[{goal_index}].priority", errors)
check_string(goal.get("emotional_stake"), f"{path}.goals[{goal_index}].emotional_stake", errors)
if goal.get("status") not in {"active", "blocked", "dormant", "resolved", "abandoned"}:
errors.append(f"{path}.goals[{goal_index}].status is not a Ghostlight status")
memories = require_object(agent.get("memories"), f"{path}.agents[{index}].memories", errors)
for bundle_name in ("episodic", "semantic", "relationship_summaries"):
for memory_index, raw_memory in enumerate(
require_array(memories.get(bundle_name), f"{path}.memories.{bundle_name}", errors)
):
validate_memory(raw_memory, f"{path}.memories.{bundle_name}[{memory_index}]", errors)
require_array(
agent.get("perceived_state_overlays"),
f"{path}.agents[{index}].perceived_state_overlays",
errors,
)
for key in ("relationships", "events", "scenes"):
require_array(root.get(key), f"{path}.{key}", errors)
return errors
def valid_identifier(value: Any, prefix: str) -> bool:
return (
isinstance(value, str)
and value.startswith(prefix)
and len(value) <= 120
and all(ch.isascii() and (ch.isalnum() or ch in "-_.") for ch in value)
)
def review_patch(role_id: str, patch: Any) -> dict[str, Any]:
agent_id, target_path = role_target(role_id)
reasons: list[str] = []
if not isinstance(patch, dict):
reasons.append("selfPatch must be a JSON object")
else:
actual_agent = patch.get("agentId")
if actual_agent != agent_id:
reasons.append(f"selfPatch agentId {actual_agent!r} does not match this lane; expected {agent_id!r}")
reason = patch.get("reason")
if not isinstance(reason, str) or len(reason.strip()) < 16 or len(reason) > 800:
reasons.append("selfPatch reason must be a bounded explanation of at least 16 characters")
for key in patch:
if key in FORBIDDEN_PATCH_FIELDS:
reasons.append(
f"selfPatch field {key!r} is project truth or authority; use the proper Epiphany control surface instead"
)
elif key not in ALLOWED_PATCH_FIELDS:
reasons.append(f"selfPatch field {key!r} is not part of the bounded memory mutation contract")
mutation_count = 0
for field in ("semanticMemories", "episodicMemories", "relationshipMemories"):
mutation_count += review_memory_patch_array(patch, field, reasons)
mutation_count += review_goal_patch_array(patch, reasons)
mutation_count += review_value_patch_array(patch, reasons)
mutation_count += review_private_notes(patch, reasons)
review_string_array(patch, "evidenceIds", reasons, max_items=16, max_len=160)
if mutation_count == 0:
reasons.append(
"selfPatch must contain at least one semantic memory, episodic memory, relationship memory, goal, value, or private note"
)
return {
"status": "rejected" if reasons else "accepted",
"targetAgentId": agent_id,
"targetPath": str(target_path),
"reasons": reasons,
}
def review_memory_patch_array(patch: dict[str, Any], field: str, reasons: list[str]) -> int:
if field not in patch:
return 0
value = patch[field]
if not isinstance(value, list):
reasons.append(f"selfPatch {field} must be an array")
return 0
if len(value) > 8:
reasons.append(f"selfPatch {field} may contain at most 8 records")
for index, item in enumerate(value):
if not isinstance(item, dict):
reasons.append(f"selfPatch {field}[{index}] must be an object")
continue
if not valid_identifier(item.get("memoryId"), "mem-"):
reasons.append(f"selfPatch {field}[{index}].memoryId must start with 'mem-' and avoid whitespace")
check_patch_text(item.get("summary"), f"selfPatch {field}[{index}].summary", reasons, 600)
check_patch_unit(item.get("salience"), f"selfPatch {field}[{index}].salience", reasons)
check_patch_unit(item.get("confidence"), f"selfPatch {field}[{index}].confidence", reasons)
return len(value)
def review_goal_patch_array(patch: dict[str, Any], reasons: list[str]) -> int:
if "goals" not in patch:
return 0
value = patch["goals"]
if not isinstance(value, list):
reasons.append("selfPatch goals must be an array")
return 0
if len(value) > 6:
reasons.append("selfPatch goals may contain at most 6 records")
for index, item in enumerate(value):
if not isinstance(item, dict):
reasons.append(f"selfPatch goals[{index}] must be an object")
continue
if not valid_identifier(item.get("goalId"), "goal-"):
reasons.append(f"selfPatch goals[{index}].goalId must start with 'goal-' and avoid whitespace")
check_patch_text(item.get("description"), f"selfPatch goals[{index}].description", reasons, 700)
if item.get("scope") not in {"immediate", "scene", "case", "arc", "life"}:
reasons.append(f"selfPatch goals[{index}].scope is not a Ghostlight scope")
check_patch_unit(item.get("priority"), f"selfPatch goals[{index}].priority", reasons)
check_patch_text(item.get("emotionalStake"), f"selfPatch goals[{index}].emotionalStake", reasons, 400)
if item.get("status") not in {"active", "blocked", "dormant", "resolved", "abandoned"}:
reasons.append(f"selfPatch goals[{index}].status is not a Ghostlight status")
return len(value)
def review_value_patch_array(patch: dict[str, Any], reasons: list[str]) -> int:
if "values" not in patch:
return 0
value = patch["values"]
if not isinstance(value, list):
reasons.append("selfPatch values must be an array")
return 0
if len(value) > 6:
reasons.append("selfPatch values may contain at most 6 records")
for index, item in enumerate(value):
if not isinstance(item, dict):
reasons.append(f"selfPatch values[{index}] must be an object")
continue
if not valid_identifier(item.get("valueId"), "value-"):
reasons.append(f"selfPatch values[{index}].valueId must start with 'value-' and avoid whitespace")
check_patch_text(item.get("label"), f"selfPatch values[{index}].label", reasons, 240)
check_patch_unit(item.get("priority"), f"selfPatch values[{index}].priority", reasons)
if not isinstance(item.get("unforgivableIfBetrayed"), bool):
reasons.append(f"selfPatch values[{index}].unforgivableIfBetrayed must be boolean")
return len(value)
def review_private_notes(patch: dict[str, Any], reasons: list[str]) -> int:
if "privateNotes" not in patch:
return 0
value = patch["privateNotes"]
if not isinstance(value, list):
reasons.append("selfPatch privateNotes must be an array")
return 0
if len(value) > 6:
reasons.append("selfPatch privateNotes may contain at most 6 records")
for index, item in enumerate(value):
check_patch_text(item, f"selfPatch privateNotes[{index}]", reasons, 600)
return len(value)
def review_string_array(
patch: dict[str, Any],
field: str,
reasons: list[str],
*,
max_items: int,
max_len: int,
) -> None:
if field not in patch:
return
value = patch[field]
if not isinstance(value, list):
reasons.append(f"selfPatch {field} must be an array")
return
if len(value) > max_items:
reasons.append(f"selfPatch {field} may contain at most {max_items} records")
for index, item in enumerate(value):
check_patch_text(item, f"selfPatch {field}[{index}]", reasons, max_len)
def check_patch_text(value: Any, path: str, reasons: list[str], max_len: int) -> None:
if not isinstance(value, str) or not value.strip() or len(value) > max_len:
reasons.append(f"{path} must be non-empty text under {max_len} characters")
def check_patch_unit(value: Any, path: str, reasons: list[str]) -> None:
if not isinstance(value, (int, float)) or isinstance(value, bool) or not 0 <= float(value) <= 1:
reasons.append(f"{path} must be between 0 and 1")
def normalized_memory(item: dict[str, Any]) -> dict[str, Any]:
record = {
"memory_id": item["memoryId"],
"summary": item["summary"],
"salience": item["salience"],
"confidence": item["confidence"],
}
if "linkedEventIds" in item:
record["linked_event_ids"] = item["linkedEventIds"]
if "linkedRelationshipId" in item:
record["linked_relationship_id"] = item["linkedRelationshipId"]
return record
def normalized_goal(item: dict[str, Any]) -> dict[str, Any]:
return {
"goal_id": item["goalId"],
"description": item["description"],
"scope": item["scope"],
"priority": item["priority"],
"emotional_stake": item["emotionalStake"],
"blockers": item.get("blockers", []),
"status": item["status"],
}
def normalized_value(item: dict[str, Any]) -> dict[str, Any]:
return {
"value_id": item["valueId"],
"label": item["label"],
"priority": item["priority"],
"unforgivable_if_betrayed": item["unforgivableIfBetrayed"],
}
def upsert_by_id(records: list[dict[str, Any]], incoming: list[dict[str, Any]], id_field: str) -> list[dict[str, Any]]:
index = {record.get(id_field): record for record in records if isinstance(record, dict)}
for item in incoming:
index[item[id_field]] = item
return list(index.values())
def apply_self_patch(role_id: str, patch: dict[str, Any], *, agent_dir: Path = DEFAULT_AGENT_DIR) -> dict[str, Any]:
review = review_patch(role_id, patch)
if review["status"] != "accepted":
return review
_, filename = ROLE_TARGETS[role_id]
path = agent_dir / filename
document = load_json(path)
agent = document["agents"][0]
memories = agent["memories"]
memories["semantic"] = upsert_by_id(
memories["semantic"],
[normalized_memory(item) for item in patch.get("semanticMemories", [])],
"memory_id",
)
memories["episodic"] = upsert_by_id(
memories["episodic"],
[normalized_memory(item) for item in patch.get("episodicMemories", [])],
"memory_id",
)
memories["relationship_summaries"] = upsert_by_id(
memories["relationship_summaries"],
[normalized_memory(item) for item in patch.get("relationshipMemories", [])],
"memory_id",
)
agent["goals"] = upsert_by_id(
agent["goals"],
[normalized_goal(item) for item in patch.get("goals", [])],
"goal_id",
)
canonical = agent["canonical_state"]
canonical["values"] = upsert_by_id(
canonical["values"],
[normalized_value(item) for item in patch.get("values", [])],
"value_id",
)
private_notes = agent["identity"].setdefault("private_notes", [])
private_notes.extend(patch.get("privateNotes", []))
agent["identity"]["private_notes"] = private_notes[-32:]
write_json(path, document)
review["applied"] = True
return review
def validate_all(agent_dir: Path) -> list[str]:
errors: list[str] = []
for role_id, (_, filename) in ROLE_TARGETS.items():
path = agent_dir / filename
if not path.exists():
errors.append(f"{role_id}: missing {path}")
continue
errors.extend(validate_agent_file(path))
return errors
def parse_patch_arg(value: str) -> Any:
path = Path(value)
if path.exists():
@ -462,99 +89,191 @@ def parse_patch_arg(value: str) -> Any:
return json.loads(value)
def role_target(role_id: str) -> tuple[str, Path]:
try:
agent_id, filename = ROLE_TARGETS[role_id]
except KeyError as exc:
raise ValueError(f"unknown role id: {role_id}") from exc
return agent_id, DEFAULT_AGENT_STORE
def migrate_json_dir(agent_dir: Path = LEGACY_AGENT_DIR, store: Path = DEFAULT_AGENT_STORE) -> dict[str, Any]:
return native_agent_memory_command(
"migrate-json-dir",
"--agent-dir",
str(agent_dir),
"--store",
str(store),
)
def validate_all(agent_dir: Path = DEFAULT_AGENT_DIR) -> list[str]:
store = resolve_store_path(agent_dir)
result = native_agent_memory_command("validate", "--store", str(store))
return result.get("errors", [])
def review_patch(role_id: str, patch: Any, *, store: Path = DEFAULT_AGENT_STORE) -> dict[str, Any]:
return native_agent_memory_command(
"review-patch",
"--store",
str(resolve_store_path(store)),
"--role-id",
role_id,
"--patch",
json.dumps(patch),
)
def apply_self_patch(
role_id: str,
patch: dict[str, Any],
*,
agent_dir: Path = DEFAULT_AGENT_DIR,
) -> dict[str, Any]:
return native_agent_memory_command(
"apply-patch",
"--store",
str(resolve_store_path(agent_dir)),
"--role-id",
role_id,
"--patch",
json.dumps(patch),
)
def status(store: Path = DEFAULT_AGENT_STORE) -> dict[str, Any]:
return native_agent_memory_command("status", "--store", str(resolve_store_path(store)))
def project_json_dir(store: Path = DEFAULT_AGENT_STORE, output_dir: Path = DEFAULT_AGENT_DIR) -> dict[str, Any]:
return native_agent_memory_command(
"project-json-dir",
"--store",
str(resolve_store_path(store)),
"--output-dir",
str(output_dir),
)
def run_smoke(store: Path = DEFAULT_AGENT_STORE) -> dict[str, Any]:
errors = validate_all(store)
if errors:
return {"ok": False, "phase": "validate", "errors": errors}
accepted_patch = {
"agentId": "epiphany.body",
"reason": "The Body should remember accepted graph growth must be source-grounded and bounded.",
"semanticMemories": [
{
"memoryId": "mem-body-smoke-source-grounding",
"summary": "A modeling self-memory request is acceptable when it improves future graph/checkpoint judgment without smuggling project truth.",
"salience": 0.74,
"confidence": 0.86,
}
],
}
accepted = review_patch("modeling", accepted_patch, store=store)
wrong_role = review_patch("verification", accepted_patch, store=store)
forbidden = review_patch(
"modeling",
{
"agentId": "epiphany.body",
"reason": "This tries to put project state in lane memory, which should be refused.",
"graphs": {},
"semanticMemories": [
{
"memoryId": "mem-body-bad-project-truth",
"summary": "Bad patch.",
"salience": 0.5,
"confidence": 0.5,
}
],
},
store=store,
)
with TemporaryDirectory() as tmp:
tmp_store = Path(tmp) / "agents.msgpack"
shutil.copy2(resolve_store_path(store), tmp_store)
applied = apply_self_patch("modeling", accepted_patch, agent_dir=tmp_store)
temp_errors = validate_all(tmp_store)
ok = (
accepted["status"] == "accepted"
and wrong_role["status"] == "rejected"
and forbidden["status"] == "rejected"
and applied["status"] == "accepted"
and not temp_errors
)
return {
"ok": ok,
"accepted": accepted,
"wrongRole": wrong_role,
"forbidden": forbidden,
"applied": applied,
"tempValidationErrors": temp_errors,
}
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Review and apply Epiphany specialist self-memory patches.")
subparsers = parser.add_subparsers(dest="command", required=True)
migrate_parser = subparsers.add_parser("migrate-json-dir")
migrate_parser.add_argument("--agent-dir", type=Path, default=LEGACY_AGENT_DIR)
migrate_parser.add_argument("--store", type=Path, default=DEFAULT_AGENT_STORE)
project_parser = subparsers.add_parser("project-json-dir")
project_parser.add_argument("--store", type=Path, default=DEFAULT_AGENT_STORE)
project_parser.add_argument("--output-dir", type=Path, default=DEFAULT_AGENT_DIR)
status_parser = subparsers.add_parser("status")
status_parser.add_argument("--store", type=Path, default=DEFAULT_AGENT_STORE)
validate_parser = subparsers.add_parser("validate")
validate_parser.add_argument("--agent-dir", type=Path, default=DEFAULT_AGENT_DIR)
validate_parser.add_argument("--agent-dir", type=Path, default=DEFAULT_AGENT_STORE)
review_parser = subparsers.add_parser("review-patch")
review_parser.add_argument("--role-id", required=True, choices=sorted(ROLE_TARGETS))
review_parser.add_argument("--patch", required=True, help="JSON string or path to a JSON patch")
review_parser.add_argument("--store", type=Path, default=DEFAULT_AGENT_STORE)
apply_parser = subparsers.add_parser("apply-patch")
apply_parser.add_argument("--role-id", required=True, choices=sorted(ROLE_TARGETS))
apply_parser.add_argument("--patch", required=True, help="JSON string or path to a JSON patch")
apply_parser.add_argument("--agent-dir", type=Path, default=DEFAULT_AGENT_DIR)
apply_parser.add_argument("--agent-dir", type=Path, default=DEFAULT_AGENT_STORE)
smoke_parser = subparsers.add_parser("smoke")
smoke_parser.add_argument("--agent-dir", type=Path, default=DEFAULT_AGENT_DIR)
smoke_parser.add_argument("--store", type=Path, default=DEFAULT_AGENT_STORE)
args = parser.parse_args(argv)
if args.command == "validate":
errors = validate_all(args.agent_dir)
print(json.dumps({"ok": not errors, "errors": errors}, indent=2))
return 0 if not errors else 1
if args.command == "review-patch":
print(json.dumps(review_patch(args.role_id, parse_patch_arg(args.patch)), indent=2))
return 0
if args.command == "apply-patch":
patch = parse_patch_arg(args.patch)
result = apply_self_patch(args.role_id, patch, agent_dir=args.agent_dir)
print(json.dumps(result, indent=2))
return 0 if result["status"] == "accepted" else 1
if args.command == "smoke":
errors = validate_all(args.agent_dir)
if errors:
print(json.dumps({"ok": False, "phase": "validate", "errors": errors}, indent=2))
return 1
accepted_patch = {
"agentId": "epiphany.body",
"reason": "The Body should remember accepted graph growth must be source-grounded and bounded.",
"semanticMemories": [
{
"memoryId": "mem-body-smoke-source-grounding",
"summary": "A modeling self-memory request is acceptable when it improves future graph/checkpoint judgment without smuggling project truth.",
"salience": 0.74,
"confidence": 0.86,
}
],
}
accepted = review_patch("modeling", accepted_patch)
wrong_role = review_patch("verification", accepted_patch)
forbidden = review_patch(
"modeling",
{
"agentId": "epiphany.body",
"reason": "This tries to put project state in lane memory, which should be refused.",
"graphs": {},
"semanticMemories": [
{
"memoryId": "mem-body-bad-project-truth",
"summary": "Bad patch.",
"salience": 0.5,
"confidence": 0.5,
}
],
},
)
with TemporaryDirectory() as tmp:
tmp_dir = Path(tmp)
shutil.copytree(args.agent_dir, tmp_dir / "agents")
applied = apply_self_patch("modeling", accepted_patch, agent_dir=tmp_dir / "agents")
temp_errors = validate_all(tmp_dir / "agents")
ok = (
accepted["status"] == "accepted"
and wrong_role["status"] == "rejected"
and forbidden["status"] == "rejected"
and applied["status"] == "accepted"
and not temp_errors
)
print(
json.dumps(
{
"ok": ok,
"accepted": accepted,
"wrongRole": wrong_role,
"forbidden": forbidden,
"applied": applied,
"tempValidationErrors": temp_errors,
},
indent=2,
)
)
return 0 if ok else 1
try:
if args.command == "migrate-json-dir":
print(json.dumps(migrate_json_dir(args.agent_dir, args.store), indent=2))
return 0
if args.command == "project-json-dir":
print(json.dumps(project_json_dir(args.store, args.output_dir), indent=2))
return 0
if args.command == "status":
print(json.dumps(status(args.store), indent=2))
return 0
if args.command == "validate":
errors = validate_all(args.agent_dir)
print(json.dumps({"ok": not errors, "errors": errors}, indent=2))
return 0 if not errors else 1
if args.command == "review-patch":
print(json.dumps(review_patch(args.role_id, parse_patch_arg(args.patch), store=args.store), indent=2))
return 0
if args.command == "apply-patch":
patch = parse_patch_arg(args.patch)
result = apply_self_patch(args.role_id, patch, agent_dir=args.agent_dir)
print(json.dumps(result, indent=2))
return 0 if result["status"] == "accepted" else 1
if args.command == "smoke":
result = run_smoke(args.store)
print(json.dumps(result, indent=2))
return 0 if result["ok"] else 1
except ValueError as exc:
print(json.dumps({"ok": False, "error": str(exc)}, indent=2))
return 1
raise AssertionError(args.command)

View file

@ -6,6 +6,7 @@ import json
import os
from pathlib import Path
import sys
import tomllib
from typing import Any
from urllib import error
from urllib import request
@ -13,7 +14,7 @@ from uuid import uuid4
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_CONFIG = ROOT / "state" / "face-discord.json"
DEFAULT_CONFIG = ROOT / "state" / "face-discord.toml"
DEFAULT_ARTIFACT_DIR = ROOT / ".epiphany-face"
DISCORD_API = "https://discord.com/api/v10"
CHAT_SCHEMA_VERSION = "epiphany.face_chat.v0"
@ -39,6 +40,17 @@ def load_json(path: Path) -> Any:
return json.loads(path.read_text(encoding="utf-8"))
def load_config(path: Path) -> dict[str, Any]:
if path.suffix.lower() == ".toml":
with path.open("rb") as handle:
data = tomllib.load(handle)
else:
data = load_json(path)
if not isinstance(data, dict):
raise ValueError(f"Face config must be an object: {path}")
return data
def write_json(path: Path, value: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, indent=2, sort_keys=False) + "\n", encoding="utf-8")
@ -178,7 +190,7 @@ def post_message(content: str, *, channel_id: str, token: str) -> dict[str, Any]
def run_draft(args: argparse.Namespace) -> dict[str, Any]:
config = load_json(args.config)
config = load_config(args.config)
content = read_text_arg(args.content)
if not content.strip():
raise ValueError("Face chat content is empty")
@ -207,7 +219,7 @@ def run_bubble(args: argparse.Namespace) -> dict[str, Any]:
def run_post(args: argparse.Namespace) -> dict[str, Any]:
config = load_json(args.config)
config = load_config(args.config)
content = read_text_arg(args.content)
if not content.strip():
raise ValueError("Face chat content is empty")

View file

@ -21,6 +21,7 @@ from epiphany_agent_heartbeat import heartbeat_status
from epiphany_agent_heartbeat import run_tick as run_heartbeat_tick
from epiphany_agent_telemetry import write_transcript_telemetry
from epiphany_agent_memory import apply_self_patch
from epiphany_agent_memory import DEFAULT_AGENT_STORE
from epiphany_face_discord import DEFAULT_ARTIFACT_DIR as DEFAULT_FACE_ARTIFACT_DIR
from epiphany_face_discord import latest_face_artifacts
from epiphany_face_discord import write_bubble
@ -37,7 +38,7 @@ from epiphany_unity_bridge import bridge_guidance as unity_bridge_guidance
DEFAULT_CODEX_HOME = ROOT / ".epiphany-gui" / "codex-home"
DEFAULT_ARTIFACT_ROOT = ROOT / ".epiphany-gui" / "actions"
DEFAULT_AGENT_MEMORY_DIR = ROOT / "state" / "agents"
DEFAULT_AGENT_MEMORY_DIR = DEFAULT_AGENT_STORE
EPIPHANY_PROMPTS_PATH = (
ROOT
/ "vendor"

View file

@ -10,6 +10,7 @@ from typing import Any
from epiphany_agent_telemetry import write_transcript_telemetry
from epiphany_agent_memory import apply_self_patch
from epiphany_agent_memory import DEFAULT_AGENT_STORE
from epiphany_mvp_status import DEFAULT_APP_SERVER
from epiphany_mvp_status import collect_status
from epiphany_mvp_status import render_status
@ -28,7 +29,7 @@ from epiphany_phase6_role_smoke import complete_role_backend_job
DEFAULT_ARTIFACT_DIR = ROOT / ".epiphany-dogfood" / "coordinator"
DEFAULT_CODEX_HOME = Path(os.environ.get("CODEX_HOME", Path.home() / ".codex"))
DEFAULT_AGENT_MEMORY_DIR = ROOT / "state" / "agents"
DEFAULT_AGENT_MEMORY_DIR = DEFAULT_AGENT_STORE
TERMINAL_ROLE_STATUSES = {"completed", "failed", "cancelled"}
TERMINAL_REORIENT_STATUSES = {"completed", "failed", "cancelled"}
STOP_ACTIONS = {

View file

@ -7,6 +7,8 @@ from pathlib import Path
from types import SimpleNamespace
from typing import Any
from epiphany_agent_memory import project_json_dir
from epiphany_agent_memory import resolve_store_path
from epiphany_mvp_coordinator import DEFAULT_APP_SERVER
from epiphany_mvp_coordinator import DEFAULT_AGENT_MEMORY_DIR
from epiphany_mvp_coordinator import run_coordinator
@ -39,6 +41,7 @@ def coordinator_args(
dry_compact: bool = False,
auto_review: bool = False,
max_steps: int = 4,
agent_memory_store: Path | None = None,
) -> argparse.Namespace:
artifact_dir = artifact_root / name
return SimpleNamespace(
@ -47,7 +50,7 @@ def coordinator_args(
cwd=ROOT,
codex_home=artifact_dir / "codex-home",
artifact_dir=artifact_dir,
agent_memory_dir=artifact_root / "agent-memory",
agent_memory_dir=agent_memory_store or artifact_root / "agent-memory.msgpack",
mode=mode,
max_steps=max_steps,
poll_seconds=0.1,
@ -99,10 +102,16 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
artifact_root = args.artifact_root.resolve()
reset_artifact_root(artifact_root)
shutil.copytree(DEFAULT_AGENT_MEMORY_DIR, artifact_root / "agent-memory")
agent_memory_store = artifact_root / "agent-memory.msgpack"
shutil.copy2(resolve_store_path(DEFAULT_AGENT_MEMORY_DIR), agent_memory_store)
cold = run_coordinator(
coordinator_args(app_server=app_server, artifact_root=artifact_root, name="cold")
coordinator_args(
app_server=app_server,
artifact_root=artifact_root,
name="cold",
agent_memory_store=agent_memory_store,
)
)
require(
cold["finalAction"]["action"] == "prepareCheckpoint",
@ -145,9 +154,11 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
)
require_artifacts(verification)
require_operator_safe(verification)
projected_memory = artifact_root / "agent-memory-projection"
project_json_dir(agent_memory_store, projected_memory)
require(
"mem-body-phase6-role-smoke"
in (artifact_root / "agent-memory" / "body.agent-state.json").read_text(encoding="utf-8"),
in (projected_memory / "body.agent-state.json").read_text(encoding="utf-8"),
"auto-review coordinator smoke should apply accepted selfPatch to isolated agent memory",
)

View file

@ -2,6 +2,7 @@ from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
from dataclasses import dataclass
@ -17,6 +18,12 @@ MAP_PATH = STATE_DIR / "map.yaml"
SCRATCH_PATH = STATE_DIR / "scratch.md"
BRANCHES_PATH = STATE_DIR / "branches.json"
EVIDENCE_PATH = STATE_DIR / "evidence.jsonl"
LEDGER_STORE_PATH = STATE_DIR / "ledgers.msgpack"
STATE_LEDGER_EXE = (
Path(os.environ.get("CARGO_TARGET_DIR", r"C:\Users\Meta\.cargo-target-codex"))
/ "debug"
/ "epiphany-state-ledger-store.exe"
)
HANDOFF_PATH = NOTES_DIR / "fresh-workspace-handoff.md"
PLAN_PATH = NOTES_DIR / "epiphany-fork-implementation-plan.md"
ALGO_MAP_PATH = NOTES_DIR / "epiphany-current-algorithmic-map.md"
@ -44,6 +51,38 @@ def run_git(args: list[str]) -> str:
return completed.stdout.strip()
def run_state_ledger_status() -> dict[str, Any]:
if STATE_LEDGER_EXE.exists():
command = [
str(STATE_LEDGER_EXE),
"status",
"--store",
str(LEDGER_STORE_PATH),
]
else:
command = [
"cargo",
"run",
"--quiet",
"--manifest-path",
str(ROOT / "epiphany-core" / "Cargo.toml"),
"--bin",
"epiphany-state-ledger-store",
"--",
"status",
"--store",
str(LEDGER_STORE_PATH),
]
completed = subprocess.run(
command,
cwd=ROOT,
check=True,
capture_output=True,
text=True,
)
return json.loads(completed.stdout)
def extract_map_field(name: str) -> str | None:
prefix = f" {name}:"
for line in read_text(MAP_PATH).splitlines():
@ -82,36 +121,25 @@ def current_scratch_subgoal() -> str | None:
def load_evidence() -> list[dict[str, Any]]:
records: list[dict[str, Any]] = []
for line_number, line in enumerate(read_text(EVIDENCE_PATH).splitlines(), start=1):
if not line.strip():
continue
try:
record = json.loads(line)
except json.JSONDecodeError as exc:
raise ValueError(f"evidence line {line_number} is invalid JSON: {exc}") from exc
if not isinstance(record, dict):
raise ValueError(f"evidence line {line_number} is not a JSON object")
records.append(record)
return records
ledger = run_state_ledger_status()
latest = ledger.get("latestEvidence") or []
return list(reversed(latest))
def load_branches() -> dict[str, Any]:
data = json.loads(read_text(BRANCHES_PATH))
if not isinstance(data, dict):
raise ValueError("branches.json must be a JSON object")
branches = data.get("branches")
if not isinstance(branches, list):
raise ValueError("branches.json must contain a branches list")
return data
ledger = run_state_ledger_status()
return {
"branches": [None] * int(ledger.get("branches") or 0),
"activeBranches": int(ledger.get("activeBranches") or 0),
"evidence": int(ledger.get("evidence") or 0),
}
def add_required_file_checks(findings: list[Finding]) -> None:
for path in [
MAP_PATH,
SCRATCH_PATH,
BRANCHES_PATH,
EVIDENCE_PATH,
LEDGER_STORE_PATH,
HANDOFF_PATH,
PLAN_PATH,
ALGO_MAP_PATH,
@ -154,23 +182,17 @@ def add_content_checks(findings: list[Finding]) -> tuple[list[dict[str, Any]], d
try:
evidence = load_evidence()
findings.append(Finding("ok", f"state/evidence.jsonl parses ({len(evidence)} record(s))"))
branches = load_branches()
findings.append(Finding("ok", f"state/ledgers.msgpack parses ({branches.get('evidence', 0)} evidence record(s))"))
except ValueError as exc:
findings.append(Finding("error", str(exc)))
if EVIDENCE_PATH.exists() and EVIDENCE_PATH.stat().st_size > 25_000:
findings.append(Finding("warn", "state/evidence.jsonl is larger than 25 KB; consider distillation"))
try:
branches = load_branches()
active = [
branch
for branch in branches.get("branches", [])
if isinstance(branch, dict) and branch.get("status") == "active"
]
findings.append(Finding("ok", f"state/branches.json parses ({len(active)} active branch(es))"))
active = branches.get("activeBranches", 0)
findings.append(Finding("ok", f"state/ledgers.msgpack has {active} active branch(es)"))
except (json.JSONDecodeError, ValueError) as exc:
findings.append(Finding("error", f"branches.json parse failed: {exc}"))
findings.append(Finding("error", f"state ledger parse failed: {exc}"))
return evidence, branches

View file

@ -2,6 +2,8 @@ from __future__ import annotations
import argparse
import json
import os
import subprocess
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
@ -12,29 +14,47 @@ STATE_DIR = ROOT / "state"
MAP_PATH = STATE_DIR / "map.yaml"
BRANCHES_PATH = STATE_DIR / "branches.json"
EVIDENCE_PATH = STATE_DIR / "evidence.jsonl"
LEDGER_STORE_PATH = STATE_DIR / "ledgers.msgpack"
STATE_LEDGER_BIN = "epiphany-state-ledger-store"
STATE_LEDGER_EXE = (
Path(os.environ.get("CARGO_TARGET_DIR", r"C:\Users\Meta\.cargo-target-codex"))
/ "debug"
/ "epiphany-state-ledger-store.exe"
)
def native_ledger_command(*args: str) -> dict[str, Any]:
if STATE_LEDGER_EXE.exists():
command = [str(STATE_LEDGER_EXE), *args]
else:
command = [
"cargo",
"run",
"--quiet",
"--manifest-path",
str(ROOT / "epiphany-core" / "Cargo.toml"),
"--bin",
STATE_LEDGER_BIN,
"--",
*args,
]
completed = subprocess.run(
command,
cwd=ROOT,
text=True,
capture_output=True,
check=False,
)
if completed.returncode != 0:
message = completed.stderr.strip() or completed.stdout.strip() or f"{STATE_LEDGER_BIN} failed"
raise ValueError(message)
return json.loads(completed.stdout)
def read_text(path: Path) -> str:
return path.read_text(encoding="utf-8")
def write_text(path: Path, content: str) -> None:
path.write_text(content, encoding="utf-8")
def load_branches() -> dict[str, Any]:
return json.loads(read_text(BRANCHES_PATH))
def save_branches(data: dict[str, Any]) -> None:
write_text(BRANCHES_PATH, json.dumps(data, indent=2) + "\n")
def append_evidence(record: dict[str, Any]) -> None:
with EVIDENCE_PATH.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(record, ensure_ascii=True) + "\n")
def utc_stamp() -> str:
return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
@ -64,9 +84,26 @@ def extract_active_subgoals() -> list[str]:
return results
def cmd_migrate_json(args: argparse.Namespace) -> int:
print(
json.dumps(
native_ledger_command(
"migrate-json",
"--branches",
str(args.branches),
"--evidence",
str(args.evidence),
"--store",
str(args.store),
),
indent=2,
)
)
return 0
def cmd_status(_: argparse.Namespace) -> int:
branches = load_branches().get("branches", [])
active = [branch for branch in branches if branch.get("status") == "active"]
ledger = native_ledger_command("status", "--store", str(LEDGER_STORE_PATH))
summary = extract_map_field("summary") or "(missing)"
next_action = extract_map_field("next_action") or "(missing)"
subgoals = extract_active_subgoals()
@ -74,7 +111,8 @@ def cmd_status(_: argparse.Namespace) -> int:
print(f"Workspace: {ROOT}")
print(f"Summary: {summary}")
print(f"Next action: {next_action}")
print(f"Active branches: {len(active)} / {len(branches)}")
print(f"Active branches: {ledger.get('activeBranches', 0)} / {ledger.get('branches', 0)}")
print(f"Evidence records: {ledger.get('evidence', 0)}")
if subgoals:
print("Active subgoals:")
for item in subgoals:
@ -83,63 +121,79 @@ def cmd_status(_: argparse.Namespace) -> int:
def cmd_add_evidence(args: argparse.Namespace) -> int:
record: dict[str, Any] = {
"ts": utc_stamp(),
"type": args.type,
"status": args.status,
"note": args.note,
}
command = [
"add-evidence",
"--store",
str(LEDGER_STORE_PATH),
"--ts",
utc_stamp(),
"--type",
args.type,
"--status",
args.status,
"--note",
args.note,
]
if args.branch:
record["branch"] = args.branch
append_evidence(record)
command.extend(["--branch", args.branch])
native_ledger_command(*command)
print("Appended evidence record.")
return 0
def cmd_add_branch(args: argparse.Namespace) -> int:
data = load_branches()
branches = data.setdefault("branches", [])
if any(branch.get("id") == args.id for branch in branches):
raise SystemExit(f"Branch '{args.id}' already exists.")
branches.append(
{
"id": args.id,
"hypothesis": args.hypothesis,
"status": "active",
"artifacts": args.artifact or [],
"notes": args.note or "",
}
)
save_branches(data)
command = [
"add-branch",
"--store",
str(LEDGER_STORE_PATH),
"--id",
args.id,
"--hypothesis",
args.hypothesis,
]
for artifact in args.artifact or []:
command.extend(["--artifact", artifact])
if args.note:
command.extend(["--note", args.note])
native_ledger_command(*command)
print(f"Added branch '{args.id}'.")
return 0
def cmd_close_branch(args: argparse.Namespace) -> int:
data = load_branches()
for branch in data.get("branches", []):
if branch.get("id") != args.id:
continue
branch["status"] = args.status
if args.note:
branch["notes"] = args.note
save_branches(data)
print(f"Updated branch '{args.id}' to status '{args.status}'.")
return 0
raise SystemExit(f"Branch '{args.id}' was not found.")
command = [
"close-branch",
"--store",
str(LEDGER_STORE_PATH),
"--id",
args.id,
"--status",
args.status,
]
if args.note:
command.extend(["--note", args.note])
native_ledger_command(*command)
print(f"Updated branch '{args.id}' to status '{args.status}'.")
return 0
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Inspect and update EpiphanyAgent state files."
description="Inspect and update EpiphanyAgent typed state ledgers."
)
subparsers = parser.add_subparsers(dest="command", required=True)
migrate_parser = subparsers.add_parser("migrate-json", help="One-shot migration from legacy JSON ledgers.")
migrate_parser.add_argument("--branches", type=Path, default=BRANCHES_PATH)
migrate_parser.add_argument("--evidence", type=Path, default=EVIDENCE_PATH)
migrate_parser.add_argument("--store", type=Path, default=LEDGER_STORE_PATH)
migrate_parser.set_defaults(func=cmd_migrate_json)
status_parser = subparsers.add_parser("status", help="Show a compact state summary.")
status_parser.set_defaults(func=cmd_status)
evidence_parser = subparsers.add_parser(
"add-evidence", help="Append one distilled JSONL evidence record."
"add-evidence", help="Append one distilled evidence record."
)
evidence_parser.add_argument("--type", required=True)
evidence_parser.add_argument("--status", required=True)
@ -172,7 +226,11 @@ def build_parser() -> argparse.ArgumentParser:
def main() -> int:
parser = build_parser()
args = parser.parse_args()
return args.func(args)
try:
return args.func(args)
except ValueError as exc:
print(json.dumps({"ok": False, "error": str(exc)}, indent=2))
return 1
if __name__ == "__main__":