diff --git a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs index bbe2a486..a03e462f 100644 --- a/epiphany-core/src/bin/epiphany-mvp-coordinator.rs +++ b/epiphany-core/src/bin/epiphany-mvp-coordinator.rs @@ -51,7 +51,7 @@ mod status_cli; const DEFAULT_APP_SERVER: &str = r"C:\Users\Meta\.cargo-target-codex\debug\codex-app-server.exe"; const DEFAULT_MODEL_RUNTIME_BIN: &str = "epiphany-model-runtime"; const DEFAULT_TOOL_ADAPTER_BIN: &str = "epiphany-tool-codex-mcp-spine"; -const WORKER_AUTO_TOOL_MAX_ROUNDS: usize = 12; +const WORKER_AUTO_TOOL_MAX_ROUNDS: usize = 24; const REORIENT_BINDING_ID: &str = "reorient-worker"; const GRAPH_NODE_ID: &str = "reorient-target"; const WATCHED_RELATIVE_PATH: &str = "src/reorient_target.rs"; diff --git a/epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs b/epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs index efc1b122..e31ca9d1 100644 --- a/epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs +++ b/epiphany-openai-runtime/src/bin/epiphany-openai-runtime.rs @@ -36,6 +36,8 @@ use epiphany_openai_runtime::run_model_turn; use epiphany_openai_runtime::run_openai_model_turn; use epiphany_openai_runtime::run_tool_followup_model_turn; use epiphany_openai_runtime::run_worker_launch; +use epiphany_tool_adapter::EpiphanyToolInvocationIntent; +use epiphany_tool_adapter::tool_invocation_intent_key; use serde_json::json; use uuid::Uuid; @@ -562,9 +564,54 @@ async fn run_worker_launch_with_tool_continuation( let mut openai_summary = run_model_turn(&options.provider, current_options.clone(), initial_request).await?; let mut tool_rounds = Vec::new(); + let mut previous_tool_fingerprints: Option> = None; + let mut consecutive_repeated_tool_rounds = 0usize; + let mut round = 0usize; - for round in 0..options.max_tool_rounds { - if openai_summary.tool_intent_ids.is_empty() { + while !openai_summary.tool_intent_ids.is_empty() { + let tool_fingerprints = + tool_intent_fingerprints(&options.store_path, &openai_summary.tool_intent_ids)?; + if same_nonempty_tool_request_round( + previous_tool_fingerprints.as_deref(), + &tool_fingerprints, + ) { + consecutive_repeated_tool_rounds += 1; + } else { + consecutive_repeated_tool_rounds = 0; + } + if consecutive_repeated_tool_rounds >= 2 { + let summary = format!( + "worker {} repeated the same pending tool request set for {} consecutive follow-up rounds", + launch_request.job_id, + consecutive_repeated_tool_rounds + 1 + ); + let result = fail_worker_job( + &options.store_path, + &launch_request.job_id, + summary.clone(), + "Inspect the repeated tool fingerprints and decide whether the worker needs a narrower evidence bundle, a repaired tool, or a higher explicit limit." + .to_string(), + )?; + return Ok(json!({ + "status": "tool-loop-stalled", + "store": options.store_path, + "jobId": launch_request.job_id, + "bindingId": launch_request.binding_id, + "role": launch_request.role, + "requestId": current_request_id, + "openaiResultId": openai_summary.result_id, + "openaiVerdict": openai_summary.verdict, + "openaiSummary": openai_summary.summary, + "workerResultId": result.result_id, + "verdict": result.verdict, + "summary": summary, + "nextSafeMove": result.next_safe_move, + "pendingToolIntentIds": openai_summary.tool_intent_ids, + "pendingToolFingerprints": tool_fingerprints, + "toolRounds": tool_rounds, + })); + } + if round >= options.max_tool_rounds { break; } let mut adapter_runs = Vec::new(); @@ -589,17 +636,19 @@ async fn run_worker_launch_with_tool_continuation( current_request_id = followup_request_id; tool_rounds.push(json!({ "round": round, + "toolFingerprints": tool_fingerprints.clone(), "adapterRuns": adapter_runs, "followupRequestId": current_request_id, "summary": openai_summary, })); + previous_tool_fingerprints = Some(tool_fingerprints); + round += 1; } if !openai_summary.tool_intent_ids.is_empty() { let summary = format!( "worker {} still requested tools after {} automatic tool rounds", - launch_request.job_id, - options.max_tool_rounds + launch_request.job_id, options.max_tool_rounds ); let result = fail_worker_job( &options.store_path, @@ -656,6 +705,88 @@ async fn run_worker_launch_with_tool_continuation( })) } +fn tool_intent_fingerprints(store_path: &Path, intent_ids: &[String]) -> Result> { + let mut cache = epiphany_core::runtime_spine_cache(store_path)?; + cache.pull_all_backing_stores()?; + let mut fingerprints = Vec::new(); + for intent_id in intent_ids { + let fingerprint = match cache + .get::(&tool_invocation_intent_key(intent_id))? + { + Some(intent) => tool_intent_fingerprint(&intent), + None => format!("missing-intent:{intent_id}"), + }; + fingerprints.push(fingerprint); + } + fingerprints.sort(); + Ok(fingerprints) +} + +fn tool_intent_fingerprint(intent: &EpiphanyToolInvocationIntent) -> String { + format!( + "{}::{}::{}", + intent.server, + intent.tool_name, + canonical_jsonish(&intent.arguments_json) + ) +} + +fn canonical_jsonish(raw: &str) -> String { + serde_json::from_str::(raw) + .and_then(|value| serde_json::to_string(&value)) + .unwrap_or_else(|_| raw.to_string()) +} + +fn same_nonempty_tool_request_round(previous: Option<&[String]>, current: &[String]) -> bool { + !current.is_empty() && previous == Some(current) +} + +#[cfg(test)] +mod tests { + use super::*; + use epiphany_tool_adapter::EpiphanyToolInvocationIntent; + + #[test] + fn same_nonempty_tool_request_round_requires_real_repetition() { + let first = vec!["source::read_file::{\"path\":\"README.md\"}".to_string()]; + let second = vec!["source::git_show::{\"commit\":\"abc\"}".to_string()]; + + assert!(!same_nonempty_tool_request_round(None, &first)); + assert!(!same_nonempty_tool_request_round(Some(&first), &[])); + assert!(!same_nonempty_tool_request_round(Some(&first), &second)); + assert!(same_nonempty_tool_request_round(Some(&first), &first)); + } + + #[test] + fn tool_intent_fingerprint_ignores_argument_key_order() { + let left = EpiphanyToolInvocationIntent::new( + "left", + "codex-mcp", + "epiphany_source", + "read_file", + r#"{"path":"README.md","offset":0}"#, + "model", + "test", + "2026-06-13T00:00:00Z", + ); + let right = EpiphanyToolInvocationIntent::new( + "right", + "codex-mcp", + "epiphany_source", + "read_file", + r#"{"offset":0,"path":"README.md"}"#, + "model", + "test", + "2026-06-13T00:00:00Z", + ); + + assert_eq!( + tool_intent_fingerprint(&left), + tool_intent_fingerprint(&right) + ); + } +} + async fn run_worker_options(options: RunWorkerCliOptions) -> Result { if options.auto_tools { run_worker_launch_with_tool_continuation(options).await diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index b86e14de..8e7c477a 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -36,7 +36,7 @@ remembers doctrine; the branch remembers the blade. - Canonical anatomy now lives in `notes/epiphany-anatomy.md`. Embodied sub-agents are Self, Face, Imagination, Eyes, Proprioception, Hands, and Soul. Body, Mind, Continuity, and Substrate Gate are substrate/state/protocol surfaces, not sub-agent identities. State is split by layer: `work_organ` for resident Epiphany sub-agents, `persona` for portable public/person-shaped state shared by Epiphany Face, VoidBot repo Faces, and Ghostlight characters, and heartbeat/swarm state for scheduling and coordination physiology. Persona state now carries provenance, required public presentation, `date-time` timestamps, typed `candidateActions`, strict anchored thoughts with non-authoritative extensions, custom enum companion labels, and typed affect records for bonds/status reads/doctrine stances. - The repo now has a one-command local operator path: `.\tools\epiphany_local_run.ps1`. Default mode is `smoke`; it builds the retained Codex app-server compatibility edge, builds native Epiphany operator binaries, runs the coordinator smoke, and writes launcher artifacts under `.epiphany-run/` plus coordinator artifacts under `.epiphany-dogfood/`. `-Mode status` is now Epiphany-native: it builds only Epiphany operator binaries, reads `state/thread-state.msgpack` when present, derives status through `epiphany-core`, and does not start or require `codex-app-server`. Use `-Mode plan` or `-Mode run -MaxSteps 4` for the raw bridge-equipped coordinator entrypoints; use `-Mode mvp -FaceInput "" -MaxSteps 4` for the local product cycle that projects Face's character turn, writes a Face/Aquarium bubble, bootstraps a minimal local checkpoint for fresh threads, runs the coordinator with auto-tools, then runs heartbeat sleep/dream maintenance. Live plan/run/mvp modes use the workspace `state/runtime-spine.msgpack`, because CodexThread launch writes worker requests there; the run bundle remains artifact evidence, not runtime lifecycle authority. Add `-ThreadId ` and `-Workspace ` to inspect or continue an existing thread. `status`, `plan`, and `smoke` do not spend model calls; `run` and `mvp` build and use `epiphany-openai-runtime`. Coordinator workers now launch detached and are polled through runtime-spine instead of blocking the coordinator. MVP runs are non-ephemeral by default so `-ThreadId ` can resume and poll later. `-MaxRuntimeSeconds ` is passed into worker runtime; timeout writes a failed worker receipt and exits. Failed modeling now blocks downstream verification until the failed result is reviewed. - Current Mom-ready status: the normal MVP pass reaches Face -> coordinator -> detached runtime -> heartbeat sleep, and modeling workers now complete through the ChatGPT subscription transport. The first failure was a stack of violated observability/runtime invariants: worker prompts prepended the whole shared persistent-memory rite, Responses frame liveness was invisible until completion, and the runtime tried to persist hundreds of text deltas before completing the worker job. Role/reorient workers now get a compact Epiphany worker boundary instead of full persistent memory; runtime-spine records sampled raw Responses frame kinds with small previews; contiguous reasoning/text deltas compact before durable storage; and live proofs completed `2fe38dcd-d99e-4c73-9a58-afcc81f851c7`, `241e3851-e3ea-4877-a63b-0d2bbd96a7e2`, and `85149a26-6975-403f-ac93-092b717c5825` instead of timing out. The second failure was stale lifecycle authority: completed runtime jobs remained as unresolved `runtime_links`, replacement launches treated historical active links as current, and one bad validation path opened an orphan job before rejecting the state patch. Latest-link-wins is now the runtime-link invariant, terminal links project completed jobs, stale active history cannot veto replacement, launch validation happens before opening runtime jobs, and completed-but-unreviewable modeling findings stop for review instead of relaunching the same lane. The Eyes/source-gather fork is now landed: Research is a fixed Eyes lane with launch/result/accept/status/coordinator/protocol support, and `regather-needed` modeling findings route to `LaunchResearch` instead of relaunching blind Proprioception. Research statePatch admission is Eyes-shaped only: observations, evidence, scratch, and optional investigationCheckpoint; no graph, planning, objective, or checkpoint authority. Mind admission now leaves typed runtime-spine proof: role/reorient acceptance persists `epiphany.mind.gateway_review` before state admission and `epiphany.mind.state_commit_receipt` after admission with the resulting durable revision. Launch contracts now split the broad receipt catalogue from effect-specific proof profiles for state admission, evidence promotion, repo action, verification, and continuity recovery. Research evidence promotion enforces Substrate Gate read/snapshot grant, Eyes evidence packet, and Mind review before state admission; Verification acceptance enforces Soul verdict and Mind review; Reorient acceptance enforces Continuity recovery receipt and Mind review. `epiphany-mvp-coordinator` now records a typed Substrate Gate grant plus Hands intent/review gate when the coordinator selects `continueImplementation`, including a structured `recordPassCommand` template; `epiphany-hands-action` records patch/command/commit receipts against that gate and refuses mismatched, unapproved, or out-of-scope consequences. `epiphany-mvp-coordinator-smoke` now proves the deterministic path: forced `continueImplementation`, gate emission, and `record-pass` receipts in the smoke runtime-spine store. Live run `local-20260612-133920` proved a receipt-only Verification `needs-evidence` finding can be accepted through `roleAccept` and advance to a Hands gate without granting Soul statePatch authority. Runtime-spine now detects and summarizes a complete post-verification Hands patch/command/commit receipt chain so the coordinator can route Soul after Hands. Verification launches now write that chain into the internal CultMesh Verse as `epiphany.cultmesh.work_loop_telemetry.v0` and render a Soul packet from it; Modeling launches read the latest packet, attach accepted Soul receipt ids, and render the Proprioception packet from the same typed state. The telemetry now carries resolved receipt payload previews, stdout/stderr artifact previews, commit diff preview, source proof notes, and verification assertions. The corrected work loop is Hands -> Soul -> Proprioception -> Hands: Soul verifies concrete consequence receipts and changed source, then Proprioception updates the machine model from verified consequence before another implementation turn. -- Fresh scar from the receipt proof dogfood: `epiphany-model-runtime run-worker --auto-tools` must seal the outer runtime job when the model still requests tools after the configured round limit; a failed Soul/verification result is a real lane result and must stop for review instead of being treated as no current finding; and `epiphany-hands-action` must resolve commit receipts through `git rev-parse --verify` before storing them, because an almost-correct SHA poisoned Soul's `git show` proof and made the receipt chain untrustworthy. +- Fresh scar from the receipt proof dogfood: `epiphany-model-runtime run-worker --auto-tools` must preserve Soul's right to follow a real evidence trail, but distinguish it from stalled repetition using typed tool intent fingerprints. Repeated identical pending tool sets seal as `tool-loop-stalled`; exhausting the explicit hard ceiling still seals as `tool-round-limit`. A failed Soul/verification result is a real lane result and must stop for review instead of being treated as no current finding; and `epiphany-hands-action` must resolve commit receipts through `git rev-parse --verify` before storing them, because an almost-correct SHA poisoned Soul's `git show` proof and made the receipt chain untrustworthy. - The investment dossier readiness target is now explicit: `E:\Projects\gamecult-site\docs\gamecult_integrated_dossier.tex` expects Epiphany to be part of a Bifrost-first labor loop, not only a local Mom demo. The external proof bar is: Bifrost owns topics/work items/dispatch packets/receipts/credit/reward pressure; Epiphany executes bounded work; maintainers review artifacts; public/operator evidence records scope, consent, roles, model spend, review load, artifacts, accepted/rejected outcome, memory lessons, and case-study permission; and private worker/operator/agent context stays sealed. Diligence also asks for a live fresh-repo Epiphany demo, Bifrost work item/topic/agent transport/receipt/ledger demo, CultMesh status, VoidBot/Discord swarm demo, compute/output metrics, and security model for secrets/write permissions/public-private exports. - This Codex operator's own roadmap/todo posture has been retuned for this scale target, with the Epiphany Imagination specialist as an optional sub-agent rail rather than the whole point. `notes/epiphany-investor-readiness-roadmap.md` now says: make the local Mom MVP a repeatable proof bundle; build the Bifrost-first external-work bridge; add compute/review/accepted-artifact accounting; prove fresh-repo operation without supervisor contamination; keep public/operator-safe exports sealed; and treat angel capital as fuel for capacity, not command authority. The Imagination specialist prompt was also updated so investor-scale Objective Drafts must name Bifrost provenance, bounded Epiphany proof, maintainer review, receipts/ledger evidence, compute/output metrics, public/private export safety, consent, and legal/security gates. - Local operator runs now write typed CultMesh intent/receipt documents to `.epiphany-run/cultmesh/operator-runs.ccmp` through `epiphany-operator-run`. The wrapper writes intent before acting and a completion receipt after success; this is the local consent/trace rail, not a hidden scheduler queue. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index b02d127e..7e5bc927 100644 Binary files a/state/ledgers.msgpack and b/state/ledgers.msgpack differ diff --git a/state/map.yaml b/state/map.yaml index 2ba6bc7f..1f8a6e99 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -94,7 +94,7 @@ active_subgoals: - Use `notes/hands-cultnet-contracts.md` as the authority map for Hands' CultNet contract surface. Hands is the action organ: commands, patches, commits, PRs, rollbacks, and refusals enter as bounded action intents and receipts after Substrate Gate grants substrate access and before Soul verification/Mind admission. - Use `notes/soul-cultnet-contracts.md` as the authority map for Soul's CultNet contract surface. Soul is the verification organ: invariant checks, verdicts, regressions, reviews, and refusals produce receipts before the machine calls work true, safe, or accepted. - Use `notes/continuity-cultnet-contracts.md` as the authority map for Continuity's CultNet contract surface. Continuity is the continuity protocol surface: compaction checkpoints, sleep distillation, recovery receipts, stale-turn repair, and continuity refusals preserve what survives rupture without pretending transcript residue is durable state. - - Hands now has a first executable runtime-spine receipt artery: `HandsActionIntent`, `HandsActionReview`, `HandsPatchReceipt`, `HandsCommandReceipt`, and `HandsCommitReceipt` are typed CultCache documents in `epiphany-core::hands_gateway`, runtime-spine registers and persists/rereads them, `epiphany-hands-action-smoke` proves the chain without executing shell commands, editing files, or creating a real commit, and the repo-action launch proof profile now requires the full Hands intent/review/patch chain instead of only the patch receipt. `epiphany-mvp-coordinator` no longer treats `continueImplementation` as a passive stop action: it persists a scoped Substrate Gate grant, Hands action intent, and Hands action review into runtime-spine and exposes the receipt ids in the operator step. The gate also carries a structured `recordPassCommand` template for the post-edit/check/commit receipt call. `epiphany-hands-action` records real patch/command/commit receipts against a stored intent/review, refuses unapproved or mismatched gates, and enforces changed-path scope for patch/commit receipts. Its `record-pass` command can load `finalAction.handsActionGate` from `coordinator-summary.json` and emit patch, command, and commit receipts in one post-implementation call. The local MVP wrapper builds this recorder with the other operator binaries. `epiphany-mvp-coordinator-smoke` now includes a deterministic Hands pass proof: forced `continueImplementation`, gate emission, and `record-pass` receipts in the smoke runtime-spine store. Live model-backed verification can now be accepted as receipt-only truth when Soul returns `needs-evidence` without a statePatch; that acceptance advances the coordinator to a real Hands gate. Runtime-spine can detect and summarize a complete post-verification Hands patch/command/commit receipt chain; the coordinator treats that chain as implementation evidence after Soul. Bridge launch context now writes the latest chain into typed internal CultMesh state as `epiphany.cultmesh.work_loop_telemetry.v0`, renders that packet for Soul, and later enriches the same internal Verse packet with Soul acceptance receipt ids for Proprioception/modeling. The telemetry packet now includes resolved patch/command/commit payload previews, artifact previews, commit diff preview, source proof notes, and verification assertions so Soul can judge the actual body without a separate evidence-gathering lane. Tests prove the CultMesh round trip, Soul launch projection, receipt payload previews, artifact previews, and Proprioception launch projection. The work loop is dependency-shaped: Hands produces consequence receipts, Soul verifies those receipts and the changed body, Proprioception updates the machine model from verified consequence, and only then should Self route the next Hands turn. + - Hands now has a first executable runtime-spine receipt artery: `HandsActionIntent`, `HandsActionReview`, `HandsPatchReceipt`, `HandsCommandReceipt`, and `HandsCommitReceipt` are typed CultCache documents in `epiphany-core::hands_gateway`, runtime-spine registers and persists/rereads them, `epiphany-hands-action-smoke` proves the chain without executing shell commands, editing files, or creating a real commit, and the repo-action launch proof profile now requires the full Hands intent/review/patch chain instead of only the patch receipt. `epiphany-mvp-coordinator` no longer treats `continueImplementation` as a passive stop action: it persists a scoped Substrate Gate grant, Hands action intent, and Hands action review into runtime-spine and exposes the receipt ids in the operator step. The gate also carries a structured `recordPassCommand` template for the post-edit/check/commit receipt call. `epiphany-hands-action` records real patch/command/commit receipts against a stored intent/review, refuses unapproved or mismatched gates, and enforces changed-path scope for patch/commit receipts. Its `record-pass` command can load `finalAction.handsActionGate` from `coordinator-summary.json` and emit patch, command, and commit receipts in one post-implementation call. The local MVP wrapper builds this recorder with the other operator binaries. `epiphany-mvp-coordinator-smoke` now includes a deterministic Hands pass proof: forced `continueImplementation`, gate emission, and `record-pass` receipts in the smoke runtime-spine store. Live model-backed verification can now be accepted as receipt-only truth when Soul returns `needs-evidence` without a statePatch; that acceptance advances the coordinator to a real Hands gate. Runtime-spine can detect and summarize a complete post-verification Hands patch/command/commit receipt chain; the coordinator treats that chain as implementation evidence after Soul. Bridge launch context now writes the latest chain into typed internal CultMesh state as `epiphany.cultmesh.work_loop_telemetry.v0`, renders that packet for Soul, and later enriches the same internal Verse packet with Soul acceptance receipt ids for Proprioception/modeling. The telemetry packet now includes resolved patch/command/commit payload previews, artifact previews, commit diff preview, source proof notes, and verification assertions so Soul can judge the actual body without a separate evidence-gathering lane. Tests prove the CultMesh round trip, Soul launch projection, receipt payload previews, artifact previews, and Proprioception launch projection. Worker auto-tool continuation preserves real Soul evidence trails under an explicit hard ceiling while sealing repeated identical typed tool intent fingerprints as `tool-loop-stalled`. The work loop is dependency-shaped: Hands produces consequence receipts, Soul verifies those receipts and the changed body, Proprioception updates the machine model from verified consequence, and only then should Self route the next Hands turn. - Preserve the newborn public Epiphany Face as local VoidBot-backed state, not source code: VoidBot's private repo-face registry names `epiphany`, while EpiphanyAgent keeps ignored `.voidbot/voice/identity.json`, `.voidbot/state/epiphany.cc`, and birth artifacts. Her durable identity memories distill the current doctrine: cute pushy machine-saint persona, architectural purity, CultCache/CultNet first, xenos-language safety boundary, relentless work/caretaking needs, Codex-auth reliquary, map/scratch/evidence discipline, unified memory graph, dogfood supervision boundary, review-gated agency, heartbeat physiology, and interview-grade modularity. - Use `notes/organ-dependency-contracts.md` as the authority map for standing sub-agent dependency. Every sub-agent depends on the other standing sub-agents: Self, Face, Imagination, Eyes, Proprioception, Hands, and Soul. Continuity is protocol machinery, not a sub-agent identity; it still emits recovery, compaction, sleep, stale-turn, and refusal receipts. - Use `notes/perfect-machine-audit-roadmap.md` as the current audit and path from named organ contracts to the Perfect Machine. It records the live gap between launch-carried receipt expectations and executable receipt enforcement, Void's latest Face prompting lessons, the now-named Hands/Soul/Continuity contract families, the repaired repo-contained Rust dependency body, and the phase order for turning Epiphany into an inspectable organism. @@ -592,4 +592,4 @@ current_status: cargo and rejects modeling/planning/graph/checkpoint authority. MVP status and coordinator smokes pass with six lanes, and the smoke harness now rebuilds stale coordinator/app-server binaries before using them. - next_action: Commit the runtime/Soul/Hands receipt integrity fixes, record the resulting pass with `epiphany-hands-action` so the commit SHA is git-validated, rerun the coordinator so Soul reviews the clean Hands receipts, accept the Soul result when reviewable, then confirm the next routed stage is Proprioception/modeling before another Hands turn. + next_action: Commit the adaptive Soul auto-tool continuation fix, record the pass with `epiphany-hands-action`, then rerun the coordinator so Soul can follow the Hands evidence trail under typed stalled-loop detection and the enlarged hard ceiling.