Remove Python wrappers from native agent surfaces
This commit is contained in:
parent
2607cb1aea
commit
72b11d27c7
15 changed files with 301 additions and 1135 deletions
|
|
@ -38,6 +38,7 @@ fn main() -> Result<()> {
|
|||
let mut action_id: Option<String> = None;
|
||||
let mut limit = 8_usize;
|
||||
let mut agent_store: Option<PathBuf> = None;
|
||||
let mut apply_rumination = false;
|
||||
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
|
|
@ -60,6 +61,7 @@ fn main() -> Result<()> {
|
|||
"--action-id" => action_id = Some(next_value(&mut args, "--action-id")?),
|
||||
"--limit" => limit = next_value(&mut args, "--limit")?.parse()?,
|
||||
"--agent-store" => agent_store = Some(next_path(&mut args, "--agent-store")?),
|
||||
"--apply-rumination" => apply_rumination = true,
|
||||
_ => return Err(anyhow!("unknown argument {arg:?}")),
|
||||
}
|
||||
}
|
||||
|
|
@ -84,7 +86,17 @@ fn main() -> Result<()> {
|
|||
let store_path = store_path.ok_or_else(|| anyhow!("tick requires --store"))?;
|
||||
let artifact_dir =
|
||||
artifact_dir.ok_or_else(|| anyhow!("tick requires --artifact-dir"))?;
|
||||
let result = tick_heartbeat_store(
|
||||
if let Some(agent_store) = &agent_store {
|
||||
let errors = validate_agent_memory_store(agent_store)?;
|
||||
if !errors.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"agent memory validation failed: {}",
|
||||
errors.join("; ")
|
||||
));
|
||||
}
|
||||
}
|
||||
let tick_schedule_id = schedule_id.clone();
|
||||
let mut result = tick_heartbeat_store(
|
||||
&store_path,
|
||||
&artifact_dir,
|
||||
HeartbeatTickOptions {
|
||||
|
|
@ -92,11 +104,17 @@ fn main() -> Result<()> {
|
|||
coordinator_action,
|
||||
target_role,
|
||||
urgency,
|
||||
schedule_id,
|
||||
schedule_id: tick_schedule_id,
|
||||
source_scene_ref,
|
||||
defer_completion,
|
||||
},
|
||||
)?;
|
||||
if apply_rumination {
|
||||
let agent_store = agent_store
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow!("--apply-rumination requires --agent-store"))?;
|
||||
apply_rumination_patch(&mut result, agent_store, &artifact_dir, &schedule_id)?;
|
||||
}
|
||||
println!("{}", result);
|
||||
}
|
||||
"complete" => {
|
||||
|
|
@ -203,7 +221,7 @@ fn next_value(args: &mut impl Iterator<Item = String>, name: &str) -> Result<Str
|
|||
|
||||
fn usage() -> Result<()> {
|
||||
Err(anyhow!(
|
||||
"usage: epiphany-heartbeat-store init --store <path>\n epiphany-heartbeat-store tick --store <path> --artifact-dir <path> [--coordinator-action <action>] [--defer-completion]\n epiphany-heartbeat-store complete --store <path> --artifact-dir <path> --role <role> [--action-id <id>]\n epiphany-heartbeat-store status --store <path> [--artifact-dir <path>]\n epiphany-heartbeat-store migrate-json --json <path> --store <path> [--projection <path>]\n epiphany-heartbeat-store project --store <path> --projection <path>\n epiphany-heartbeat-store smoke [--agent-store <path>]"
|
||||
"usage: epiphany-heartbeat-store init --store <path>\n epiphany-heartbeat-store tick --store <path> --artifact-dir <path> [--coordinator-action <action>] [--agent-store <path> --apply-rumination] [--defer-completion]\n epiphany-heartbeat-store complete --store <path> --artifact-dir <path> --role <role> [--action-id <id>]\n epiphany-heartbeat-store status --store <path> [--artifact-dir <path>]\n epiphany-heartbeat-store migrate-json --json <path> --store <path> [--projection <path>]\n epiphany-heartbeat-store project --store <path> --projection <path>\n epiphany-heartbeat-store smoke [--agent-store <path>]"
|
||||
))
|
||||
}
|
||||
|
||||
|
|
@ -338,6 +356,30 @@ fn run_smoke(agent_store: &Path) -> Result<serde_json::Value> {
|
|||
Ok(result)
|
||||
}
|
||||
|
||||
fn apply_rumination_patch(
|
||||
result: &mut serde_json::Value,
|
||||
agent_store: &Path,
|
||||
artifact_dir: &Path,
|
||||
schedule_id: &str,
|
||||
) -> Result<()> {
|
||||
if result["rumination"].is_null() {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(patch) = result["rumination"]["selfPatch"].as_object() else {
|
||||
return Ok(());
|
||||
};
|
||||
let role_id = result["rumination"]["roleId"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow!("rumination has no roleId"))?
|
||||
.to_string();
|
||||
let patch = serde_json::Value::Object(patch.clone());
|
||||
let applied = apply_agent_self_patch(&role_id, &patch, agent_store)?;
|
||||
result["rumination"]["result"] = serde_json::to_value(applied)?;
|
||||
result["rumination"]["applied"] = serde_json::Value::Bool(true);
|
||||
write_rumination_artifact(artifact_dir, schedule_id, &result["rumination"])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_rumination_artifact(
|
||||
artifact_dir: &Path,
|
||||
schedule_id: &str,
|
||||
|
|
|
|||
|
|
@ -35,8 +35,8 @@ The spine exists in more than twenty-five live paths:
|
|||
- reorientation policy: app-server declares experimental read-only `thread/epiphany/reorient`, reuses the same live/stored thread view plus mapped pressure/freshness/watcher signals, and derives a bounded `resume`/`regather` verdict with checkpoint-path/frontier reasons without mutating, compacting, scheduling, notifying, or continuing work in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:365), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4514), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4394), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:11424).
|
||||
- CRRC coordinator recommendation: app-server declares experimental read-only `thread/epiphany/crrc`, reuses the same pressure/freshness/watcher/reorientation mapping plus the fixed `reorient-worker` binding and result read-back helper, recognizes already accepted reorientation findings so an accepted result is not recommended for acceptance again, and returns one bounded recommendation such as continue, prepare checkpoint, launch worker, wait, review, accept, or regather manually without mutating, launching, accepting, compacting, notifying, scheduling, or silently continuing work in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:370), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4661), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4546).
|
||||
- role ownership projection: app-server declares experimental read-only `thread/epiphany/roles`, reuses the same state/jobs/pressure/reorient/result/CRRC signals as the coordinator loop, and projects implementation, Imagination/planning, modeling/checkpoint, verification/review, and reorientation lanes with owner roles, status, linked jobs, authority scopes, and recommended scene actions without launching, scheduling, accepting, compacting, notifying, or mutating state in [common.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/common.rs:350), [v2.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server-protocol/src/protocol/v2.rs:4161), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:4310).
|
||||
- role specialist launch/read-back/acceptance: app-server declares experimental `thread/epiphany/roleLaunch`, read-only `thread/epiphany/roleResult`, and write-gated `thread/epiphany/roleAccept`. `roleLaunch` accepts fixed Imagination/planning, modeling/checkpoint, and verification/review role ids, builds bounded specialist payloads from authoritative Epiphany state, routes them through the existing `epiphany_launch_job` job-control seam, and emits the normal `jobLaunch` state update for `jobBindings` only. `roleResult` resolves the fixed or requested binding through the current `agent_jobs` backend and projects structured output as a reviewable finding with verdict, summary, next safe move, inspected files, frontier/evidence ids, optional `statePatch`, optional `selfPatch`, coordinator `selfPersistence` review, raw result, and errors without mutation, promotion, scheduling, or hidden continuation. `selfPatch` is a Ghostlight-shaped lane-memory request, not project truth: the coordinator accepts only role-matched, bounded, evidence-grounded memory/goal/value/private-note mutations and refuses objectives, graphs, checkpoints, scratch, planning, jobs, authority, code edits, or raw transcripts with reasons. `roleAccept` accepts completed Imagination findings only when they contain a valid planning-only patch with draft Objective Draft review gates, accepts completed modeling/checkpoint findings only with a modeling-safe `statePatch`, applies accepted project patches through the existing Epiphany state validator, appends audit observation/evidence, and carries the same `selfPersistence` review. GUI/coordinator accept paths then apply accepted `selfPatch` requests to typed CultCache role dossiers in `state/agents.msgpack` through `tools/epiphany_agent_memory.py`. Implementation stays owned by the main coding agent, verification output remains review-only, and reorientation stays on the CRRC-specific `reorientLaunch` / `reorientResult` / `reorientAccept` path.
|
||||
- shared prompt memory projection and role dossiers: the prompt config now carries `[shared].persistent_memory` in [epiphany_specialists.toml](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/prompts/epiphany_specialists.toml:2). App-server parses that block, prepends it through `epiphany_agent_prompt_with_memory`, and therefore projects the same Ghostlight-derived memory into fixed role specialist instructions, reorientation-worker instructions, coordinator notes, and CRRC checkpoint steering in [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:13260), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:13349), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:13594), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:13603), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:16119). The GUI-launched Hands implementation lane prepends the same memory in [epiphany_gui_action.py](E:/Projects/EpiphanyAgent/tools/epiphany_gui_action.py:52), while the base `<epiphany_state>` doctrine reinforces the Perfect Machine rule through [prompt.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/prompt.rs:31) and [epiphany_doctrine.md](E:/Projects/EpiphanyAgent/epiphany-core/src/prompts/epiphany_doctrine.md:1). Individual Ghostlight-shaped role dossiers now live in typed CultCache `state/agents.msgpack`, and `tools/epiphany_agent_memory.py` validates, reviews, and applies bounded self-memory patches through the native Rust store.
|
||||
- role specialist launch/read-back/acceptance: app-server declares experimental `thread/epiphany/roleLaunch`, read-only `thread/epiphany/roleResult`, and write-gated `thread/epiphany/roleAccept`. `roleLaunch` accepts fixed Imagination/planning, modeling/checkpoint, and verification/review role ids, builds bounded specialist payloads from authoritative Epiphany state, routes them through the existing `epiphany_launch_job` job-control seam, and emits the normal `jobLaunch` state update for `jobBindings` only. `roleResult` resolves the fixed or requested binding through the current `agent_jobs` backend and projects structured output as a reviewable finding with verdict, summary, next safe move, inspected files, frontier/evidence ids, optional `statePatch`, optional `selfPatch`, coordinator `selfPersistence` review, raw result, and errors without mutation, promotion, scheduling, or hidden continuation. `selfPatch` is a Ghostlight-shaped lane-memory request, not project truth: the coordinator accepts only role-matched, bounded, evidence-grounded memory/goal/value/private-note mutations and refuses objectives, graphs, checkpoints, scratch, planning, jobs, authority, code edits, or raw transcripts with reasons. `roleAccept` accepts completed Imagination findings only when they contain a valid planning-only patch with draft Objective Draft review gates, accepts completed modeling/checkpoint findings only with a modeling-safe `statePatch`, applies accepted project patches through the existing Epiphany state validator, appends audit observation/evidence, and carries the same `selfPersistence` review. GUI/coordinator accept paths then apply accepted `selfPatch` requests to typed CultCache role dossiers in `state/agents.msgpack` through the native `epiphany-agent-memory-store` binary. Implementation stays owned by the main coding agent, verification output remains review-only, and reorientation stays on the CRRC-specific `reorientLaunch` / `reorientResult` / `reorientAccept` path.
|
||||
- shared prompt memory projection and role dossiers: the prompt config now carries `[shared].persistent_memory` in [epiphany_specialists.toml](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/prompts/epiphany_specialists.toml:2). App-server parses that block, prepends it through `epiphany_agent_prompt_with_memory`, and therefore projects the same Ghostlight-derived memory into fixed role specialist instructions, reorientation-worker instructions, coordinator notes, and CRRC checkpoint steering in [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:13260), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:13349), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:13594), [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:13603), and [codex_message_processor.rs](E:/Projects/EpiphanyAgent/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs:16119). The GUI-launched Hands implementation lane prepends the same memory in [epiphany_gui_action.py](E:/Projects/EpiphanyAgent/tools/epiphany_gui_action.py:52), while the base `<epiphany_state>` doctrine reinforces the Perfect Machine rule through [prompt.rs](E:/Projects/EpiphanyAgent/epiphany-core/src/prompt.rs:31) and [epiphany_doctrine.md](E:/Projects/EpiphanyAgent/epiphany-core/src/prompts/epiphany_doctrine.md:1). Individual Ghostlight-shaped role dossiers now live in typed CultCache `state/agents.msgpack`, and the native `epiphany-agent-memory-store` binary validates, reviews, and applies bounded self-memory patches through the Rust store.
|
||||
- fixed-lane coordinator: app-server declares experimental read-only `thread/epiphany/coordinator`, composes role, pressure, reorient, CRRC, role result, and reorient result signals, and returns one current action without mutation. Review acceptance and implementation clearance are intentionally different: an accepted verification finding clears implementation only when the verifier verdict is `pass`; accepted `needs-evidence`, `needs-review`, or `fail` findings route back toward modeling/checkpoint strengthening before code work resumes. `regatherManually` is now fallback, not a supervisor-puppeteering excuse: completed unaccepted modeling findings stop at `reviewModelingResult`, modeling acceptance precedes verification, and fixed lane actions are considered before manual regather.
|
||||
- MVP operator view: `tools/epiphany_mvp_status.py` launches app-server over stdio, starts or reads one thread, gathers scene, pressure, reorient, jobs, roles, Imagination/modeling/verification role results, reorient result, and CRRC responses, and renders them as text or JSON so the loop can be dogfooded without reading Rust.
|
||||
- MVP dogfood runner: `tools/epiphany_mvp_dogfood.py` launches app-server over stdio, drives a bounded state/role/CRRC/reorientation loop, and writes operator-safe JSON/text artifacts plus sealed transcript diagnostics under `.epiphany-dogfood/mvp-loop` so a human can audit the run through projections and compare it against a vanilla Codex reference.
|
||||
|
|
|
|||
|
|
@ -40,10 +40,10 @@ Do not trust this file for the exact live HEAD. Always check git.
|
|||
- Durable in-flight investigation checkpointing is now landed in authoritative typed state, writable through `thread/epiphany/update` or accepted `thread/epiphany/promote`, rendered into the prompt, and reflected through scene/context.
|
||||
- The prompt doctrine pass is landed. Shared Epiphany prompts now carry distilled memory/evidence discipline. Rendered state intro/doctrine text lives in `epiphany-core/src/prompts/`, and lane/control prompt text lives in `vendor/codex/codex-rs/app-server/src/prompts/epiphany_specialists.toml`: modeling is the Body, implementation is the Hands and GUI-launched main coding lane, verification is the Soul, reorientation is Life, coordinator remains the read-only Self, and CRRC owns the pre-compaction intervention template.
|
||||
- The Ghostlight memory pass is landed. `epiphany_specialists.toml` now has a shared persistent-memory projection prepended by the harness to fixed role specialists, reorientation workers, coordinator notes, and CRRC checkpoint interventions; `tools/epiphany_gui_action.py` prepends the same memory to GUI-launched implementation prompts. The rendered base doctrine also states the Perfect Machine rule directly: prompt is projection, durable typed state is the mind, every lane must improve its own memory/model/prompt/evidence habit or name the repair, and each lane phrases that duty in its own organ language so the salience sticks.
|
||||
- The role self-memory persistence pass is native now. Each lane has a Ghostlight-shaped typed dossier in `state/agents.msgpack`, and specialists may return optional `selfPatch` requests beside their normal role result. `roleResult`/`roleAccept` project coordinator review as `selfPersistence`: accepted requests are role-matched, bounded lane memory/goal/value/private-note mutations; refused requests explain wrong role, project-truth smuggling, authority grabs, bloat, missing reason, or malformed records. GUI/coordinator accept paths apply accepted `selfPatch` requests through `tools/epiphany_agent_memory.py`, which delegates to the Rust CultCache store; project truth still belongs only in `EpiphanyThreadState`.
|
||||
- The heartbeat initiative pass is landed as a bounded tool seam. `state/agent-heartbeats.msgpack` tracks Self, Face, Imagination, Eyes, Body, Hands, Soul, and Life as Ghostlight-style initiative participants with speed, next-ready time, reaction bias, interrupt threshold, load, status, constraints, history, and pending turns through `epiphany-core::EpiphanyHeartbeatStateEntry` and the native `epiphany-heartbeat-store` binary. `tools/epiphany_agent_heartbeat.py` delegates init/status/tick/complete to that Rust CultCache store, then only handles Python-owned role memory patch application and artifact glue. JSON heartbeat state is gone; general CultCache schema sync, polyglot domain loading, and debug display tools belong in CultLib. This is a callable scheduler seam, not yet an always-on daemon.
|
||||
- The Face public-surface pass is landed as a bounded lane. Face's role dossier lives in `state/agents.msgpack`; `epiphany_specialists.toml` gives it a VoidBot-heartbeat-derived prompt stripped of moderation authority; `state/face-discord.toml` and `tools/epiphany_face_discord.py` enforce that Face may interact only through #aquarium. Missing channel id or token writes candidate chat artifacts instead of posting elsewhere.
|
||||
- The heartbeat/Face operator API pass is landed. `tools/epiphany_agent_heartbeat.py status` returns machine-readable initiative state plus CultCache store presence, `tools/epiphany_face_discord.py bubble` writes Discord-independent `epiphany.face_bubble.v0` artifacts, `tools/epiphany_mvp_status.py` includes `heartbeat` and `face` blocks, and `tools/epiphany_gui_action.py` exposes `heartbeatStatus`, `runHeartbeat`, and `faceBubble`. `runHeartbeat` advances one slot and emits a Face bubble so Aquarium can show chat even before Discord posting is configured.
|
||||
- The role self-memory persistence pass is native now. Each lane has a Ghostlight-shaped typed dossier in `state/agents.msgpack`, and specialists may return optional `selfPatch` requests beside their normal role result. `roleResult`/`roleAccept` project coordinator review as `selfPersistence`: accepted requests are role-matched, bounded lane memory/goal/value/private-note mutations; refused requests explain wrong role, project-truth smuggling, authority grabs, bloat, missing reason, or malformed records. GUI/coordinator accept paths apply accepted `selfPatch` requests through the native `epiphany-agent-memory-store` binary; project truth still belongs only in `EpiphanyThreadState`.
|
||||
- The heartbeat initiative pass is landed as a bounded tool seam. `state/agent-heartbeats.msgpack` tracks Self, Face, Imagination, Eyes, Body, Hands, Soul, and Life as Ghostlight-style initiative participants with speed, next-ready time, reaction bias, interrupt threshold, load, status, constraints, history, and pending turns through `epiphany-core::EpiphanyHeartbeatStateEntry` and the native `epiphany-heartbeat-store` binary. Tick/status/complete and idle rumination selfPatch application now run through Rust/CultCache directly. JSON heartbeat state and Python wrapper state are gone; general CultCache schema sync, polyglot domain loading, and debug display tools belong in CultLib. This is a callable scheduler seam, not yet an always-on daemon.
|
||||
- The Face public-surface pass is landed as a bounded lane. Face's role dossier lives in `state/agents.msgpack`; `epiphany_specialists.toml` gives it a VoidBot-heartbeat-derived prompt stripped of moderation authority; `state/face-discord.toml` and the native `epiphany-face-discord` binary enforce that Face may interact only through #aquarium. Missing channel id or token writes candidate chat artifacts instead of posting elsewhere.
|
||||
- The heartbeat/Face operator API pass is landed. Native `epiphany-heartbeat-store status` returns machine-readable initiative state plus CultCache store presence, native `epiphany-face-discord bubble` writes Discord-independent `epiphany.face_bubble.v0` artifacts, `tools/epiphany_mvp_status.py` includes `heartbeat` and `face` blocks, and `tools/epiphany_gui_action.py` exposes `heartbeatStatus`, `runHeartbeat`, and `faceBubble`. `runHeartbeat` advances one slot and emits a Face bubble so Aquarium can show chat even before Discord posting is configured.
|
||||
- The Aetheria dogfood run has a contamination scar. The supervising Codex session directly edited and committed target-repo work on `E:\Projects\Aetheria-Economy` instead of only driving Epiphany lanes. Treat those Aetheria commits as supervisor-seeded implementation, not clean evidence that Epiphany coordinated the work. Future dogfood must run through the GUI/coordinator/fixed role lanes with auditable artifacts unless the user explicitly authorizes an operator intervention.
|
||||
- The dogfood quarantine now has a direct-thought boundary. The supervisor may read coordinator actions, role/reorient statuses, structured finding summaries, reviewed state patches, rendered status snapshots, and artifact manifests. It must not read raw worker transcripts, direct worker messages, full turn logs, or `rawResult` payloads during normal dogfood. Those artifacts are sealed for explicit forensic debugging only.
|
||||
- `tools/epiphany_agent_telemetry.py` is the safe instrument panel for sealed runs. Status/coordinator/GUI/dogfood/live-specialist tools generate telemetry JSON from sealed transcripts that preserves method names, call shape, job/status/path counts, and any visible function/tool names while sealing text, direct messages, and raw results.
|
||||
|
|
@ -132,9 +132,9 @@ The current spine:
|
|||
- durable investigation checkpoint packet through typed state, prompt, scene, and context
|
||||
- distilled shared and config-backed prompt doctrine through the base prompt, rendered Epiphany state prompt files, modeling/Body, implementation/Hands, verification/Soul, reorientation/Life, coordinator/Self, and CRRC intervention surfaces
|
||||
- shared Ghostlight-derived persistent memory projection across Imagination, Body, Soul, Life, Self, CRRC checkpoint steering, and the GUI-launched Hands implementation lane
|
||||
- Ghostlight-derived heartbeat initiative scheduling through `tools/epiphany_agent_heartbeat.py`, with Self and Face included as first-class participants, idle rumination routed through normal `selfPatch` review/application, and the heartbeat state round-tripped through the typed CultCache MessagePack store in `state/agent-heartbeats.msgpack`
|
||||
- Ghostlight-derived heartbeat initiative scheduling through the native `epiphany-heartbeat-store` binary, with Self and Face included as first-class participants, idle rumination routed through normal `selfPatch` review/application, and the heartbeat state round-tripped through the typed CultCache MessagePack store in `state/agent-heartbeats.msgpack`
|
||||
- Face as the public #aquarium-only surface for translating agent thought-weather into short chats or candidate drafts, without moderator authority
|
||||
- Ghostlight-shaped role dossiers in `state/agents.msgpack`, plus `selfPatch` review projection through `roleResult`/`roleAccept` and accepted memory application through `tools/epiphany_agent_memory.py`
|
||||
- Ghostlight-shaped role dossiers in `state/agents.msgpack`, plus `selfPatch` review projection through `roleResult`/`roleAccept` and accepted memory application through the native `epiphany-agent-memory-store` binary
|
||||
- first Unity runtime bridge through `tools/epiphany_unity_bridge.py`, `tools/epiphany_unity_bridge_smoke.py`, GUI Inspect Unity, runtime artifact listing, and implementation prompt guardrails
|
||||
- first Rider source-context bridge through `tools/epiphany_rider_bridge.py`, `tools/epiphany_rider_bridge_smoke.py`, GUI Inspect Rider, Rider artifact listing, implementation prompt guardrails, and a source scaffold under `integrations/rider`
|
||||
- first GUI graph dashboard through the adjacent `@epiphanygraph/epiphany-graph-viewer` package over typed Epiphany graph state
|
||||
|
|
|
|||
|
|
@ -41,10 +41,10 @@ Default imported planning status should be conservative: use `new`, `triaged`, `
|
|||
Use the existing Ghostlight-shaped role memory contract in:
|
||||
|
||||
- `E:\Projects\EpiphanyAgent\state\agents\README.md`
|
||||
- `E:\Projects\EpiphanyAgent\tools\epiphany_agent_memory.py`
|
||||
- native `epiphany-agent-memory-store` binary in `E:\Projects\EpiphanyAgent\epiphany-core`
|
||||
- `E:\Projects\EpiphanyAgent\state\agents.msgpack`
|
||||
|
||||
All proposed memory mutations must be expressible as bounded `selfPatch` JSON objects accepted by `tools/epiphany_agent_memory.py review-patch`.
|
||||
All proposed memory mutations must be expressible as bounded `selfPatch` JSON objects accepted by `epiphany-agent-memory-store review-patch`.
|
||||
|
||||
## Source Repositories To Inspect
|
||||
|
||||
|
|
@ -448,7 +448,7 @@ Write these files:
|
|||
Validate every role memory patch with:
|
||||
|
||||
```powershell
|
||||
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_agent_memory.py' review-patch --role-id <role> --patch '<path-to-patch>'
|
||||
cargo run --manifest-path E:\Projects\EpiphanyAgent\epiphany-core\Cargo.toml --bin epiphany-agent-memory-store -- review-patch --store E:\Projects\EpiphanyAgent\state\agents.msgpack --role-id <role> --patch '<path-to-patch>'
|
||||
```
|
||||
|
||||
Record status and refusal reasons. Fix rejected patches until they validate, unless a rejection reveals the lesson should not be migrated.
|
||||
|
|
|
|||
|
|
@ -15,8 +15,8 @@ surfaces instead.
|
|||
All standing lanes use the same Ghostlight-shaped protocol, including the
|
||||
coordinator/Self and Face. Face is the public interactive surface for Epiphany
|
||||
agents: it translates useful agent thought-weather into #aquarium chat or drafts
|
||||
and is not a moderator. The heartbeat scheduler in
|
||||
`tools/epiphany_agent_heartbeat.py` borrows Ghostlight initiative timing: each
|
||||
and is not a moderator. The native `epiphany-heartbeat-store` scheduler borrows
|
||||
Ghostlight initiative timing: each
|
||||
lane carries speed, readiness, reaction bias, interrupt threshold, load, status,
|
||||
and constraints. The harness sets a target heartbeat rate, pending coordinator
|
||||
work may pull its owning lane through a reaction window, and otherwise the
|
||||
|
|
@ -29,7 +29,7 @@ review rules still apply.
|
|||
|
||||
Face's Discord boundary is still a small TOML configuration seam: it may
|
||||
interact only through #aquarium. If the channel id is not configured, Face must
|
||||
write candidate chat artifacts through `tools/epiphany_face_discord.py draft`
|
||||
write candidate chat artifacts through the native `epiphany-face-discord draft`
|
||||
instead of posting.
|
||||
|
||||
Use:
|
||||
|
|
@ -38,7 +38,7 @@ Use:
|
|||
cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-agent-memory-store -- validate --store .\state\agents.msgpack
|
||||
cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-agent-memory-store -- smoke --store .\state\agents.msgpack
|
||||
cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-agent-memory-store -- status --store .\state\agents.msgpack
|
||||
& 'C:\Users\Meta\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe' '.\tools\epiphany_agent_heartbeat.py' tick --coordinator-action continueImplementation --urgency 0.95 --apply-rumination
|
||||
cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-heartbeat-store -- tick --store .\state\agent-heartbeats.msgpack --artifact-dir .\.epiphany-heartbeats --coordinator-action continueImplementation --urgency 0.95 --agent-store .\state\agents.msgpack --apply-rumination
|
||||
cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-heartbeat-store -- smoke --agent-store .\state\agents.msgpack
|
||||
cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-face-discord -- draft --content 'Face notices the organs are arguing about evidence again.'
|
||||
cargo run --manifest-path .\epiphany-core\Cargo.toml --bin epiphany-face-discord -- smoke
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -127,15 +127,15 @@ accepted_design:
|
|||
- Specialist prompts are role-distilled instead of generic and their live text is config-backed in app-server: modeling/checkpoint is the Body of code, dataflow, seams, and frontier; research/scout is the Eyes prompt surface for existing work, vendor guidance, libraries, papers, and anti-Greenspun source selection; implementation is the Hands, the main coding lane and actuator rather than a `roleLaunch` specialist; verification/review is the Soul of promise, invariants, evidence, and user truth; reorientation is Life across compaction and source drift; coordinator is the read-only Self that routes attention without implementing, verifying, promoting, or accepting; Face is the public Discord #aquarium surface that translates agent thought-weather without moderating or leaking sealed thought.
|
||||
- Epiphany prompt surfaces now carry a shared Ghostlight-derived persistent memory projection before lane-specific text: prompt is not memory, durable typed state is the mind, personality and protected values are first-class salience handles, and every lane is explicitly responsible for making its own memory/model/prompt/evidence habit sharper or naming the needed repair. Each lane also states that self-improvement in its own role language: Imagination selects futures, Body clarifies anatomy, Eyes sees earlier, Hands touches source more precisely, Soul becomes harder to fool, Life loses less continuity, Self routes repair, and Face becomes clearer at turning inner weather into useful social presence.
|
||||
- Specialist self-memory now has a bounded Ghostlight-shaped CultCache persistence surface in `state/agents.msgpack`: Imagination, Body, Eyes, Hands, Soul, Life, Self, and Face each have an individual typed role dossier for identity, personality, semantic/episodic/relationship memory, goals, and values. These entries are lane memory only; project truth remains in authoritative `EpiphanyThreadState`.
|
||||
- `state/agent-heartbeats.msgpack`, `epiphany-core::EpiphanyHeartbeatStateEntry`, the `epiphany-heartbeat-store` binary, and `tools/epiphany_agent_heartbeat.py` are the first Ghostlight-derived heartbeat initiative seam. The harness sets a target heartbeat rate; participants carry initiative speed, next-ready time, reaction bias, interrupt threshold, current load, status, and constraints; pending coordinator work can pull its owning lane through a reaction window; otherwise the earliest ready active lane wins the slot. If the winner has no routeable work, it ruminates on role quality and may apply a bounded selfPatch through the normal coordinator-reviewed memory rules. Face can win `surfaceAgentThoughts` or `discordAquariumChat` work slots. The typed CultCache MessagePack store is the durable persistence seam; JSON state is gone.
|
||||
- `state/agent-heartbeats.msgpack`, `epiphany-core::EpiphanyHeartbeatStateEntry`, and the native `epiphany-heartbeat-store` binary are the Ghostlight-derived heartbeat initiative seam. The harness sets a target heartbeat rate; participants carry initiative speed, next-ready time, reaction bias, interrupt threshold, current load, status, and constraints; pending coordinator work can pull its owning lane through a reaction window; otherwise the earliest ready active lane wins the slot. If the winner has no routeable work, it ruminates on role quality and can apply a bounded selfPatch directly through the normal coordinator-reviewed memory rules when `--agent-store` and `--apply-rumination` are provided. Face can win `surfaceAgentThoughts` or `discordAquariumChat` work slots. The typed CultCache MessagePack store is the durable persistence seam; JSON state is gone.
|
||||
- `state/ledgers.msgpack`, `epiphany-core::EpiphanyStateLedgerEntry`, the `epiphany-state-ledger-store` binary, and the native `epiphany-state` CLI now own durable branch and evidence ledgers. The old tracked `state/branches.json` and `state/evidence.jsonl` files are gone; JSON projection remains only a migration/debug escape hatch.
|
||||
- CultCache inspection, cross-language schema synchronization, and debug display tooling belong in CultLib, not in EpiphanyAgent. Epiphany should consume typed CultCache documents and expose product-specific status through its API, while general polyglot domain loading/inspection lives with the shared CultCache ecosystem.
|
||||
- VoidBot's current routine is the reference for the next Epiphany heartbeat/state substrate: work, rumination, and sleep turns; completion-gated cooldown; typed CultCache state; Qdrant-backed memory vectors; resonance/incubation/dream state; and Aquarium-visible internals. The first MessagePack canonical state slice is now the heartbeat store through CultCache-compatible typed Rust state. See `notes/voidbot-routine-adoption-plan.md`.
|
||||
- The Rust CultCache-compatible contract now lives in dedicated upstream `https://github.com/GameCult/cultcache-rs` and is vendored as `vendor/cultcache-rs`. Epiphany should consume it as the canonical typed MessagePack persistence seam instead of growing an embedded local copy.
|
||||
- `state/face-discord.toml` and `tools/epiphany_face_discord.py` are the first Face Discord boundary. Face may interact only through #aquarium; missing or mismatched channel configuration produces candidate chat artifacts instead of posting elsewhere.
|
||||
- `tools/epiphany_agent_heartbeat.py status`, the `heartbeat` block in `tools/epiphany_mvp_status.py`, and GUI actions `heartbeatStatus` / `runHeartbeat` are the first operator API surface for heartbeat initiative state and outputs. `runHeartbeat` advances one slot and emits a Discord-independent Face bubble artifact. Status now reflects the backing CultCache store so Aquarium can see whether the typed heartbeat memory is present.
|
||||
- `tools/epiphany_face_discord.py bubble`, the `face` block in `tools/epiphany_mvp_status.py`, and GUI action `faceBubble` are the first Aquarium bubble surface. Face can open a local chat bubble artifact even when Discord channel id/token configuration is absent.
|
||||
- `thread/epiphany/roleResult` and `thread/epiphany/roleAccept` now project optional specialist `selfPatch` requests with coordinator review through `selfPersistence`: good mutations are role-matched, bounded, evidence-grounded lane memory/goal/value/private-note updates; project truth, authority, code edits, graphs, checkpoints, planning, scratch, jobs, and raw transcripts are refused with reasons. GUI/coordinator acceptance paths apply accepted `selfPatch` requests through `tools/epiphany_agent_memory.py`.
|
||||
- `state/face-discord.toml` and the native `epiphany-face-discord` binary are the first Face Discord boundary. Face may interact only through #aquarium; missing or mismatched channel configuration produces candidate chat artifacts instead of posting elsewhere.
|
||||
- The native `epiphany-heartbeat-store status`, the `heartbeat` block in `tools/epiphany_mvp_status.py`, and GUI actions `heartbeatStatus` / `runHeartbeat` are the first operator API surface for heartbeat initiative state and outputs. `runHeartbeat` advances one slot and emits a Discord-independent Face bubble artifact. Status now reflects the backing CultCache store so Aquarium can see whether the typed heartbeat memory is present.
|
||||
- The native `epiphany-face-discord bubble`, the `face` block in `tools/epiphany_mvp_status.py`, and GUI action `faceBubble` are the first Aquarium bubble surface. Face can open a local chat bubble artifact even when Discord channel id/token configuration is absent.
|
||||
- `thread/epiphany/roleResult` and `thread/epiphany/roleAccept` now project optional specialist `selfPatch` requests with coordinator review through `selfPersistence`: good mutations are role-matched, bounded, evidence-grounded lane memory/goal/value/private-note updates; project truth, authority, code edits, graphs, checkpoints, planning, scratch, jobs, and raw transcripts are refused with reasons. GUI/coordinator acceptance paths apply accepted `selfPatch` requests through the native `epiphany-agent-memory-store` binary.
|
||||
- The base Epiphany prompt now keeps Codex's useful harness DNA explicitly: AGENTS scope, concise progress updates, plan discipline, scoped edits, non-destructive filesystem/git behavior, focused validation, and concise honest finals remain first-class rather than overwritten by Epiphany metaphor.
|
||||
- Greenspun-shaped invention is now a named prompt-level guardrail. Before building a parser, scheduler, renderer, protocol, storage layer, security mechanism, workflow engine, or algorithm, agents must perform or request a bounded research/scout pass and record why existing work does or does not fit.
|
||||
- Repetitive operator work must be externalized as a visible queue before the harness treats it as complete. Batch rendering, tile generation, migrations, imports, or other finite loops need item counts, terminal states, blockers, and validation; a narratable partial run is progress, not completion.
|
||||
|
|
@ -186,9 +186,9 @@ landed_baseline:
|
|||
- Phase 6 GUI planning operator slice: MVP status and Tauri/React GUI now render planning state, and `tools/epiphany_gui_action.py` exposes explicit selected Objective Draft adoption with artifacted state patch/update proof.
|
||||
- Phase 6 Imagination role lane: `thread/epiphany/roles` now exposes Imagination/planning, `roleLaunch` can launch the fixed `planning-synthesis-worker`, `roleResult` projects its finding, `roleAccept` applies planning-only patches with review-gated Objective Drafts, and the GUI/status tools can launch, read, and accept that lane.
|
||||
- Phase 6 Aquarium graph and Rider bridge slice: the Tauri/React/WebGL Aquarium embeds the adjacent EpiphanyGraph viewer over typed graph state, `tools/epiphany_rider_bridge.py` writes Rider/source-context artifacts, Aquarium Inspect Rider surfaces those artifacts, and `integrations/rider` scaffolds the first frontend-only Rider tool-window/context-action plugin.
|
||||
- Phase 6 role self-memory slice: Ghostlight-shaped role dossiers live in typed CultCache `state/agents.msgpack`, specialists may request bounded `selfPatch` lane-memory mutations, coordinator review projects acceptance/refusal reasons through `selfPersistence`, and GUI/coordinator accept paths apply accepted requests with `tools/epiphany_agent_memory.py`.
|
||||
- Phase 6 Face public-surface slice: Face's typed role dossier, Face prompt text, `state/face-discord.toml`, and `tools/epiphany_face_discord.py` establish Face as the public #aquarium-only translator of Epiphany agent thought-weather, without VoidBot's moderation authority.
|
||||
- Phase 6 heartbeat initiative slice: `tools/epiphany_agent_heartbeat.py`, `state/agent-heartbeats.msgpack`, `epiphany-core::EpiphanyHeartbeatStateEntry`, the `epiphany-heartbeat-store` binary, and heartbeat smoke coverage borrow Ghostlight initiative scheduling so Self, Face, Imagination, Eyes, Body, Hands, Soul, and Life compete for heartbeat slots; idle slots become bounded memory rumination instead of fake project work, and the first live state surface now ticks/completes through typed CultCache MessagePack instead of JSON state.
|
||||
- Phase 6 role self-memory slice: Ghostlight-shaped role dossiers live in typed CultCache `state/agents.msgpack`, specialists may request bounded `selfPatch` lane-memory mutations, coordinator review projects acceptance/refusal reasons through `selfPersistence`, and GUI/coordinator accept paths apply accepted requests with the native `epiphany-agent-memory-store` binary.
|
||||
- Phase 6 Face public-surface slice: Face's typed role dossier, Face prompt text, `state/face-discord.toml`, and the native `epiphany-face-discord` binary establish Face as the public #aquarium-only translator of Epiphany agent thought-weather, without VoidBot's moderation authority.
|
||||
- Phase 6 heartbeat initiative slice: `state/agent-heartbeats.msgpack`, `epiphany-core::EpiphanyHeartbeatStateEntry`, the native `epiphany-heartbeat-store` binary, and heartbeat smoke coverage borrow Ghostlight initiative scheduling so Self, Face, Imagination, Eyes, Body, Hands, Soul, and Life compete for heartbeat slots; idle slots become bounded memory rumination instead of fake project work, and the live state surface now ticks/completes/applies rumination through typed CultCache MessagePack instead of JSON or Python wrapper state.
|
||||
guardrails:
|
||||
- Use `tools/epiphany_phase5_smoke.py` before modifying update, distill, propose, promote, read-projection, or notification behavior.
|
||||
- Use `tools/epiphany_phase6_scene_smoke.py` before modifying scene projection behavior.
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ What was done:
|
|||
- Inspected EpiphanyAgent's Ghostlight role memory schema and patch validator:
|
||||
- state/agents/README.md
|
||||
- state/agents/body.agent-state.json
|
||||
- tools/epiphany_agent_memory.py
|
||||
- native epiphany-agent-memory-store binary
|
||||
- Added new documentation file:
|
||||
- notes/true-epiphany-memory-migration-sandbox-prompt.md
|
||||
|
||||
|
|
@ -38,7 +38,7 @@ Important content of the new prompt:
|
|||
- It explicitly forbids direct mutation by default.
|
||||
- It maps adjacent repo lessons into role-specific memory targets for Self, Face, Imagination, Eyes, Body, Hands, Soul, and Life.
|
||||
- It requires source-inventory.json, distillation-report.md, role-selfpatches/*.json, review-results.json, and apply-plan.md.
|
||||
- It requires each proposed memory patch to validate via tools/epiphany_agent_memory.py review-patch.
|
||||
- It requires each proposed memory patch to validate via native epiphany-agent-memory-store review-patch.
|
||||
- It emphasizes project truth versus role memory separation.
|
||||
|
||||
Potential remaining work after compaction:
|
||||
|
|
|
|||
|
|
@ -1,408 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
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
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_HEARTBEAT_STATE = ROOT / "state" / "agent-heartbeats.json"
|
||||
DEFAULT_HEARTBEAT_STORE = ROOT / "state" / "agent-heartbeats.msgpack"
|
||||
DEFAULT_ARTIFACT_DIR = ROOT / ".epiphany-heartbeats"
|
||||
HEARTBEAT_STORE_BIN = "epiphany-heartbeat-store"
|
||||
HEARTBEAT_STORE_EXE = Path(os.environ.get("CARGO_TARGET_DIR", r"C:\Users\Meta\.cargo-target-codex")) / "debug" / "epiphany-heartbeat-store.exe"
|
||||
INITIATIVE_SCHEMA_VERSION = "ghostlight.initiative_schedule.v0"
|
||||
GHOSTLIGHT_ACTION_TYPES = {
|
||||
"speak",
|
||||
"silence",
|
||||
"move",
|
||||
"gesture",
|
||||
"touch_object",
|
||||
"block_object",
|
||||
"use_object",
|
||||
"show_object",
|
||||
"withhold_object",
|
||||
"transfer_object",
|
||||
"spend_resource",
|
||||
"attack",
|
||||
"wait",
|
||||
"mixed",
|
||||
}
|
||||
GHOSTLIGHT_ACTION_SCALES = {"micro", "short", "standard", "major", "committed"}
|
||||
GHOSTLIGHT_PARTICIPANT_STATUSES = {"active", "blocked", "withdrawn", "incapacitated", "offscreen"}
|
||||
|
||||
ROLE_ORDER = [
|
||||
"coordinator",
|
||||
"face",
|
||||
"imagination",
|
||||
"research",
|
||||
"modeling",
|
||||
"implementation",
|
||||
"verification",
|
||||
"reorientation",
|
||||
]
|
||||
|
||||
DISPLAY_NAMES = {
|
||||
"coordinator": "Self",
|
||||
"face": "Face",
|
||||
"imagination": "Imagination",
|
||||
"research": "Eyes",
|
||||
"modeling": "Body",
|
||||
"implementation": "Hands",
|
||||
"verification": "Soul",
|
||||
"reorientation": "Life",
|
||||
}
|
||||
|
||||
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 native_heartbeat_command(*args: str) -> dict[str, Any]:
|
||||
if HEARTBEAT_STORE_EXE.exists():
|
||||
command = [str(HEARTBEAT_STORE_EXE), *args]
|
||||
else:
|
||||
command = [
|
||||
"cargo",
|
||||
"run",
|
||||
"--quiet",
|
||||
"--manifest-path",
|
||||
str(ROOT / "epiphany-core" / "Cargo.toml"),
|
||||
"--bin",
|
||||
HEARTBEAT_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"{HEARTBEAT_STORE_BIN} failed"
|
||||
raise ValueError(message)
|
||||
try:
|
||||
return json.loads(completed.stdout)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValueError(f"{HEARTBEAT_STORE_BIN} returned non-JSON output: {completed.stdout}") from exc
|
||||
|
||||
|
||||
def heartbeat_status(
|
||||
*,
|
||||
state_file: Path = DEFAULT_HEARTBEAT_STATE,
|
||||
store_file: Path = DEFAULT_HEARTBEAT_STORE,
|
||||
artifact_dir: Path = DEFAULT_ARTIFACT_DIR,
|
||||
target_heartbeat_rate: float = 0.0,
|
||||
artifact_limit: int = 8,
|
||||
) -> dict[str, Any]:
|
||||
return native_heartbeat_command(
|
||||
"status",
|
||||
"--store",
|
||||
str(store_file),
|
||||
"--artifact-dir",
|
||||
str(artifact_dir),
|
||||
"--target-heartbeat-rate",
|
||||
str(target_heartbeat_rate),
|
||||
"--limit",
|
||||
str(artifact_limit),
|
||||
)
|
||||
|
||||
|
||||
def run_tick(args: argparse.Namespace) -> dict[str, Any]:
|
||||
errors = validate_all(args.agent_dir)
|
||||
if errors:
|
||||
raise ValueError("agent memory validation failed: " + "; ".join(errors))
|
||||
store_file = getattr(args, "store_file", DEFAULT_HEARTBEAT_STORE)
|
||||
command = [
|
||||
"tick",
|
||||
"--store",
|
||||
str(store_file),
|
||||
"--artifact-dir",
|
||||
str(args.artifact_dir),
|
||||
"--target-heartbeat-rate",
|
||||
str(args.target_heartbeat_rate),
|
||||
"--urgency",
|
||||
str(args.urgency),
|
||||
"--schedule-id",
|
||||
args.schedule_id,
|
||||
"--source-scene-ref",
|
||||
args.source_scene_ref,
|
||||
]
|
||||
if args.coordinator_action:
|
||||
command.extend(["--coordinator-action", args.coordinator_action])
|
||||
if args.target_role:
|
||||
command.extend(["--target-role", args.target_role])
|
||||
if getattr(args, "defer_completion", False):
|
||||
command.append("--defer-completion")
|
||||
result = native_heartbeat_command(*command)
|
||||
rumination = result.get("rumination")
|
||||
if isinstance(rumination, dict) and rumination.get("selfPatch") is not None:
|
||||
rumination["result"] = (
|
||||
apply_self_patch(rumination.get("roleId"), rumination["selfPatch"], agent_dir=args.agent_dir)
|
||||
if args.apply_rumination
|
||||
else None
|
||||
)
|
||||
rumination["applied"] = bool(args.apply_rumination)
|
||||
write_json(args.artifact_dir / f"{args.schedule_id}.rumination.json", rumination)
|
||||
result["rumination"] = rumination
|
||||
result.setdefault("stateFile", None)
|
||||
result["storeFile"] = str(store_file)
|
||||
result["artifactDir"] = str(args.artifact_dir)
|
||||
return result
|
||||
|
||||
|
||||
def run_complete(args: argparse.Namespace) -> dict[str, Any]:
|
||||
store_file = getattr(args, "store_file", DEFAULT_HEARTBEAT_STORE)
|
||||
command = [
|
||||
"complete",
|
||||
"--store",
|
||||
str(store_file),
|
||||
"--artifact-dir",
|
||||
str(args.artifact_dir),
|
||||
"--role",
|
||||
args.role,
|
||||
]
|
||||
if args.action_id:
|
||||
command.extend(["--action-id", args.action_id])
|
||||
return native_heartbeat_command(*command)
|
||||
|
||||
|
||||
def run_status(args: argparse.Namespace) -> dict[str, Any]:
|
||||
return heartbeat_status(
|
||||
store_file=args.store_file,
|
||||
artifact_dir=args.artifact_dir,
|
||||
target_heartbeat_rate=args.target_heartbeat_rate,
|
||||
artifact_limit=args.limit,
|
||||
)
|
||||
|
||||
|
||||
def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
|
||||
with TemporaryDirectory() as tmp:
|
||||
tmp_dir = Path(tmp)
|
||||
agent_store = tmp_dir / "agents.msgpack"
|
||||
store_file = tmp_dir / "heartbeats.msgpack"
|
||||
artifact_dir = tmp_dir / "artifacts"
|
||||
import shutil
|
||||
|
||||
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_store,
|
||||
target_heartbeat_rate=1.0,
|
||||
coordinator_action="continueImplementation",
|
||||
target_role=None,
|
||||
urgency=0.95,
|
||||
apply_rumination=True,
|
||||
schedule_id="smoke-work",
|
||||
source_scene_ref="smoke/coordinator",
|
||||
defer_completion=True,
|
||||
)
|
||||
work = run_tick(first_args)
|
||||
blocked_repeat = None
|
||||
try:
|
||||
run_tick(first_args)
|
||||
except ValueError as exc:
|
||||
blocked_repeat = str(exc)
|
||||
complete_args = argparse.Namespace(
|
||||
state_file=None,
|
||||
store_file=store_file,
|
||||
artifact_dir=artifact_dir,
|
||||
role="implementation",
|
||||
action_id=work["event"]["actionId"],
|
||||
)
|
||||
completed = run_complete(complete_args)
|
||||
second_args = argparse.Namespace(
|
||||
state_file=None,
|
||||
store_file=store_file,
|
||||
artifact_dir=artifact_dir,
|
||||
agent_dir=agent_store,
|
||||
target_heartbeat_rate=1.0,
|
||||
coordinator_action=None,
|
||||
target_role=None,
|
||||
urgency=0.0,
|
||||
apply_rumination=True,
|
||||
schedule_id="smoke-idle",
|
||||
source_scene_ref="smoke/idle",
|
||||
defer_completion=False,
|
||||
)
|
||||
idle = run_tick(second_args)
|
||||
validation_errors = validate_all(agent_store)
|
||||
initiative_errors = [
|
||||
*validate_initiative_schedule_shape(work["schedule"]),
|
||||
*validate_initiative_schedule_shape(idle["schedule"]),
|
||||
]
|
||||
status = heartbeat_status(store_file=store_file, artifact_dir=artifact_dir)
|
||||
ok = (
|
||||
work["event"]["selectedRole"] == "implementation"
|
||||
and work["event"]["turnStatus"] == "running"
|
||||
and blocked_repeat is not None
|
||||
and "already has running heartbeat turn" in blocked_repeat
|
||||
and completed["event"]["turnStatus"] == "completed"
|
||||
and idle["event"]["actionType"] == "ruminate_memory"
|
||||
and idle["event"]["turnStatus"] == "completed"
|
||||
and idle["event"]["nextReadyAt"] > completed["event"]["nextReadyAt"]
|
||||
and idle["rumination"]["result"]["status"] == "accepted"
|
||||
and not validation_errors
|
||||
and not initiative_errors
|
||||
and (artifact_dir / "smoke-work.initiative.json").exists()
|
||||
and (artifact_dir / "smoke-work.completion.json").exists()
|
||||
and (artifact_dir / "smoke-idle.rumination.json").exists()
|
||||
and len(status.get("participants", [])) == len(ROLE_ORDER)
|
||||
)
|
||||
return {
|
||||
"ok": ok,
|
||||
"workEvent": work["event"],
|
||||
"blockedRepeat": blocked_repeat,
|
||||
"completionEvent": completed["event"],
|
||||
"idleEvent": idle["event"],
|
||||
"idleRumination": idle["rumination"],
|
||||
"validationErrors": validation_errors,
|
||||
"initiativeErrors": initiative_errors,
|
||||
}
|
||||
|
||||
|
||||
def validate_initiative_schedule_shape(schedule: dict[str, Any]) -> list[str]:
|
||||
errors: list[str] = []
|
||||
required = [
|
||||
"schema_version",
|
||||
"schedule_id",
|
||||
"source_scene_ref",
|
||||
"scene_clock",
|
||||
"participants",
|
||||
"action_catalog",
|
||||
"reaction_windows",
|
||||
"selection_policy",
|
||||
"next_actor_selection",
|
||||
"review_notes",
|
||||
]
|
||||
for key in required:
|
||||
if key not in schedule:
|
||||
errors.append(f"initiative schedule missing {key}")
|
||||
if schedule.get("schema_version") != INITIATIVE_SCHEMA_VERSION:
|
||||
errors.append("initiative schedule has wrong schema_version")
|
||||
if not isinstance(schedule.get("scene_clock"), (int, float)) or schedule.get("scene_clock", -1) < 0:
|
||||
errors.append("initiative schedule scene_clock must be non-negative number")
|
||||
for participant in schedule.get("participants", []):
|
||||
if participant.get("status") not in GHOSTLIGHT_PARTICIPANT_STATUSES:
|
||||
errors.append(f"participant {participant.get('agent_id')} has invalid status")
|
||||
for key in ("initiative_speed", "next_ready_at", "reaction_bias", "interrupt_threshold", "current_load"):
|
||||
if not isinstance(participant.get(key), (int, float)):
|
||||
errors.append(f"participant {participant.get('agent_id')} {key} must be numeric")
|
||||
for action in schedule.get("action_catalog", []):
|
||||
if action.get("action_type") not in GHOSTLIGHT_ACTION_TYPES:
|
||||
errors.append(f"action {action.get('action_id')} has invalid action_type")
|
||||
if action.get("action_scale") not in GHOSTLIGHT_ACTION_SCALES:
|
||||
errors.append(f"action {action.get('action_id')} has invalid action_scale")
|
||||
selection = schedule.get("next_actor_selection", {})
|
||||
if selection.get("selection_kind") not in {"scheduled_turn", "reaction_interrupt", "coordinator_override"}:
|
||||
errors.append("next_actor_selection has invalid selection_kind")
|
||||
for snapshot in selection.get("readiness_snapshot", []):
|
||||
extra_keys = set(snapshot) - {
|
||||
"agent_id",
|
||||
"next_ready_at",
|
||||
"reaction_readiness",
|
||||
"eligible_for_reaction",
|
||||
}
|
||||
if extra_keys:
|
||||
errors.append(f"readiness snapshot has Ghostlight-incompatible keys: {sorted(extra_keys)}")
|
||||
return errors
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(description="Run Epiphany Ghostlight-style agent heartbeat scheduling.")
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
tick = subparsers.add_parser("tick")
|
||||
tick.add_argument("--state-file", type=Path, default=DEFAULT_HEARTBEAT_STATE)
|
||||
tick.add_argument("--store-file", type=Path, default=DEFAULT_HEARTBEAT_STORE)
|
||||
tick.add_argument("--artifact-dir", type=Path, default=DEFAULT_ARTIFACT_DIR)
|
||||
tick.add_argument("--agent-dir", type=Path, default=DEFAULT_AGENT_DIR)
|
||||
tick.add_argument("--target-heartbeat-rate", type=float, default=1.0)
|
||||
tick.add_argument("--coordinator-action")
|
||||
tick.add_argument("--target-role", choices=sorted(ROLE_TARGETS))
|
||||
tick.add_argument("--urgency", type=float, default=0.75)
|
||||
tick.add_argument("--apply-rumination", action="store_true")
|
||||
tick.add_argument("--schedule-id", default="epiphany-heartbeat")
|
||||
tick.add_argument("--source-scene-ref", default="epiphany/coordinator")
|
||||
tick.add_argument(
|
||||
"--defer-completion",
|
||||
action="store_true",
|
||||
help="Leave the selected lane in-flight; cooldown begins when the complete command is called.",
|
||||
)
|
||||
|
||||
complete = subparsers.add_parser("complete")
|
||||
complete.add_argument("--state-file", type=Path, default=DEFAULT_HEARTBEAT_STATE)
|
||||
complete.add_argument("--store-file", type=Path, default=DEFAULT_HEARTBEAT_STORE)
|
||||
complete.add_argument("--artifact-dir", type=Path, default=DEFAULT_ARTIFACT_DIR)
|
||||
complete.add_argument("--role", choices=sorted(ROLE_TARGETS), required=True)
|
||||
complete.add_argument("--action-id")
|
||||
|
||||
init = subparsers.add_parser("init")
|
||||
init.add_argument("--state-file", type=Path, default=DEFAULT_HEARTBEAT_STATE)
|
||||
init.add_argument("--store-file", type=Path, default=DEFAULT_HEARTBEAT_STORE)
|
||||
init.add_argument("--target-heartbeat-rate", type=float, default=1.0)
|
||||
|
||||
status = subparsers.add_parser("status")
|
||||
status.add_argument("--state-file", type=Path, default=DEFAULT_HEARTBEAT_STATE)
|
||||
status.add_argument("--store-file", type=Path, default=DEFAULT_HEARTBEAT_STORE)
|
||||
status.add_argument("--artifact-dir", type=Path, default=DEFAULT_ARTIFACT_DIR)
|
||||
status.add_argument("--target-heartbeat-rate", type=float, default=0.0)
|
||||
status.add_argument("--limit", type=int, default=8)
|
||||
|
||||
smoke = subparsers.add_parser("smoke")
|
||||
smoke.add_argument("--agent-dir", type=Path, default=DEFAULT_AGENT_DIR)
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
if args.command == "init":
|
||||
result = native_heartbeat_command(
|
||||
"init",
|
||||
"--store",
|
||||
str(args.store_file),
|
||||
"--target-heartbeat-rate",
|
||||
str(args.target_heartbeat_rate),
|
||||
)
|
||||
print(json.dumps(result, indent=2))
|
||||
return 0
|
||||
if args.command == "tick":
|
||||
print(json.dumps(run_tick(args), indent=2))
|
||||
return 0
|
||||
if args.command == "complete":
|
||||
print(json.dumps(run_complete(args), indent=2))
|
||||
return 0
|
||||
if args.command == "status":
|
||||
print(json.dumps(run_status(args), indent=2))
|
||||
return 0
|
||||
if args.command == "smoke":
|
||||
result = run_smoke(args)
|
||||
print(json.dumps(result, indent=2))
|
||||
return 0 if result["ok"] else 1
|
||||
except Exception as exc:
|
||||
print(json.dumps({"ok": False, "error": str(exc)}, indent=2), file=sys.stderr)
|
||||
return 1
|
||||
raise AssertionError(args.command)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
|
@ -1,281 +0,0 @@
|
|||
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_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"),
|
||||
"modeling": ("epiphany.body", "body.agent-state.json"),
|
||||
"verification": ("epiphany.soul", "soul.agent-state.json"),
|
||||
"implementation": ("epiphany.hands", "hands.agent-state.json"),
|
||||
"reorientation": ("epiphany.life", "life.agent-state.json"),
|
||||
"research": ("epiphany.eyes", "eyes.agent-state.json"),
|
||||
"face": ("epiphany.face", "face.agent-state.json"),
|
||||
"coordinator": ("epiphany.self", "self.agent-state.json"),
|
||||
}
|
||||
|
||||
|
||||
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 parse_patch_arg(value: str) -> Any:
|
||||
path = Path(value)
|
||||
if path.exists():
|
||||
return load_json(path)
|
||||
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_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_STORE)
|
||||
|
||||
smoke_parser = subparsers.add_parser("smoke")
|
||||
smoke_parser.add_argument("--store", type=Path, default=DEFAULT_AGENT_STORE)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
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)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
|
@ -1,371 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tomllib
|
||||
from typing import Any
|
||||
from urllib import error
|
||||
from urllib import request
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
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"
|
||||
BUBBLE_SCHEMA_VERSION = "epiphany.face_bubble.v0"
|
||||
|
||||
|
||||
def now_stamp() -> str:
|
||||
return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
|
||||
|
||||
def read_text_arg(value: str | None, *, stdin_fallback: bool = True) -> str:
|
||||
if value:
|
||||
path = Path(value)
|
||||
if path.exists():
|
||||
return path.read_text(encoding="utf-8")
|
||||
return value
|
||||
if stdin_fallback:
|
||||
return sys.stdin.read()
|
||||
return ""
|
||||
|
||||
|
||||
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")
|
||||
|
||||
|
||||
def latest_face_artifacts(artifact_dir: Path, *, limit: int = 8) -> list[dict[str, Any]]:
|
||||
if not artifact_dir.exists():
|
||||
return []
|
||||
items: list[dict[str, Any]] = []
|
||||
for path in sorted(artifact_dir.glob("face-*.json"), key=lambda item: item.stat().st_mtime, reverse=True):
|
||||
try:
|
||||
payload = load_json(path)
|
||||
except (OSError, json.JSONDecodeError):
|
||||
continue
|
||||
if not isinstance(payload, dict):
|
||||
continue
|
||||
items.append(
|
||||
{
|
||||
"path": str(path),
|
||||
"name": path.name,
|
||||
"modifiedAt": datetime.fromtimestamp(
|
||||
path.stat().st_mtime, timezone.utc
|
||||
).replace(microsecond=0).isoformat(),
|
||||
"schemaVersion": payload.get("schema_version"),
|
||||
"status": payload.get("status"),
|
||||
"reason": payload.get("reason"),
|
||||
"content": payload.get("content"),
|
||||
"bubble": payload.get("bubble"),
|
||||
"source": payload.get("source"),
|
||||
}
|
||||
)
|
||||
if len(items) >= limit:
|
||||
break
|
||||
return items
|
||||
|
||||
|
||||
def allowed_channel_id(config: dict[str, Any]) -> str | None:
|
||||
explicit = config.get("allowed_channel_id")
|
||||
if isinstance(explicit, str) and explicit.strip():
|
||||
return explicit.strip()
|
||||
env_name = config.get("allowed_channel_id_env")
|
||||
if isinstance(env_name, str) and env_name:
|
||||
env_value = os.environ.get(env_name)
|
||||
if env_value:
|
||||
return env_value.strip()
|
||||
return None
|
||||
|
||||
|
||||
def bot_token(config: dict[str, Any]) -> str | None:
|
||||
env_name = config.get("bot_token_env")
|
||||
if not isinstance(env_name, str) or not env_name:
|
||||
return None
|
||||
value = os.environ.get(env_name)
|
||||
return value.strip() if value else None
|
||||
|
||||
|
||||
def draft_payload(content: str, *, config: dict[str, Any], status: str, reason: str) -> dict[str, Any]:
|
||||
return {
|
||||
"schema_version": CHAT_SCHEMA_VERSION,
|
||||
"created_at": datetime.now(timezone.utc).replace(microsecond=0).isoformat(),
|
||||
"status": status,
|
||||
"reason": reason,
|
||||
"allowed_channel_name": config.get("allowed_channel_name", "#aquarium"),
|
||||
"allowed_channel_id": allowed_channel_id(config),
|
||||
"content": content.strip(),
|
||||
}
|
||||
|
||||
|
||||
def write_draft(content: str, *, config: dict[str, Any], artifact_dir: Path, status: str, reason: str) -> Path:
|
||||
payload = draft_payload(content, config=config, status=status, reason=reason)
|
||||
path = artifact_dir / f"face-chat-{now_stamp()}-{uuid4().hex[:8]}.json"
|
||||
write_json(path, payload)
|
||||
return path
|
||||
|
||||
|
||||
def bubble_payload(
|
||||
content: str,
|
||||
*,
|
||||
source: str,
|
||||
status: str = "ready",
|
||||
mood: str = "attentive",
|
||||
target: str = "aquarium",
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"schema_version": BUBBLE_SCHEMA_VERSION,
|
||||
"created_at": datetime.now(timezone.utc).replace(microsecond=0).isoformat(),
|
||||
"status": status,
|
||||
"source": source,
|
||||
"target": target,
|
||||
"role_id": "face",
|
||||
"agent_id": "face",
|
||||
"display_name": "Face",
|
||||
"mood": mood,
|
||||
"content": content.strip(),
|
||||
"bubble": {
|
||||
"kind": "agent-chat",
|
||||
"anchorRoleId": "face",
|
||||
"opensIn": "aquarium",
|
||||
"requiresDiscord": False,
|
||||
"ttlSeconds": 90,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def write_bubble(
|
||||
content: str,
|
||||
*,
|
||||
artifact_dir: Path,
|
||||
source: str,
|
||||
status: str = "ready",
|
||||
mood: str = "attentive",
|
||||
) -> Path:
|
||||
payload = bubble_payload(content, source=source, status=status, mood=mood)
|
||||
path = artifact_dir / f"face-bubble-{now_stamp()}-{uuid4().hex[:8]}.json"
|
||||
write_json(path, payload)
|
||||
return path
|
||||
|
||||
|
||||
def post_message(content: str, *, channel_id: str, token: str) -> dict[str, Any]:
|
||||
body = json.dumps({"content": content}).encode("utf-8")
|
||||
req = request.Request(
|
||||
f"{DISCORD_API}/channels/{channel_id}/messages",
|
||||
data=body,
|
||||
headers={
|
||||
"Authorization": f"Bot {token}",
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": "EpiphanyFace/0.1",
|
||||
},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with request.urlopen(req, timeout=20) as response:
|
||||
return json.loads(response.read().decode("utf-8"))
|
||||
except error.HTTPError as exc:
|
||||
detail = exc.read().decode("utf-8", errors="replace")
|
||||
raise RuntimeError(f"Discord post failed with HTTP {exc.code}: {detail}") from exc
|
||||
|
||||
|
||||
def run_draft(args: argparse.Namespace) -> dict[str, Any]:
|
||||
config = load_config(args.config)
|
||||
content = read_text_arg(args.content)
|
||||
if not content.strip():
|
||||
raise ValueError("Face chat content is empty")
|
||||
path = write_draft(
|
||||
content,
|
||||
config=config,
|
||||
artifact_dir=args.artifact_dir,
|
||||
status="draft",
|
||||
reason="drafted without posting",
|
||||
)
|
||||
return {"ok": True, "posted": False, "draftPath": str(path)}
|
||||
|
||||
|
||||
def run_bubble(args: argparse.Namespace) -> dict[str, Any]:
|
||||
content = read_text_arg(args.content)
|
||||
if not content.strip():
|
||||
raise ValueError("Face bubble content is empty")
|
||||
path = write_bubble(
|
||||
content,
|
||||
artifact_dir=args.artifact_dir,
|
||||
source=args.source,
|
||||
status=args.status,
|
||||
mood=args.mood,
|
||||
)
|
||||
return {"ok": True, "posted": False, "bubblePath": str(path), "bubble": load_json(path)}
|
||||
|
||||
|
||||
def run_post(args: argparse.Namespace) -> dict[str, Any]:
|
||||
config = load_config(args.config)
|
||||
content = read_text_arg(args.content)
|
||||
if not content.strip():
|
||||
raise ValueError("Face chat content is empty")
|
||||
configured_channel_id = allowed_channel_id(config)
|
||||
requested_channel_id = args.channel_id or configured_channel_id
|
||||
if not configured_channel_id:
|
||||
path = write_draft(
|
||||
content,
|
||||
config=config,
|
||||
artifact_dir=args.artifact_dir,
|
||||
status="blocked",
|
||||
reason="missing #aquarium channel id",
|
||||
)
|
||||
return {"ok": False, "posted": False, "blocked": "missing-channel-id", "draftPath": str(path)}
|
||||
if requested_channel_id != configured_channel_id:
|
||||
path = write_draft(
|
||||
content,
|
||||
config=config,
|
||||
artifact_dir=args.artifact_dir,
|
||||
status="blocked",
|
||||
reason="requested channel does not match configured #aquarium channel id",
|
||||
)
|
||||
return {"ok": False, "posted": False, "blocked": "wrong-channel", "draftPath": str(path)}
|
||||
token = bot_token(config)
|
||||
if not token:
|
||||
path = write_draft(
|
||||
content,
|
||||
config=config,
|
||||
artifact_dir=args.artifact_dir,
|
||||
status="blocked",
|
||||
reason="missing Discord bot token",
|
||||
)
|
||||
return {"ok": False, "posted": False, "blocked": "missing-token", "draftPath": str(path)}
|
||||
response = post_message(content.strip(), channel_id=configured_channel_id, token=token)
|
||||
path = write_draft(
|
||||
content,
|
||||
config=config,
|
||||
artifact_dir=args.artifact_dir,
|
||||
status="posted",
|
||||
reason=f"posted message {response.get('id')}",
|
||||
)
|
||||
return {"ok": True, "posted": True, "messageId": response.get("id"), "draftPath": str(path)}
|
||||
|
||||
|
||||
def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
|
||||
import tempfile
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tmp_dir = Path(tmp)
|
||||
config = {
|
||||
"schema_version": "epiphany.face_discord.v0",
|
||||
"allowed_channel_name": "#aquarium",
|
||||
"allowed_channel_id": None,
|
||||
"allowed_channel_id_env": "EPIPHANY_FACE_AQUARIUM_CHANNEL_ID_TEST",
|
||||
"bot_token_env": "DISCORD_BOT_TOKEN_TEST",
|
||||
"policy": ["Face may post only in #aquarium."],
|
||||
}
|
||||
config_path = tmp_dir / "face-discord.json"
|
||||
write_json(config_path, config)
|
||||
draft = run_draft(
|
||||
argparse.Namespace(
|
||||
config=config_path,
|
||||
artifact_dir=tmp_dir,
|
||||
content="Face notices Body and Soul disagree about evidence shape.",
|
||||
)
|
||||
)
|
||||
bubble = run_bubble(
|
||||
argparse.Namespace(
|
||||
artifact_dir=tmp_dir,
|
||||
content="Face opens an Aquarium bubble even while Discord is unavailable.",
|
||||
source="smoke/face",
|
||||
status="ready",
|
||||
mood="attentive",
|
||||
)
|
||||
)
|
||||
blocked = run_post(
|
||||
argparse.Namespace(
|
||||
config=config_path,
|
||||
artifact_dir=tmp_dir,
|
||||
content="Face should not post without a configured #aquarium channel id.",
|
||||
channel_id=None,
|
||||
)
|
||||
)
|
||||
os.environ["EPIPHANY_FACE_AQUARIUM_CHANNEL_ID_TEST"] = "123"
|
||||
wrong = run_post(
|
||||
argparse.Namespace(
|
||||
config=config_path,
|
||||
artifact_dir=tmp_dir,
|
||||
content="Face should not post outside #aquarium.",
|
||||
channel_id="456",
|
||||
)
|
||||
)
|
||||
ok = (
|
||||
draft["ok"]
|
||||
and bubble["ok"]
|
||||
and bubble["bubble"]["schema_version"] == BUBBLE_SCHEMA_VERSION
|
||||
and bubble["bubble"]["bubble"]["requiresDiscord"] is False
|
||||
and not blocked["ok"]
|
||||
and blocked["blocked"] == "missing-channel-id"
|
||||
and not wrong["ok"]
|
||||
and wrong["blocked"] == "wrong-channel"
|
||||
)
|
||||
return {"ok": ok, "draft": draft, "bubble": bubble, "blocked": blocked, "wrongChannel": wrong}
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(description="Draft or post Epiphany Face chat with #aquarium-only guardrails.")
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
for command in ("draft", "post"):
|
||||
sub = subparsers.add_parser(command)
|
||||
sub.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
|
||||
sub.add_argument("--artifact-dir", type=Path, default=DEFAULT_ARTIFACT_DIR)
|
||||
sub.add_argument("--content", help="Content string or path. Reads stdin when omitted.")
|
||||
if command == "post":
|
||||
sub.add_argument("--channel-id", help="Must match configured #aquarium channel id if supplied.")
|
||||
bubble = subparsers.add_parser("bubble")
|
||||
bubble.add_argument("--artifact-dir", type=Path, default=DEFAULT_ARTIFACT_DIR)
|
||||
bubble.add_argument("--content", help="Content string or path. Reads stdin when omitted.")
|
||||
bubble.add_argument("--source", default="epiphany/face")
|
||||
bubble.add_argument("--status", default="ready")
|
||||
bubble.add_argument("--mood", default="attentive")
|
||||
smoke = subparsers.add_parser("smoke")
|
||||
smoke.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
if args.command == "draft":
|
||||
result = run_draft(args)
|
||||
elif args.command == "bubble":
|
||||
result = run_bubble(args)
|
||||
elif args.command == "post":
|
||||
result = run_post(args)
|
||||
elif args.command == "smoke":
|
||||
result = run_smoke(args)
|
||||
else:
|
||||
raise AssertionError(args.command)
|
||||
print(json.dumps(result, indent=2))
|
||||
return 0 if result.get("ok") else 1
|
||||
except Exception as exc:
|
||||
print(json.dumps({"ok": False, "error": str(exc)}, indent=2), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
|
@ -13,18 +13,7 @@ import tomllib
|
|||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from epiphany_agent_heartbeat import DEFAULT_ARTIFACT_DIR as DEFAULT_HEARTBEAT_ARTIFACT_DIR
|
||||
from epiphany_agent_heartbeat import DEFAULT_HEARTBEAT_STATE
|
||||
from epiphany_agent_heartbeat import DISPLAY_NAMES as HEARTBEAT_DISPLAY_NAMES
|
||||
from epiphany_agent_heartbeat import ROLE_ORDER as HEARTBEAT_ROLE_ORDER
|
||||
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
|
||||
from epiphany_mvp_status import DEFAULT_APP_SERVER
|
||||
from epiphany_mvp_status import collect_status
|
||||
from epiphany_mvp_status import render_status
|
||||
|
|
@ -38,7 +27,21 @@ 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 = DEFAULT_AGENT_STORE
|
||||
DEFAULT_AGENT_MEMORY_DIR = ROOT / "state" / "agents.msgpack"
|
||||
DEFAULT_HEARTBEAT_STORE = ROOT / "state" / "agent-heartbeats.msgpack"
|
||||
DEFAULT_HEARTBEAT_ARTIFACT_DIR = ROOT / ".epiphany-heartbeats"
|
||||
DEFAULT_FACE_ARTIFACT_DIR = ROOT / ".epiphany-face"
|
||||
HEARTBEAT_DISPLAY_NAMES = {
|
||||
"coordinator": "Self",
|
||||
"face": "Face",
|
||||
"imagination": "Imagination",
|
||||
"research": "Eyes",
|
||||
"modeling": "Body",
|
||||
"implementation": "Hands",
|
||||
"verification": "Soul",
|
||||
"reorientation": "Life",
|
||||
}
|
||||
HEARTBEAT_ROLE_ORDER = list(HEARTBEAT_DISPLAY_NAMES)
|
||||
EPIPHANY_PROMPTS_PATH = (
|
||||
ROOT
|
||||
/ "vendor"
|
||||
|
|
@ -53,6 +56,69 @@ TERMINAL_ROLE_STATUSES = {"completed", "failed", "cancelled"}
|
|||
TERMINAL_REORIENT_STATUSES = {"completed", "failed", "cancelled"}
|
||||
|
||||
|
||||
def native_epiphany_bin(bin_name: str, *args: str) -> dict[str, Any]:
|
||||
exe = Path(os.environ.get("CARGO_TARGET_DIR", r"C:\Users\Meta\.cargo-target-codex")) / "debug" / f"{bin_name}.exe"
|
||||
if exe.exists():
|
||||
command = [str(exe), *args]
|
||||
else:
|
||||
command = [
|
||||
"cargo",
|
||||
"run",
|
||||
"--quiet",
|
||||
"--manifest-path",
|
||||
str(ROOT / "epiphany-core" / "Cargo.toml"),
|
||||
"--bin",
|
||||
bin_name,
|
||||
"--",
|
||||
*args,
|
||||
]
|
||||
completed = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, check=False)
|
||||
if completed.returncode != 0:
|
||||
raise RuntimeError(completed.stderr.strip() or completed.stdout.strip() or f"{bin_name} failed")
|
||||
return json.loads(completed.stdout)
|
||||
|
||||
|
||||
def heartbeat_status(*, store_file: Path, artifact_dir: Path, limit: int = 8) -> dict[str, Any]:
|
||||
return native_epiphany_bin(
|
||||
"epiphany-heartbeat-store",
|
||||
"status",
|
||||
"--store",
|
||||
str(store_file),
|
||||
"--artifact-dir",
|
||||
str(artifact_dir),
|
||||
"--limit",
|
||||
str(limit),
|
||||
)
|
||||
|
||||
|
||||
def write_bubble(content: str, *, artifact_dir: Path, source: str, status: str = "ready", mood: str = "attentive") -> Path:
|
||||
response = native_epiphany_bin(
|
||||
"epiphany-face-discord",
|
||||
"bubble",
|
||||
"--artifact-dir",
|
||||
str(artifact_dir),
|
||||
"--content",
|
||||
content,
|
||||
"--source",
|
||||
source,
|
||||
"--status",
|
||||
status,
|
||||
"--mood",
|
||||
mood,
|
||||
)
|
||||
return Path(response["bubblePath"])
|
||||
|
||||
|
||||
def latest_face_artifacts(artifact_dir: Path) -> list[dict[str, Any]]:
|
||||
response = native_epiphany_bin(
|
||||
"epiphany-face-discord",
|
||||
"latest",
|
||||
"--artifact-dir",
|
||||
str(artifact_dir),
|
||||
)
|
||||
return response.get("latestArtifacts", [])
|
||||
|
||||
|
||||
def maybe_apply_role_self_patch(
|
||||
response: dict[str, Any], *, agent_memory_dir: Path
|
||||
) -> dict[str, Any] | None:
|
||||
|
|
@ -78,7 +144,16 @@ def maybe_apply_role_self_patch(
|
|||
"reasons": ["roleAccept response did not include a roleId for selfPatch application"],
|
||||
"applied": False,
|
||||
}
|
||||
result = apply_self_patch(role_id, self_patch, agent_dir=agent_memory_dir)
|
||||
result = native_epiphany_bin(
|
||||
"epiphany-agent-memory-store",
|
||||
"apply-patch",
|
||||
"--store",
|
||||
str(agent_memory_dir),
|
||||
"--role-id",
|
||||
role_id,
|
||||
"--patch",
|
||||
json.dumps(self_patch),
|
||||
)
|
||||
result["appliedFromRoleAccept"] = True
|
||||
return result
|
||||
|
||||
|
|
@ -1124,26 +1199,36 @@ def heartbeat_bubble_text(event: dict[str, Any]) -> str:
|
|||
def run_local_surface_action(args: argparse.Namespace, *, artifact_dir: Path) -> dict[str, Any]:
|
||||
if args.action == "heartbeatStatus":
|
||||
response = heartbeat_status(
|
||||
state_file=args.heartbeat_state_file,
|
||||
store_file=args.heartbeat_store_file,
|
||||
artifact_dir=args.heartbeat_artifact_dir,
|
||||
)
|
||||
summary = "Read the Ghostlight heartbeat initiative status."
|
||||
elif args.action == "runHeartbeat":
|
||||
schedule_id = f"epiphany-gui-heartbeat-{time.time_ns()}-{os.getpid()}"
|
||||
response = run_heartbeat_tick(
|
||||
argparse.Namespace(
|
||||
state_file=args.heartbeat_state_file,
|
||||
artifact_dir=args.heartbeat_artifact_dir,
|
||||
agent_dir=args.agent_memory_dir,
|
||||
target_heartbeat_rate=args.target_heartbeat_rate,
|
||||
coordinator_action=args.heartbeat_coordinator_action,
|
||||
target_role=args.heartbeat_target_role,
|
||||
urgency=args.heartbeat_urgency,
|
||||
apply_rumination=args.apply_rumination,
|
||||
schedule_id=schedule_id,
|
||||
source_scene_ref="epiphany/gui/heartbeat",
|
||||
)
|
||||
)
|
||||
heartbeat_args = [
|
||||
"tick",
|
||||
"--store",
|
||||
str(args.heartbeat_store_file),
|
||||
"--artifact-dir",
|
||||
str(args.heartbeat_artifact_dir),
|
||||
"--target-heartbeat-rate",
|
||||
str(args.target_heartbeat_rate),
|
||||
"--urgency",
|
||||
str(args.heartbeat_urgency),
|
||||
"--schedule-id",
|
||||
schedule_id,
|
||||
"--source-scene-ref",
|
||||
"epiphany/gui/heartbeat",
|
||||
"--agent-store",
|
||||
str(args.agent_memory_dir),
|
||||
]
|
||||
if args.heartbeat_coordinator_action:
|
||||
heartbeat_args.extend(["--coordinator-action", args.heartbeat_coordinator_action])
|
||||
if args.heartbeat_target_role:
|
||||
heartbeat_args.extend(["--target-role", args.heartbeat_target_role])
|
||||
if args.apply_rumination:
|
||||
heartbeat_args.append("--apply-rumination")
|
||||
response = native_epiphany_bin("epiphany-heartbeat-store", *heartbeat_args)
|
||||
event = response.get("event") or {}
|
||||
bubble_path = write_bubble(
|
||||
heartbeat_bubble_text(event),
|
||||
|
|
@ -1159,7 +1244,7 @@ def run_local_surface_action(args: argparse.Namespace, *, artifact_dir: Path) ->
|
|||
content = args.face_content
|
||||
if not content:
|
||||
current = heartbeat_status(
|
||||
state_file=args.heartbeat_state_file,
|
||||
store_file=args.heartbeat_store_file,
|
||||
artifact_dir=args.heartbeat_artifact_dir,
|
||||
)
|
||||
latest = current.get("latestEvent") or {}
|
||||
|
|
@ -1584,7 +1669,7 @@ def main() -> int:
|
|||
"faceBubble",
|
||||
],
|
||||
)
|
||||
parser.add_argument("--heartbeat-state-file", type=Path, default=DEFAULT_HEARTBEAT_STATE)
|
||||
parser.add_argument("--heartbeat-store-file", type=Path, default=DEFAULT_HEARTBEAT_STORE)
|
||||
parser.add_argument("--heartbeat-artifact-dir", type=Path, default=DEFAULT_HEARTBEAT_ARTIFACT_DIR)
|
||||
parser.add_argument("--face-artifact-dir", type=Path, default=DEFAULT_FACE_ARTIFACT_DIR)
|
||||
parser.add_argument("--target-heartbeat-rate", type=float, default=1.0)
|
||||
|
|
|
|||
|
|
@ -4,13 +4,12 @@ import argparse
|
|||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
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
|
||||
|
|
@ -29,7 +28,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 = DEFAULT_AGENT_STORE
|
||||
DEFAULT_AGENT_MEMORY_DIR = ROOT / "state" / "agents.msgpack"
|
||||
TERMINAL_ROLE_STATUSES = {"completed", "failed", "cancelled"}
|
||||
TERMINAL_REORIENT_STATUSES = {"completed", "failed", "cancelled"}
|
||||
STOP_ACTIONS = {
|
||||
|
|
@ -42,6 +41,28 @@ STOP_ACTIONS = {
|
|||
}
|
||||
|
||||
|
||||
def native_agent_memory(*args: str) -> dict[str, Any]:
|
||||
exe = Path(os.environ.get("CARGO_TARGET_DIR", r"C:\Users\Meta\.cargo-target-codex")) / "debug" / "epiphany-agent-memory-store.exe"
|
||||
if exe.exists():
|
||||
command = [str(exe), *args]
|
||||
else:
|
||||
command = [
|
||||
"cargo",
|
||||
"run",
|
||||
"--quiet",
|
||||
"--manifest-path",
|
||||
str(ROOT / "epiphany-core" / "Cargo.toml"),
|
||||
"--bin",
|
||||
"epiphany-agent-memory-store",
|
||||
"--",
|
||||
*args,
|
||||
]
|
||||
completed = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, check=False)
|
||||
if completed.returncode != 0:
|
||||
raise RuntimeError(completed.stderr.strip() or completed.stdout.strip() or "epiphany-agent-memory-store failed")
|
||||
return json.loads(completed.stdout)
|
||||
|
||||
|
||||
def maybe_apply_role_self_patch(
|
||||
response: dict[str, Any], *, agent_memory_dir: Path
|
||||
) -> dict[str, Any] | None:
|
||||
|
|
@ -67,7 +88,15 @@ def maybe_apply_role_self_patch(
|
|||
"reasons": ["roleAccept response did not include a roleId for selfPatch application"],
|
||||
"applied": False,
|
||||
}
|
||||
result = apply_self_patch(role_id, self_patch, agent_dir=agent_memory_dir)
|
||||
result = native_agent_memory(
|
||||
"apply-patch",
|
||||
"--store",
|
||||
str(agent_memory_dir),
|
||||
"--role-id",
|
||||
role_id,
|
||||
"--patch",
|
||||
json.dumps(self_patch),
|
||||
)
|
||||
result["appliedFromRoleAccept"] = True
|
||||
return result
|
||||
|
||||
|
|
|
|||
|
|
@ -3,12 +3,11 @@ from __future__ import annotations
|
|||
import argparse
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
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
|
||||
|
|
@ -19,6 +18,28 @@ from epiphany_phase5_smoke import require
|
|||
DEFAULT_ARTIFACT_ROOT = ROOT / ".epiphany-dogfood" / "coordinator-smoke"
|
||||
|
||||
|
||||
def native_agent_memory(*args: str) -> dict[str, Any]:
|
||||
exe = Path(r"C:\Users\Meta\.cargo-target-codex") / "debug" / "epiphany-agent-memory-store.exe"
|
||||
if exe.exists():
|
||||
command = [str(exe), *args]
|
||||
else:
|
||||
command = [
|
||||
"cargo",
|
||||
"run",
|
||||
"--quiet",
|
||||
"--manifest-path",
|
||||
str(ROOT / "epiphany-core" / "Cargo.toml"),
|
||||
"--bin",
|
||||
"epiphany-agent-memory-store",
|
||||
"--",
|
||||
*args,
|
||||
]
|
||||
completed = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, check=False)
|
||||
if completed.returncode != 0:
|
||||
raise RuntimeError(completed.stderr.strip() or completed.stdout.strip() or "epiphany-agent-memory-store failed")
|
||||
return json.loads(completed.stdout)
|
||||
|
||||
|
||||
def reset_artifact_root(path: Path) -> None:
|
||||
root = (ROOT / ".epiphany-dogfood").resolve()
|
||||
resolved = path.resolve()
|
||||
|
|
@ -103,7 +124,7 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
|
|||
artifact_root = args.artifact_root.resolve()
|
||||
reset_artifact_root(artifact_root)
|
||||
agent_memory_store = artifact_root / "agent-memory.msgpack"
|
||||
shutil.copy2(resolve_store_path(DEFAULT_AGENT_MEMORY_DIR), agent_memory_store)
|
||||
shutil.copy2(DEFAULT_AGENT_MEMORY_DIR, agent_memory_store)
|
||||
|
||||
cold = run_coordinator(
|
||||
coordinator_args(
|
||||
|
|
@ -155,7 +176,13 @@ 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)
|
||||
native_agent_memory(
|
||||
"project-json-dir",
|
||||
"--store",
|
||||
str(agent_memory_store),
|
||||
"--output-dir",
|
||||
str(projected_memory),
|
||||
)
|
||||
require(
|
||||
"mem-body-phase6-role-smoke"
|
||||
in (projected_memory / "body.agent-state.json").read_text(encoding="utf-8"),
|
||||
|
|
|
|||
|
|
@ -4,20 +4,19 @@ import argparse
|
|||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from typing import Any
|
||||
|
||||
from epiphany_agent_heartbeat import DEFAULT_ARTIFACT_DIR as DEFAULT_HEARTBEAT_ARTIFACT_DIR
|
||||
from epiphany_agent_heartbeat import DEFAULT_HEARTBEAT_STATE
|
||||
from epiphany_agent_heartbeat import heartbeat_status
|
||||
from epiphany_agent_telemetry import write_transcript_telemetry
|
||||
from epiphany_face_discord import DEFAULT_ARTIFACT_DIR as DEFAULT_FACE_ARTIFACT_DIR
|
||||
from epiphany_face_discord import latest_face_artifacts
|
||||
from epiphany_phase5_smoke import AppServerClient
|
||||
from epiphany_phase5_smoke import DEFAULT_APP_SERVER
|
||||
from epiphany_phase5_smoke import ROOT
|
||||
|
||||
|
||||
DEFAULT_CODEX_HOME = Path(os.environ.get("CODEX_HOME", Path.home() / ".codex"))
|
||||
DEFAULT_HEARTBEAT_STORE = ROOT / "state" / "agent-heartbeats.msgpack"
|
||||
DEFAULT_HEARTBEAT_ARTIFACT_DIR = ROOT / ".epiphany-heartbeats"
|
||||
DEFAULT_FACE_ARTIFACT_DIR = ROOT / ".epiphany-face"
|
||||
DEFAULT_TRANSCRIPT = ROOT / ".epiphany-status" / "epiphany-mvp-status-transcript.jsonl"
|
||||
DEFAULT_STDERR = ROOT / ".epiphany-status" / "epiphany-mvp-status-server.stderr.log"
|
||||
SEALED_DIRECT_THOUGHT_KEYS = {
|
||||
|
|
@ -29,6 +28,53 @@ SEALED_DIRECT_THOUGHT_KEYS = {
|
|||
}
|
||||
|
||||
|
||||
def native_epiphany_bin(bin_name: str, *args: str) -> dict[str, Any]:
|
||||
exe = Path(os.environ.get("CARGO_TARGET_DIR", r"C:\Users\Meta\.cargo-target-codex")) / "debug" / f"{bin_name}.exe"
|
||||
if exe.exists():
|
||||
command = [str(exe), *args]
|
||||
else:
|
||||
command = [
|
||||
"cargo",
|
||||
"run",
|
||||
"--quiet",
|
||||
"--manifest-path",
|
||||
str(ROOT / "epiphany-core" / "Cargo.toml"),
|
||||
"--bin",
|
||||
bin_name,
|
||||
"--",
|
||||
*args,
|
||||
]
|
||||
completed = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, check=False)
|
||||
if completed.returncode != 0:
|
||||
raise RuntimeError(completed.stderr.strip() or completed.stdout.strip() or f"{bin_name} failed")
|
||||
return json.loads(completed.stdout)
|
||||
|
||||
|
||||
def heartbeat_status(*, artifact_dir: Path = DEFAULT_HEARTBEAT_ARTIFACT_DIR, limit: int = 8) -> dict[str, Any]:
|
||||
return native_epiphany_bin(
|
||||
"epiphany-heartbeat-store",
|
||||
"status",
|
||||
"--store",
|
||||
str(DEFAULT_HEARTBEAT_STORE),
|
||||
"--artifact-dir",
|
||||
str(artifact_dir),
|
||||
"--limit",
|
||||
str(limit),
|
||||
)
|
||||
|
||||
|
||||
def latest_face_artifacts(artifact_dir: Path, *, limit: int = 8) -> list[dict[str, Any]]:
|
||||
result = native_epiphany_bin(
|
||||
"epiphany-face-discord",
|
||||
"latest",
|
||||
"--artifact-dir",
|
||||
str(artifact_dir),
|
||||
"--limit",
|
||||
str(limit),
|
||||
)
|
||||
return result.get("latestArtifacts", [])
|
||||
|
||||
|
||||
def sealed_direct_thought(key: str, value: Any) -> dict[str, Any]:
|
||||
length: int | None = None
|
||||
if isinstance(value, (list, str, dict)):
|
||||
|
|
@ -135,10 +181,7 @@ def collect_status(
|
|||
reorient_result = client.send("thread/epiphany/reorientResult", {"threadId": thread_id})
|
||||
crrc = client.send("thread/epiphany/crrc", {"threadId": thread_id})
|
||||
coordinator = client.send("thread/epiphany/coordinator", {"threadId": thread_id})
|
||||
heartbeat = heartbeat_status(
|
||||
state_file=DEFAULT_HEARTBEAT_STATE,
|
||||
artifact_dir=DEFAULT_HEARTBEAT_ARTIFACT_DIR,
|
||||
)
|
||||
heartbeat = heartbeat_status(artifact_dir=DEFAULT_HEARTBEAT_ARTIFACT_DIR)
|
||||
face = {
|
||||
"status": "ready",
|
||||
"artifactDir": str(DEFAULT_FACE_ARTIFACT_DIR),
|
||||
|
|
|
|||
Reference in a new issue