Harden supervised Epiphany dogfood loop
This commit is contained in:
parent
d1660270ba
commit
2646c1c775
20 changed files with 1482 additions and 189 deletions
|
|
@ -32,9 +32,19 @@ struct ArtifactBundle {
|
|||
summary_path: Option<String>,
|
||||
final_status_path: Option<String>,
|
||||
comparison_path: Option<String>,
|
||||
implementation_audit: Option<ImplementationAudit>,
|
||||
modified_millis: Option<u128>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct ImplementationAudit {
|
||||
result_path: String,
|
||||
workspace_changed: bool,
|
||||
tracked_diff_present: bool,
|
||||
changed_files: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct OperatorSnapshot {
|
||||
|
|
@ -72,9 +82,11 @@ fn run_operator_action(
|
|||
| "acceptModeling"
|
||||
| "launchVerification"
|
||||
| "readVerificationResult"
|
||||
| "acceptVerification"
|
||||
| "launchReorient"
|
||||
| "readReorientResult"
|
||||
| "acceptReorient"
|
||||
| "continueImplementation"
|
||||
| "prepareCheckpoint" => run_gui_action_bridge(&repo_root, request, action),
|
||||
_ => Err(format!("unknown operator action: {action}")),
|
||||
}
|
||||
|
|
@ -371,6 +383,7 @@ fn collect_artifact_root(
|
|||
final_status_path: existing_path(&path, "epiphany-final-status.json")
|
||||
.or_else(|| existing_path(&path, "after-status.json")),
|
||||
comparison_path: existing_path(&path, "comparison.md"),
|
||||
implementation_audit: read_implementation_audit(&path),
|
||||
files,
|
||||
modified_millis,
|
||||
});
|
||||
|
|
@ -384,6 +397,34 @@ fn existing_path(root: &Path, name: &str) -> Option<String> {
|
|||
path.exists().then(|| path.display().to_string())
|
||||
}
|
||||
|
||||
fn read_implementation_audit(root: &Path) -> Option<ImplementationAudit> {
|
||||
let result_path = root.join("implementation-result.json");
|
||||
let text = fs::read_to_string(&result_path).ok()?;
|
||||
let value: Value = serde_json::from_str(&text).ok()?;
|
||||
Some(ImplementationAudit {
|
||||
result_path: result_path.display().to_string(),
|
||||
workspace_changed: value
|
||||
.get("workspaceChanged")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false),
|
||||
tracked_diff_present: value
|
||||
.get("trackedDiffPresent")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false),
|
||||
changed_files: value
|
||||
.get("changedFiles")
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(ToString::to_string)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn repo_root() -> Result<PathBuf, String> {
|
||||
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
manifest_dir
|
||||
|
|
|
|||
|
|
@ -23,7 +23,9 @@ const actionButtons: Array<{
|
|||
requiresThread?: boolean;
|
||||
requiresReadyState?: boolean;
|
||||
requiresModelingPatch?: boolean;
|
||||
requiresVerificationResult?: boolean;
|
||||
requiresReorientResult?: boolean;
|
||||
requiresContinueImplementation?: boolean;
|
||||
icon: "file" | "check" | "play" | "eye" | "accept";
|
||||
}> = [
|
||||
{
|
||||
|
|
@ -47,6 +49,16 @@ const actionButtons: Array<{
|
|||
title: "Seed durable Epiphany state for this GUI operator thread",
|
||||
icon: "accept",
|
||||
},
|
||||
{
|
||||
action: "continueImplementation",
|
||||
label: "Continue Implementation",
|
||||
runningLabel: "Implementing",
|
||||
title: "Run a bounded implementation turn when the coordinator has cleared specialist lanes",
|
||||
requiresThread: true,
|
||||
requiresReadyState: true,
|
||||
requiresContinueImplementation: true,
|
||||
icon: "play",
|
||||
},
|
||||
{
|
||||
action: "launchModeling",
|
||||
label: "Launch Modeling",
|
||||
|
|
@ -91,6 +103,16 @@ const actionButtons: Array<{
|
|||
requiresThread: true,
|
||||
icon: "eye",
|
||||
},
|
||||
{
|
||||
action: "acceptVerification",
|
||||
label: "Accept Verification",
|
||||
runningLabel: "Accepting",
|
||||
title: "Accept a reviewed verification finding into Epiphany state",
|
||||
requiresThread: true,
|
||||
requiresReadyState: true,
|
||||
requiresVerificationResult: true,
|
||||
icon: "accept",
|
||||
},
|
||||
{
|
||||
action: "launchReorient",
|
||||
label: "Launch Reorient",
|
||||
|
|
@ -219,12 +241,22 @@ export function App() {
|
|||
const jobs: any[] = Array.isArray(status?.jobs?.jobs) ? status.jobs.jobs : [];
|
||||
const roleResults = status?.roleResults ?? {};
|
||||
const reorientResult = status?.reorientResult ?? {};
|
||||
const latestArtifact = snapshot?.artifacts?.[0];
|
||||
const latestImplementationArtifact = useMemo(
|
||||
() => (snapshot?.artifacts ?? []).find((artifact) => artifact.implementationAudit),
|
||||
[snapshot?.artifacts],
|
||||
);
|
||||
const latestImplementationAudit = latestImplementationArtifact?.implementationAudit;
|
||||
const implementationNoDiffPending =
|
||||
Boolean(latestArtifact?.implementationAudit) && latestArtifact?.implementationAudit?.workspaceChanged === false;
|
||||
const readyState = scene.stateStatus === "ready";
|
||||
const currentThreadId = request.threadId;
|
||||
const modelingFinding = roleResults?.modeling?.finding;
|
||||
const canAcceptModeling =
|
||||
text(roleResults?.modeling?.status).toLowerCase() === "completed" && Boolean(modelingFinding?.statePatch);
|
||||
const canAcceptVerification = text(roleResults?.verification?.status).toLowerCase() === "completed";
|
||||
const canAcceptReorient = text(reorientResult?.status).toLowerCase() === "completed";
|
||||
const canContinueImplementation = text(coordinator.action).toLowerCase() === "continueimplementation";
|
||||
|
||||
return (
|
||||
<main className="shell">
|
||||
|
|
@ -263,17 +295,34 @@ export function App() {
|
|||
const needsThread = button.requiresThread && !currentThreadId;
|
||||
const needsState = button.requiresReadyState && !readyState;
|
||||
const needsModeling = button.requiresModelingPatch && !canAcceptModeling;
|
||||
const needsVerification = button.requiresVerificationResult && !canAcceptVerification;
|
||||
const needsReorient = button.requiresReorientResult && !canAcceptReorient;
|
||||
const disabled = runningAction !== null || needsThread || needsState || needsModeling || needsReorient;
|
||||
const needsImplementation = button.requiresContinueImplementation && !canContinueImplementation;
|
||||
const needsNoDiffReview = button.requiresContinueImplementation && implementationNoDiffPending;
|
||||
const disabled =
|
||||
runningAction !== null ||
|
||||
needsThread ||
|
||||
needsState ||
|
||||
needsModeling ||
|
||||
needsVerification ||
|
||||
needsReorient ||
|
||||
needsImplementation ||
|
||||
needsNoDiffReview;
|
||||
const title = needsThread
|
||||
? "Prepare a checkpoint or enter a persisted thread id first"
|
||||
: needsState
|
||||
? "Prepare Epiphany state before launching this lane"
|
||||
: needsModeling
|
||||
? "Read a completed modeling result with a state patch before accepting it"
|
||||
: needsReorient
|
||||
? "Read a completed reorient result before accepting it"
|
||||
: button.title;
|
||||
: needsVerification
|
||||
? "Read a completed verification result before accepting it"
|
||||
: needsReorient
|
||||
? "Read a completed reorient result before accepting it"
|
||||
: needsImplementation
|
||||
? "Run the coordinator and clear review gates before continuing implementation"
|
||||
: needsNoDiffReview
|
||||
? "Review the latest no-diff implementation artifact or run another lane before retrying"
|
||||
: button.title;
|
||||
return (
|
||||
<button
|
||||
className="secondaryButton"
|
||||
|
|
@ -301,6 +350,23 @@ export function App() {
|
|||
</section>
|
||||
)}
|
||||
|
||||
{latestImplementationAudit && (
|
||||
<section className={`notice ${latestImplementationAudit.workspaceChanged ? "okNotice" : "warnNotice"}`}>
|
||||
{latestImplementationAudit.workspaceChanged ? (
|
||||
<CheckCircle2 size={18} aria-hidden="true" />
|
||||
) : (
|
||||
<AlertTriangle size={18} aria-hidden="true" />
|
||||
)}
|
||||
<span>
|
||||
<strong>Latest implementation audit:</strong>{" "}
|
||||
{latestImplementationAudit.workspaceChanged
|
||||
? `${latestImplementationAudit.changedFiles.length} changed file(s) need review.`
|
||||
: "the worker completed with no workspace diff; review the artifact before rerunning."}{" "}
|
||||
<code>{latestImplementationArtifact?.path}</code>
|
||||
</span>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="statusGrid" aria-label="Coordinator summary">
|
||||
<Panel title="Recommendation" icon={<ClipboardCheck size={18} />}>
|
||||
<div className={`actionBanner ${statusClass(coordinator.action ?? crrc.action)}`}>
|
||||
|
|
@ -374,12 +440,14 @@ export function App() {
|
|||
<div className="artifactTable" role="table" aria-label="Artifact bundles">
|
||||
<div className="artifactHeader" role="row">
|
||||
<span>Name</span>
|
||||
<span>Outcome</span>
|
||||
<span>Files</span>
|
||||
<span>Path</span>
|
||||
</div>
|
||||
{(snapshot?.artifacts ?? []).map((artifact: ArtifactBundle) => (
|
||||
<div className="artifactRow" role="row" key={artifact.path}>
|
||||
<strong>{artifact.name}</strong>
|
||||
<span><ArtifactOutcome artifact={artifact} /></span>
|
||||
<span>{artifact.files.length}</span>
|
||||
<code title={artifact.path}>{artifact.path}</code>
|
||||
</div>
|
||||
|
|
@ -445,6 +513,16 @@ function Finding({ title, result, findingKey = "finding" }: { title: string; res
|
|||
);
|
||||
}
|
||||
|
||||
function ArtifactOutcome({ artifact }: { artifact: ArtifactBundle }) {
|
||||
const audit = artifact.implementationAudit;
|
||||
if (!audit) return <span className="artifactOutcome muted">none</span>;
|
||||
return (
|
||||
<Pill tone={audit.workspaceChanged ? "ok" : "warn"}>
|
||||
{audit.workspaceChanged ? "Diff" : "No Diff"}
|
||||
</Pill>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyState({ label }: { label: string }) {
|
||||
return <p className="emptyState">{label}</p>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -172,6 +172,24 @@ input {
|
|||
background: #fff7f4;
|
||||
}
|
||||
|
||||
.warnNotice {
|
||||
border-color: #dfc36f;
|
||||
color: #76520b;
|
||||
background: #fff8df;
|
||||
}
|
||||
|
||||
.okNotice {
|
||||
border-color: #9ac8aa;
|
||||
color: #1d5d39;
|
||||
background: #edf8f0;
|
||||
}
|
||||
|
||||
.notice code {
|
||||
display: inline;
|
||||
max-width: min(620px, 70vw);
|
||||
vertical-align: bottom;
|
||||
}
|
||||
|
||||
.statusGrid {
|
||||
grid-template-columns: minmax(0, 1.35fr) minmax(320px, 0.65fr);
|
||||
margin-bottom: 22px;
|
||||
|
|
@ -352,7 +370,7 @@ dd {
|
|||
|
||||
.artifactHeader,
|
||||
.artifactRow {
|
||||
grid-template-columns: minmax(180px, 0.6fr) 72px minmax(220px, 1fr);
|
||||
grid-template-columns: minmax(180px, 0.6fr) 96px 72px minmax(220px, 1fr);
|
||||
min-height: 42px;
|
||||
padding: 0 12px;
|
||||
}
|
||||
|
|
@ -377,6 +395,11 @@ code {
|
|||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.artifactOutcome.muted {
|
||||
color: #77817a;
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.emptyState {
|
||||
border: 1px dashed #cbd3c8;
|
||||
border-radius: 8px;
|
||||
|
|
|
|||
|
|
@ -9,11 +9,13 @@ export type OperatorAction =
|
|||
| "statusSnapshot"
|
||||
| "coordinatorPlan"
|
||||
| "prepareCheckpoint"
|
||||
| "continueImplementation"
|
||||
| "launchModeling"
|
||||
| "readModelingResult"
|
||||
| "acceptModeling"
|
||||
| "launchVerification"
|
||||
| "readVerificationResult"
|
||||
| "acceptVerification"
|
||||
| "launchReorient"
|
||||
| "readReorientResult"
|
||||
| "acceptReorient";
|
||||
|
|
@ -32,6 +34,12 @@ export interface ArtifactBundle {
|
|||
summaryPath?: string;
|
||||
finalStatusPath?: string;
|
||||
comparisonPath?: string;
|
||||
implementationAudit?: {
|
||||
resultPath: string;
|
||||
workspaceChanged: boolean;
|
||||
trackedDiffPresent: boolean;
|
||||
changedFiles: string[];
|
||||
};
|
||||
modifiedMillis?: number;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -20,10 +20,8 @@ fn finalize_active_segment(
|
|||
epiphany_state: &mut Option<EpiphanyThreadState>,
|
||||
pending_rollback_turns: &mut usize,
|
||||
) {
|
||||
if *pending_rollback_turns > 0 {
|
||||
if active_segment.counts_as_user_turn {
|
||||
*pending_rollback_turns -= 1;
|
||||
}
|
||||
if *pending_rollback_turns > 0 && active_segment.counts_as_user_turn {
|
||||
*pending_rollback_turns -= 1;
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -35,6 +33,12 @@ fn finalize_active_segment(
|
|||
}
|
||||
}
|
||||
|
||||
fn is_out_of_band_epiphany_segment(active_segment: &ActiveEpiphanyReplaySegment) -> bool {
|
||||
active_segment.turn_id.is_none()
|
||||
&& !active_segment.counts_as_user_turn
|
||||
&& active_segment.epiphany_state.is_some()
|
||||
}
|
||||
|
||||
pub fn latest_epiphany_state_from_rollout_items<F>(
|
||||
rollout_items: &[RolloutItem],
|
||||
is_user_turn_boundary: F,
|
||||
|
|
@ -47,6 +51,21 @@ where
|
|||
let mut active_segment: Option<ActiveEpiphanyReplaySegment> = None;
|
||||
|
||||
for item in rollout_items.iter().rev() {
|
||||
if active_segment
|
||||
.as_ref()
|
||||
.is_some_and(is_out_of_band_epiphany_segment)
|
||||
&& let Some(active_segment) = active_segment.take()
|
||||
{
|
||||
finalize_active_segment(
|
||||
active_segment,
|
||||
&mut epiphany_state,
|
||||
&mut pending_rollback_turns,
|
||||
);
|
||||
}
|
||||
if epiphany_state.is_some() {
|
||||
break;
|
||||
}
|
||||
|
||||
match item {
|
||||
RolloutItem::EventMsg(EventMsg::ThreadRolledBack(rollback)) => {
|
||||
pending_rollback_turns = pending_rollback_turns
|
||||
|
|
@ -346,4 +365,44 @@ mod tests {
|
|||
Some(state)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn latest_epiphany_state_from_rollout_items_accepts_out_of_band_snapshot_after_turn() {
|
||||
let turn_state = sample_epiphany_state("turn-before-control-plane-update");
|
||||
let control_plane_state = sample_epiphany_state("control-plane-update");
|
||||
let rollout_items = vec![
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
|
||||
turn_id: "turn-before-control-plane-update".to_string(),
|
||||
started_at: None,
|
||||
model_context_window: None,
|
||||
collaboration_mode_kind: Default::default(),
|
||||
})),
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
|
||||
message: "before control-plane update".to_string(),
|
||||
images: None,
|
||||
text_elements: Vec::new(),
|
||||
local_images: Vec::new(),
|
||||
})),
|
||||
RolloutItem::EpiphanyState(EpiphanyStateItem {
|
||||
turn_id: Some("turn-before-control-plane-update".to_string()),
|
||||
state: turn_state,
|
||||
}),
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent {
|
||||
turn_id: "turn-before-control-plane-update".to_string(),
|
||||
last_agent_message: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
time_to_first_token_ms: None,
|
||||
})),
|
||||
RolloutItem::EpiphanyState(EpiphanyStateItem {
|
||||
turn_id: None,
|
||||
state: control_plane_state.clone(),
|
||||
}),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
latest_epiphany_state_from_rollout_items(&rollout_items, simple_is_user_turn_boundary),
|
||||
Some(control_plane_state)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,6 +42,9 @@ Do not trust this file for the exact live HEAD. Always check git.
|
|||
- 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.
|
||||
- Latest Aetheria supervised dogfood thread: `019ddc52-4ee8-7203-b6c0-106a9c270067` with codex-home `.epiphany-dogfood/aetheria-supervised/codex-home`. CRRC compact/reorient/reorientAccept reached Epiphany state revision 16 after rollout replay fixes, and a fresh coordinator resume now clears to `continueImplementation`.
|
||||
- The implementation lane is the current MVP blocker. Four `continueImplementation` turns completed without a tracked Aetheria diff; the latest audited artifact is `.epiphany-dogfood/aetheria-supervised/gui-actions/continueImplementation-1777527640605829200-12724`, with `implementation-result.json` showing `workspaceChanged: false` and telemetry showing only `Get-Content` commands with no write verbs.
|
||||
- The GUI now parses `implementation-result.json` into artifact metadata, surfaces the latest implementation diff/no-diff outcome, and pauses immediate `Continue Implementation` repeats when the newest artifact is a no-diff implementation audit. Future `continueImplementation` action bundles also write `implementation-audit.md`.
|
||||
- The repo is an Epiphany fork of Codex, not a Codex preset.
|
||||
- `vendor/codex` is tracked directly, not a submodule.
|
||||
- `epiphany-core` owns the heavy Epiphany organs where practical.
|
||||
|
|
@ -351,19 +354,22 @@ bounded browser-fallback controls. A live bridge probe also proved
|
|||
`prepareCheckpoint` creates a resumable thread and a later process can
|
||||
`readModelingResult` from it.
|
||||
|
||||
The next real move is not more direct Aetheria implementation. The uncommitted
|
||||
supervisor-created fog-compute slice was discarded; the remaining Aetheria
|
||||
branch work is supervisor-seeded and must not be presented as clean dogfood.
|
||||
Run the next Aetheria step through Epiphany's GUI/coordinator/fixed lanes and
|
||||
produce artifacts that show who did what. Read only operator-safe projections;
|
||||
do not open raw worker transcripts, direct worker messages, or `rawResult`
|
||||
payloads unless the user explicitly asks for forensic debugging. Use generated
|
||||
function/API telemetry for call-shape visibility without sungazing. CRRC is not
|
||||
a specialist-agent persona; the reorient-worker it may launch is the
|
||||
specialist. Do not turn the coordinator into a broad hidden dispatcher,
|
||||
arbitrary marketplace, alternate job backend, automatic semantic acceptance
|
||||
path, target-repo implementation worker, direct-thought feed, or
|
||||
GUI-as-source-of-truth.
|
||||
The next real move is not more direct Aetheria implementation. The clean
|
||||
supervised lane now reaches implementation, but the implementation agent is
|
||||
reading and stopping without leaving a diff. The GUI surfaces that and prevents
|
||||
immediate repeat-mashing, but the coordinator still does not know about the
|
||||
implementation failure. Treat this as an MVP blocker: either make no-diff
|
||||
implementation a coordinator-visible review stop or redirect it into a bounded
|
||||
modeling/reorientation repair path, then rerun through the GUI/coordinator/fixed
|
||||
lanes and produce artifacts that show who did what. Read only operator-safe
|
||||
projections; do not open raw worker transcripts, direct
|
||||
worker messages, or `rawResult` payloads unless the user explicitly asks for
|
||||
forensic debugging. Use generated function/API telemetry for call-shape
|
||||
visibility without sungazing. CRRC is not a specialist-agent persona; the
|
||||
reorient-worker it may launch is the specialist. Do not turn the coordinator
|
||||
into a broad hidden dispatcher, arbitrary marketplace, alternate job backend,
|
||||
automatic semantic acceptance path, target-repo implementation worker,
|
||||
direct-thought feed, or GUI-as-source-of-truth.
|
||||
|
||||
Live `thread/epiphany/scene`, `thread/epiphany/jobs`, `thread/epiphany/roles`,
|
||||
`thread/epiphany/freshness`, `thread/epiphany/context`,
|
||||
|
|
|
|||
|
|
@ -37,3 +37,7 @@
|
|||
{"ts": "2026-04-30T02:24:44+00:00", "type": "implementation", "status": "ok", "note": "Dogfood supervision now has a projection boundary: operator/status/coordinator/live-specialist/dogfood tools sanitize direct worker payloads by default, seal raw transcripts/stderr as forensic artifacts, and coordinator smoke asserts rawResult is sealed in operator-facing summaries. Durable instructions now forbid supervisor exposure to raw worker thoughts during normal dogfood."}
|
||||
{"ts": "2026-04-30T02:39:43+00:00", "type": "implementation", "status": "ok", "note": "Function/API telemetry now gives dogfood supervision a non-thought instrument panel: status, coordinator, GUI action, dogfood, and live-specialist tools emit agent-function-telemetry.json from sealed app-server transcripts with method counts, request shape, job/status/path metadata, and visible tool names while sealing text, raw results, turn items, and direct worker messages."}
|
||||
{"ts": "2026-04-30T03:18:48+00:00", "type": "implementation", "status": "ok", "note": "Aetheria supervised dogfood exposed a coordinator policy bug: after the modeling/checkpoint worker was interrupted and roleResult became backendUnavailable, coordinator skipped to verification. Fixed map_epiphany_coordinator so backendUnavailable is treated as a relaunchable role status for modeling and verification; focused Rust test and live coordinator plan now keep verification behind modeling."}
|
||||
{"ts": "2026-04-30T05:45:20+00:00", "type": "verification", "status": "ok", "note": "Aetheria supervised dogfood tested CRRC through the GUI/coordinator lane: modeling and verification findings were accepted, CRRC compact/reorient/reorientAccept reached state revision 16, rollout replay now preserves out-of-band Epiphany snapshots on fresh resume, and the coordinator clears to continueImplementation after accepted resume reorientation despite stale cumulative pressure."}
|
||||
{"ts": "2026-04-30T05:45:31+00:00", "type": "verification", "status": "blocked", "note": "Aetheria supervised dogfood exposed the implementation-lane MVP blocker: four continueImplementation turns completed without any tracked Aetheria workspace diff. The latest audited run at .epiphany-dogfood/aetheria-supervised/gui-actions/continueImplementation-1777527640605829200-12724 records workspaceChanged=false and command telemetry shows only Get-Content reads, no write verbs."}
|
||||
{"ts": "2026-04-30T05:45:38+00:00", "type": "implementation", "status": "ok", "note": "The GUI action bridge now writes implementation-result.json for continueImplementation turns, emits implementation-audit.md on future runs, and the Tauri/React operator console parses implementation-result.json into artifact metadata so the latest no-diff or diff outcome is visible without opening terminal artifacts."}
|
||||
{"ts": "2026-04-30T05:47:56+00:00", "type": "implementation", "status": "ok", "note": "The GUI now treats a newest no-diff implementation artifact as a soft operator gate: Continue Implementation is paused until the operator reviews or runs another lane, preventing immediate repeated no-diff pseudo-progress from the console."}
|
||||
|
|
|
|||
|
|
@ -64,6 +64,7 @@ active_subgoals:
|
|||
- Quarantine the Aetheria dogfood contamination: future target-repo work must be driven through Epiphany's GUI/coordinator/fixed lanes with auditable artifacts, not direct supervisor implementation.
|
||||
- Keep the supervisor out of Epiphany worker thought streams: dogfood artifacts should be operator-safe by default, with direct transcripts and raw result payloads sealed.
|
||||
- Use `tools/epiphany_agent_telemetry.py` and generated `agent-function-telemetry.json` files to inspect behavior shape without opening sealed transcripts.
|
||||
- Treat repeated no-diff implementation turns as an MVP blocker, not success. A bounded implementation pass must leave a reviewable workspace diff or an explicit reviewable failure artifact before dogfood can be called healthy.
|
||||
|
||||
accepted_design:
|
||||
- Epiphany is a fork-level modeling architecture, not merely a Codex collaboration mode.
|
||||
|
|
@ -179,5 +180,5 @@ rejected_paths:
|
|||
reason: persistent state that accumulates every local truth becomes memory cruft and weakens rehydration
|
||||
|
||||
current_status:
|
||||
summary: Phase 1 durable state, Phase 2 prompt integration, Phase 3 typed read, Phase 4 retrieval/indexing, Phase 5 update/distill/propose/promote/read/notification, and Phase 6 read-only scene, jobs, roles, freshness, targeted context, graph traversal, pressure, reorient, CRRC, coordinator, reorient launch/result/accept, explicit modeling/checkpoint and verification/review role launch/result templates, review-gated modeling role acceptance, MVP status, dogfood runner, coordinator runner, live specialist runner, limited safe-boundary CRRC automation, pre-compaction checkpoint intervention, the first Tauri/React GUI operator shell, and the distilled shared plus config-backed specialist prompt doctrine are landed. Aetheria dogfood exposed a supervision-boundary failure: the supervising Codex session directly implemented and committed target-repo slices instead of driving Epiphany lanes, so those commits are supervisor-seeded work, not clean dogfood evidence. The quarantine is now stronger: operator tools sanitize direct worker payloads by default, mark raw transcripts/stderr as sealed forensic artifacts, and generate function/API telemetry as a safe non-thought instrument panel. Native CRRC can steer active loaded Epiphany turns once at `shouldPrepareCompaction`; turn-complete automation can still compact or launch the fixed reorient-worker when the coordinator says it can auto-run. The GUI remains an operator surface over typed state, not a source of truth.
|
||||
next_action: Rerun Aetheria dogfood through Epiphany's GUI/coordinator/fixed role lanes using only operator-safe projections; do not inspect raw worker transcripts or `rawResult` payloads unless the user explicitly requests forensic debugging.
|
||||
summary: Phase 1 durable state through the Phase 6 GUI/coordinator/specialist/CRRC MVP surfaces are landed. Aetheria dogfood first exposed a supervisor contamination scar, so the quarantine now keeps the supervisor on operator-safe projections and sealed transcripts. The latest clean supervised pass proved the CRRC compact/reorient/reorientAccept lane can reach state revision 16 and clear to `continueImplementation`, but it also exposed the current MVP blocker: repeated implementation turns complete with no tracked Aetheria diff and telemetry shows read-only source inspection. The GUI now surfaces implementation diff/no-diff audit artifacts and pauses immediate repeat when the newest artifact is no-diff; the next fix is making that outcome coordinator/state-visible or redirecting it through a repair lane.
|
||||
next_action: Fix the implementation-lane no-diff loop at the coordinator/state level or redirect it into a bounded modeling/reorientation repair path. The GUI now exposes and soft-gates no-diff artifacts, but the harness-native coordinator still clears to `continueImplementation` after the lanes are clean. Keep supervision through operator-safe projections; do not inspect raw worker transcripts or `rawResult` payloads unless the user explicitly requests forensic debugging.
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ from datetime import datetime
|
|||
from datetime import timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
|
||||
|
|
@ -140,6 +141,52 @@ def collect_strings(value: Any, key_names: set[str]) -> list[str]:
|
|||
return found
|
||||
|
||||
|
||||
def summarize_command_text(command: str) -> dict[str, Any]:
|
||||
compact = " ".join(line.strip() for line in command.splitlines() if line.strip())
|
||||
verbs = sorted(
|
||||
{
|
||||
match.group(0)
|
||||
for match in re.finditer(
|
||||
r"\b(?:rg|git|Get-Content|Get-ChildItem|Select-String|Test-Path|New-Item|Set-Content|"
|
||||
r"python|cargo|dotnet|npm|node|apply_patch)\b",
|
||||
command,
|
||||
flags=re.IGNORECASE,
|
||||
)
|
||||
},
|
||||
key=str.lower,
|
||||
)
|
||||
return {
|
||||
"chars": len(command),
|
||||
"lines": len(command.splitlines()) or 1,
|
||||
"preview": compact[:240],
|
||||
"truncated": len(compact) > 240,
|
||||
"verbs": verbs,
|
||||
"hasWriteVerb": any(
|
||||
verb.lower() in {"new-item", "set-content", "apply_patch"}
|
||||
for verb in verbs
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def collect_command_telemetry(value: Any) -> list[dict[str, Any]]:
|
||||
found: list[dict[str, Any]] = []
|
||||
if isinstance(value, dict):
|
||||
if value.get("type") == "commandExecution" and isinstance(value.get("command"), str):
|
||||
command_info = summarize_command_text(value["command"])
|
||||
command_info["cwd"] = value.get("cwd")
|
||||
command_info["status"] = value.get("status")
|
||||
command_info["exitCode"] = value.get("exitCode")
|
||||
command_info["durationMs"] = value.get("durationMs")
|
||||
found.append(command_info)
|
||||
for item in value.values():
|
||||
if isinstance(item, (dict, list)):
|
||||
found.extend(collect_command_telemetry(item))
|
||||
elif isinstance(value, list):
|
||||
for item in value:
|
||||
found.extend(collect_command_telemetry(item))
|
||||
return found
|
||||
|
||||
|
||||
def telemetry_event(index: int, record: dict[str, Any]) -> dict[str, Any]:
|
||||
direction = "unknown"
|
||||
payload: Any = record
|
||||
|
|
@ -166,6 +213,11 @@ def telemetry_event(index: int, record: dict[str, Any]) -> dict[str, Any]:
|
|||
if "result" in payload:
|
||||
event["result"] = summarize_value(payload["result"], key="responseResult")
|
||||
|
||||
command_telemetry = collect_command_telemetry(payload)
|
||||
if command_telemetry:
|
||||
event["commandTelemetry"] = command_telemetry[:16]
|
||||
event["commandTelemetryCount"] = len(command_telemetry)
|
||||
|
||||
names = sorted(set(collect_strings(payload, {"toolName", "tool", "functionName", "name"})))
|
||||
if names:
|
||||
event["functionNames"] = names[:16]
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ from datetime import datetime
|
|||
from datetime import timezone
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
|
@ -21,6 +22,255 @@ from epiphany_phase6_reorient_launch_smoke import BINDING_ID as REORIENT_BINDING
|
|||
|
||||
DEFAULT_CODEX_HOME = ROOT / ".epiphany-gui" / "codex-home"
|
||||
DEFAULT_ARTIFACT_ROOT = ROOT / ".epiphany-gui" / "actions"
|
||||
TERMINAL_ROLE_STATUSES = {"completed", "failed", "cancelled"}
|
||||
TERMINAL_REORIENT_STATUSES = {"completed", "failed", "cancelled"}
|
||||
|
||||
|
||||
def run_git(cwd: Path, *args: str) -> dict[str, Any]:
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
["git", *args],
|
||||
cwd=cwd,
|
||||
capture_output=True,
|
||||
check=False,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
)
|
||||
except OSError as error:
|
||||
return {"ok": False, "error": str(error), "args": list(args)}
|
||||
return {
|
||||
"ok": completed.returncode == 0,
|
||||
"returncode": completed.returncode,
|
||||
"args": list(args),
|
||||
"stdout": completed.stdout.strip(),
|
||||
"stderr": completed.stderr.strip(),
|
||||
}
|
||||
|
||||
|
||||
def git_snapshot(cwd: Path) -> dict[str, Any]:
|
||||
return {
|
||||
"head": run_git(cwd, "rev-parse", "--short", "HEAD"),
|
||||
"branch": run_git(cwd, "branch", "--show-current"),
|
||||
"status": run_git(cwd, "status", "--short", "--branch"),
|
||||
"changedFiles": run_git(cwd, "diff", "--name-only"),
|
||||
"diffStat": run_git(cwd, "diff", "--stat"),
|
||||
}
|
||||
|
||||
|
||||
def git_change_summary(before: dict[str, Any], after: dict[str, Any]) -> dict[str, Any]:
|
||||
before_status = set(str(nested_get(before, "status", "stdout") or "").splitlines())
|
||||
after_status = set(str(nested_get(after, "status", "stdout") or "").splitlines())
|
||||
added_status = sorted(after_status - before_status)
|
||||
removed_status = sorted(before_status - after_status)
|
||||
changed_files = str(nested_get(after, "changedFiles", "stdout") or "").strip()
|
||||
diff_stat = str(nested_get(after, "diffStat", "stdout") or "").strip()
|
||||
return {
|
||||
"workspaceChanged": bool(added_status or removed_status or changed_files or diff_stat),
|
||||
"trackedDiffPresent": bool(changed_files or diff_stat),
|
||||
"changedFiles": changed_files.splitlines() if changed_files else [],
|
||||
"statusAdded": added_status,
|
||||
"statusRemoved": removed_status,
|
||||
"diffStat": diff_stat,
|
||||
}
|
||||
|
||||
|
||||
def render_implementation_audit(result: dict[str, Any]) -> str:
|
||||
changed_files = result.get("changedFiles")
|
||||
if not isinstance(changed_files, list):
|
||||
changed_files = []
|
||||
status_added = result.get("statusAdded")
|
||||
if not isinstance(status_added, list):
|
||||
status_added = []
|
||||
status_removed = result.get("statusRemoved")
|
||||
if not isinstance(status_removed, list):
|
||||
status_removed = []
|
||||
|
||||
outcome = (
|
||||
"reviewable workspace diff"
|
||||
if result.get("workspaceChanged")
|
||||
else "no workspace diff"
|
||||
)
|
||||
next_action = (
|
||||
"Review the changed files before accepting this implementation slice."
|
||||
if result.get("workspaceChanged")
|
||||
else "Stop and review this as an implementation-lane failure before rerunning; the worker completed without changing the target workspace."
|
||||
)
|
||||
return "\n".join(
|
||||
[
|
||||
"# Implementation Audit",
|
||||
"",
|
||||
f"Outcome: {outcome}",
|
||||
f"Tracked diff present: {bool(result.get('trackedDiffPresent'))}",
|
||||
"",
|
||||
"Changed files:",
|
||||
*(f"- {path}" for path in changed_files),
|
||||
*([] if changed_files else ["- none"]),
|
||||
"",
|
||||
"Git status delta:",
|
||||
*(f"- added: {line}" for line in status_added),
|
||||
*(f"- removed: {line}" for line in status_removed),
|
||||
*([] if status_added or status_removed else ["- none"]),
|
||||
"",
|
||||
f"Next action: {next_action}",
|
||||
"",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def nested_get(value: dict[str, Any], *keys: str) -> Any:
|
||||
current: Any = value
|
||||
for key in keys:
|
||||
if not isinstance(current, dict):
|
||||
return None
|
||||
current = current.get(key)
|
||||
return current
|
||||
|
||||
|
||||
def first_present(value: dict[str, Any], *paths: tuple[str, ...]) -> Any:
|
||||
for path in paths:
|
||||
item = nested_get(value, *path)
|
||||
if item not in (None, "", []):
|
||||
return item
|
||||
return None
|
||||
|
||||
|
||||
def summarized_recent_evidence(state: dict[str, Any], limit: int = 8) -> list[str]:
|
||||
recent = state.get("recent_evidence")
|
||||
if not isinstance(recent, list):
|
||||
return []
|
||||
lines: list[str] = []
|
||||
for item in recent[:limit]:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
summary = item.get("summary")
|
||||
if not isinstance(summary, str) or not summary.strip():
|
||||
continue
|
||||
evidence_id = item.get("id", "unknown")
|
||||
kind = item.get("kind", "unknown")
|
||||
status = item.get("status", "unknown")
|
||||
lines.append(f"- {evidence_id} [{kind}/{status}]: {summary}")
|
||||
return lines
|
||||
|
||||
|
||||
def build_implementation_prompt(status: dict[str, Any]) -> str:
|
||||
operator_status = sanitize_for_operator(status)
|
||||
state = first_present(
|
||||
operator_status,
|
||||
("read", "thread", "epiphanyState"),
|
||||
("scene", "scene", "epiphanyState"),
|
||||
)
|
||||
if not isinstance(state, dict):
|
||||
state = {}
|
||||
coordinator = operator_status.get("coordinator")
|
||||
if not isinstance(coordinator, dict):
|
||||
coordinator = {}
|
||||
crrc = nested_get(operator_status, "crrc", "decision")
|
||||
if not isinstance(crrc, dict):
|
||||
crrc = {}
|
||||
|
||||
checkpoint = first_present(
|
||||
state,
|
||||
("graph_checkpoint",),
|
||||
("graphCheckpoint",),
|
||||
)
|
||||
if not isinstance(checkpoint, dict):
|
||||
checkpoint = {}
|
||||
frontier = first_present(state, ("graph_frontier",), ("graphFrontier",))
|
||||
if not isinstance(frontier, dict):
|
||||
frontier = {}
|
||||
scratch = state.get("scratch")
|
||||
if not isinstance(scratch, dict):
|
||||
scratch = {}
|
||||
|
||||
evidence_lines = summarized_recent_evidence(state)
|
||||
if not evidence_lines:
|
||||
evidence_lines = ["- none recorded"]
|
||||
|
||||
active_node_ids = frontier.get("active_node_ids") or frontier.get("activeNodeIds") or []
|
||||
if isinstance(active_node_ids, list):
|
||||
active_node_text = ", ".join(str(item) for item in active_node_ids)
|
||||
else:
|
||||
active_node_text = str(active_node_ids or "none")
|
||||
|
||||
return f"""You are the Epiphany implementation agent for this repository.
|
||||
|
||||
Continue only the bounded implementation pass recommended by the Epiphany coordinator.
|
||||
|
||||
Coordinator:
|
||||
- action: {coordinator.get("action")}
|
||||
- target role: {coordinator.get("targetRole")}
|
||||
- reason: {coordinator.get("reason")}
|
||||
|
||||
Checkpoint:
|
||||
- id: {checkpoint.get("checkpoint_id") or checkpoint.get("checkpointId")}
|
||||
- summary: {checkpoint.get("summary")}
|
||||
- frontier: {active_node_text}
|
||||
|
||||
Continuity:
|
||||
- next action: {crrc.get("nextAction") or nested_get(operator_status, "reorient", "decision", "nextAction")}
|
||||
- scratch: {scratch.get("summary")}
|
||||
|
||||
Accepted evidence:
|
||||
{chr(10).join(evidence_lines)}
|
||||
|
||||
Implementation rules:
|
||||
- Do not read sealed transcript artifacts or raw specialist result payloads.
|
||||
- Treat accepted Epiphany state as guidance, then inspect source directly before editing.
|
||||
- Make a bounded first pass: design or implement a parallel compute-backed gravity height producer that preserves the current `_NebulaSurfaceHeight`, `_GridTransform`, and Slime `Heightmap` contracts before changing shader consumers.
|
||||
- This is an implementation turn, not a planning turn. Leave a concrete source diff unless direct source evidence proves the bounded pass is impossible.
|
||||
- If there is no implementation diff yet, prefer a small reversible compatibility scaffold over another explanation. A valid first diff may be a source-local contract/scaffold for a compute-backed gravity height producer that runs beside the camera path and does not rewire consumers yet.
|
||||
- A previous supervised implementation attempt already performed source-only inspection and left no diff. Do not repeat that pattern. Reuse the accepted checkpoint and inspect only what you need to place the smallest safe scaffold.
|
||||
- A good minimal patch shape is a disabled/parallel gravity heightfield compatibility producer or contract in the rendering layer, plus any tiny supporting compute-shader stub needed to express the intended data path. Preserve legacy texture names and do not rewire consumers in this pass.
|
||||
- Before stopping, check `git status --short`. If it still shows no source diff, continue implementing unless you have found a specific source contradiction or missing dependency that makes even the compatibility scaffold unsafe.
|
||||
- Do not attempt the full fog/froxel migration in this pass unless the compatibility producer and contract evidence are already in place.
|
||||
- Keep the change reviewable. Update or add source-local notes/tests if the repo has an established place for them.
|
||||
- If the source contradicts the checkpoint, stop and explain the contradiction instead of tower-building.
|
||||
"""
|
||||
|
||||
|
||||
def wait_for_role_result(
|
||||
client: AppServerClient,
|
||||
*,
|
||||
thread_id: str,
|
||||
role_id: str,
|
||||
timeout_seconds: int,
|
||||
poll_seconds: float,
|
||||
) -> dict[str, Any]:
|
||||
deadline = time.time() + timeout_seconds
|
||||
latest: dict[str, Any] | None = None
|
||||
while time.time() < deadline:
|
||||
latest = client.send(
|
||||
"thread/epiphany/roleResult",
|
||||
{"threadId": thread_id, "roleId": role_id},
|
||||
)
|
||||
assert latest is not None
|
||||
if latest.get("status") in TERMINAL_ROLE_STATUSES:
|
||||
return latest
|
||||
time.sleep(poll_seconds)
|
||||
assert latest is not None
|
||||
return latest
|
||||
|
||||
|
||||
def wait_for_reorient_result(
|
||||
client: AppServerClient,
|
||||
*,
|
||||
thread_id: str,
|
||||
timeout_seconds: int,
|
||||
poll_seconds: float,
|
||||
) -> dict[str, Any]:
|
||||
deadline = time.time() + timeout_seconds
|
||||
latest: dict[str, Any] | None = None
|
||||
while time.time() < deadline:
|
||||
latest = client.send(
|
||||
"thread/epiphany/reorientResult",
|
||||
{"threadId": thread_id, "bindingId": REORIENT_BINDING_ID},
|
||||
)
|
||||
assert latest is not None
|
||||
if latest.get("status") in TERMINAL_REORIENT_STATUSES:
|
||||
return latest
|
||||
time.sleep(poll_seconds)
|
||||
assert latest is not None
|
||||
return latest
|
||||
|
||||
|
||||
def checkpoint_patch(cwd: Path) -> dict[str, Any]:
|
||||
|
|
@ -246,6 +496,7 @@ def run_action(args: argparse.Namespace) -> dict[str, Any]:
|
|||
)
|
||||
summary = "Prepared durable Epiphany checkpoint."
|
||||
else:
|
||||
client.send("thread/resume", {"threadId": thread_id})
|
||||
before = collect_status(client, thread_id=thread_id, cwd=cwd, ephemeral=False)
|
||||
revision = state_revision(before)
|
||||
|
||||
|
|
@ -258,8 +509,20 @@ def run_action(args: argparse.Namespace) -> dict[str, Any]:
|
|||
}
|
||||
if revision is not None:
|
||||
payload["expectedRevision"] = revision
|
||||
response = client.send("thread/epiphany/roleLaunch", payload)
|
||||
summary = f"Launched {role_id} role worker."
|
||||
launch = client.send("thread/epiphany/roleLaunch", payload)
|
||||
if args.wait:
|
||||
result = wait_for_role_result(
|
||||
client,
|
||||
thread_id=thread_id,
|
||||
role_id=role_id,
|
||||
timeout_seconds=args.timeout_seconds,
|
||||
poll_seconds=args.poll_seconds,
|
||||
)
|
||||
response = {"launch": launch, "result": result}
|
||||
summary = f"Launched {role_id} role worker and waited for a reviewable result."
|
||||
else:
|
||||
response = launch
|
||||
summary = f"Launched {role_id} role worker without waiting."
|
||||
elif args.action in {"readModelingResult", "readVerificationResult"}:
|
||||
role_id = "modeling" if args.action == "readModelingResult" else "verification"
|
||||
response = client.send(
|
||||
|
|
@ -278,12 +541,35 @@ def run_action(args: argparse.Namespace) -> dict[str, Any]:
|
|||
},
|
||||
)
|
||||
summary = "Accepted reviewed modeling graph/checkpoint patch."
|
||||
elif args.action == "acceptVerification":
|
||||
if revision is None:
|
||||
raise ValueError("acceptVerification requires ready Epiphany state with a revision")
|
||||
response = client.send(
|
||||
"thread/epiphany/roleAccept",
|
||||
{
|
||||
"threadId": thread_id,
|
||||
"roleId": "verification",
|
||||
"expectedRevision": revision,
|
||||
},
|
||||
)
|
||||
summary = "Accepted reviewed verification finding."
|
||||
elif args.action == "launchReorient":
|
||||
payload = {"threadId": thread_id, "maxRuntimeSeconds": args.max_runtime_seconds}
|
||||
if revision is not None:
|
||||
payload["expectedRevision"] = revision
|
||||
response = client.send("thread/epiphany/reorientLaunch", payload)
|
||||
summary = "Launched fixed reorient-worker."
|
||||
launch = client.send("thread/epiphany/reorientLaunch", payload)
|
||||
if args.wait:
|
||||
result = wait_for_reorient_result(
|
||||
client,
|
||||
thread_id=thread_id,
|
||||
timeout_seconds=args.timeout_seconds,
|
||||
poll_seconds=args.poll_seconds,
|
||||
)
|
||||
response = {"launch": launch, "result": result}
|
||||
summary = "Launched fixed reorient-worker and waited for a reviewable result."
|
||||
else:
|
||||
response = launch
|
||||
summary = "Launched fixed reorient-worker without waiting."
|
||||
elif args.action == "readReorientResult":
|
||||
response = client.send(
|
||||
"thread/epiphany/reorientResult",
|
||||
|
|
@ -304,6 +590,67 @@ def run_action(args: argparse.Namespace) -> dict[str, Any]:
|
|||
},
|
||||
)
|
||||
summary = "Accepted reviewed reorientation finding."
|
||||
elif args.action == "continueImplementation":
|
||||
coordinator = before.get("coordinator")
|
||||
if not isinstance(coordinator, dict):
|
||||
raise ValueError("continueImplementation requires coordinator status")
|
||||
if coordinator.get("action") != "continueImplementation" and not args.force:
|
||||
raise ValueError(
|
||||
"coordinator is not recommending continueImplementation "
|
||||
f"(got {coordinator.get('action')!r})"
|
||||
)
|
||||
pre_git = git_snapshot(cwd)
|
||||
prompt = build_implementation_prompt(before)
|
||||
write_text(artifact_dir / "implementation-prompt.md", prompt)
|
||||
turn = client.send(
|
||||
"turn/start",
|
||||
{
|
||||
"threadId": thread_id,
|
||||
"cwd": str(cwd),
|
||||
"sandboxPolicy": {
|
||||
"type": "workspaceWrite",
|
||||
"writableRoots": [str(cwd)],
|
||||
"readOnlyAccess": {"type": "fullAccess"},
|
||||
"networkAccess": False,
|
||||
"excludeTmpdirEnvVar": False,
|
||||
"excludeSlashTmp": False,
|
||||
},
|
||||
"input": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": prompt,
|
||||
"textElements": [],
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
completed = client.wait_for_notification(
|
||||
"turn/completed", timeout=args.timeout_seconds
|
||||
)
|
||||
post_git = git_snapshot(cwd)
|
||||
implementation_result = git_change_summary(pre_git, post_git)
|
||||
write_json(artifact_dir / "git-before.json", pre_git)
|
||||
write_json(artifact_dir / "git-after.json", post_git)
|
||||
write_json(artifact_dir / "implementation-result.json", implementation_result)
|
||||
write_text(
|
||||
artifact_dir / "implementation-audit.md",
|
||||
render_implementation_audit(implementation_result),
|
||||
)
|
||||
response = {
|
||||
"turn": turn,
|
||||
"completed": sanitize_for_operator(completed),
|
||||
"preGit": pre_git,
|
||||
"postGit": post_git,
|
||||
"implementationResult": implementation_result,
|
||||
}
|
||||
if implementation_result["workspaceChanged"]:
|
||||
summary = (
|
||||
"Ran bounded implementation turn and produced a reviewable workspace diff."
|
||||
)
|
||||
else:
|
||||
summary = (
|
||||
"Ran bounded implementation turn, but it produced no workspace diff."
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"unsupported GUI action: {args.action}")
|
||||
|
||||
|
|
@ -348,6 +695,9 @@ def main() -> int:
|
|||
parser.add_argument("--thread-id")
|
||||
parser.add_argument("--artifact-root", type=Path, default=DEFAULT_ARTIFACT_ROOT)
|
||||
parser.add_argument("--max-runtime-seconds", type=int, default=180)
|
||||
parser.add_argument("--timeout-seconds", type=int, default=300)
|
||||
parser.add_argument("--poll-seconds", type=float, default=5.0)
|
||||
parser.add_argument("--wait", action=argparse.BooleanOptionalAction, default=True)
|
||||
parser.add_argument(
|
||||
"--action",
|
||||
required=True,
|
||||
|
|
@ -357,12 +707,19 @@ def main() -> int:
|
|||
"acceptModeling",
|
||||
"launchVerification",
|
||||
"readVerificationResult",
|
||||
"acceptVerification",
|
||||
"launchReorient",
|
||||
"readReorientResult",
|
||||
"acceptReorient",
|
||||
"continueImplementation",
|
||||
"prepareCheckpoint",
|
||||
],
|
||||
)
|
||||
parser.add_argument(
|
||||
"--force",
|
||||
action="store_true",
|
||||
help="Allow continueImplementation even when the coordinator is not recommending it.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
print(json.dumps(run_action(args), indent=2, ensure_ascii=False))
|
||||
return 0
|
||||
|
|
|
|||
|
|
@ -65,6 +65,19 @@ def append_jsonl(path: Path, value: Any) -> None:
|
|||
handle.write(json.dumps(value, ensure_ascii=False) + "\n")
|
||||
|
||||
|
||||
def thread_lifecycle_event(kind: str, response: dict[str, Any]) -> dict[str, Any]:
|
||||
thread = response.get("thread")
|
||||
if not isinstance(thread, dict):
|
||||
return {"type": kind}
|
||||
return {
|
||||
"type": kind,
|
||||
"threadId": thread.get("id"),
|
||||
"status": thread.get("status"),
|
||||
"cwd": thread.get("cwd"),
|
||||
"ephemeral": thread.get("ephemeral"),
|
||||
}
|
||||
|
||||
|
||||
def state_revision(status: dict[str, Any]) -> int | None:
|
||||
state = status.get("read", {}).get("thread", {}).get("epiphanyState")
|
||||
if isinstance(state, dict):
|
||||
|
|
@ -152,6 +165,29 @@ def wait_for_reorient_result(
|
|||
return latest
|
||||
|
||||
|
||||
def wait_for_any_notification(
|
||||
client: AppServerClient,
|
||||
methods: set[str],
|
||||
*,
|
||||
start_index: int,
|
||||
timeout: float,
|
||||
) -> dict[str, Any]:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
assert client.proc is not None
|
||||
if client.proc.poll() is not None:
|
||||
ordered = ", ".join(sorted(methods))
|
||||
raise RuntimeError(
|
||||
f"app-server exited with {client.proc.returncode} before notification {ordered}"
|
||||
)
|
||||
for msg in client.notifications[start_index:]:
|
||||
if msg.get("method") in methods:
|
||||
return msg
|
||||
time.sleep(0.1)
|
||||
ordered = ", ".join(sorted(methods))
|
||||
raise TimeoutError(f"timed out waiting for notification {ordered}")
|
||||
|
||||
|
||||
def launch_role(
|
||||
client: AppServerClient,
|
||||
*,
|
||||
|
|
@ -248,6 +284,7 @@ def run_coordinator(args: argparse.Namespace) -> dict[str, Any]:
|
|||
prepare_workspace(cwd)
|
||||
|
||||
steps: list[dict[str, Any]] = []
|
||||
startup_events: list[dict[str, Any]] = []
|
||||
snapshots: list[str] = []
|
||||
final_status: dict[str, Any] | None = None
|
||||
final_action: dict[str, Any] | None = None
|
||||
|
|
@ -272,8 +309,12 @@ def run_coordinator(args: argparse.Namespace) -> dict[str, Any]:
|
|||
)
|
||||
assert started is not None
|
||||
thread_id = started["thread"]["id"]
|
||||
startup_events.append(thread_lifecycle_event("threadStart", started))
|
||||
else:
|
||||
thread_id = args.thread_id
|
||||
resumed = client.send("thread/resume", {"threadId": thread_id})
|
||||
assert resumed is not None
|
||||
startup_events.append(thread_lifecycle_event("threadResume", resumed))
|
||||
|
||||
if args.bootstrap_smoke_state:
|
||||
update = client.send(
|
||||
|
|
@ -366,6 +407,12 @@ def run_coordinator(args: argparse.Namespace) -> dict[str, Any]:
|
|||
"result": sanitize_for_operator(result),
|
||||
}
|
||||
)
|
||||
final_status = collect_coordinator_status(
|
||||
client,
|
||||
thread_id=thread_id,
|
||||
cwd=cwd,
|
||||
ephemeral=args.ephemeral,
|
||||
)
|
||||
if not args.auto_review:
|
||||
final_action = {"action": "reviewModelingResult", "reason": result.get("note")}
|
||||
append_jsonl(steps_path, step)
|
||||
|
|
@ -407,6 +454,12 @@ def run_coordinator(args: argparse.Namespace) -> dict[str, Any]:
|
|||
"result": sanitize_for_operator(result),
|
||||
}
|
||||
)
|
||||
final_status = collect_coordinator_status(
|
||||
client,
|
||||
thread_id=thread_id,
|
||||
cwd=cwd,
|
||||
ephemeral=args.ephemeral,
|
||||
)
|
||||
if not args.auto_review:
|
||||
final_action = {"action": "reviewVerificationResult", "reason": result.get("note")}
|
||||
append_jsonl(steps_path, step)
|
||||
|
|
@ -434,6 +487,12 @@ def run_coordinator(args: argparse.Namespace) -> dict[str, Any]:
|
|||
poll_seconds=args.poll_seconds,
|
||||
)
|
||||
step["events"].append({"type": "reorientResult", "result": sanitize_for_operator(result)})
|
||||
final_status = collect_coordinator_status(
|
||||
client,
|
||||
thread_id=thread_id,
|
||||
cwd=cwd,
|
||||
ephemeral=args.ephemeral,
|
||||
)
|
||||
if not args.auto_review:
|
||||
final_action = {"action": "reviewReorientResult", "reason": result.get("note")}
|
||||
append_jsonl(steps_path, step)
|
||||
|
|
@ -446,11 +505,15 @@ def run_coordinator(args: argparse.Namespace) -> dict[str, Any]:
|
|||
step["events"].append({"type": "dryCompact", "threadId": thread_id})
|
||||
append_jsonl(steps_path, step)
|
||||
continue
|
||||
notification_start_index = len(client.notifications)
|
||||
compact = client.send("thread/compact/start", {"threadId": thread_id})
|
||||
step["events"].append({"type": "compactStart", "response": sanitize_for_operator(compact)})
|
||||
try:
|
||||
notification = client.wait_for_notification(
|
||||
"thread/compacted", timeout=args.timeout_seconds
|
||||
notification = wait_for_any_notification(
|
||||
client,
|
||||
{"thread/compacted", "turn/completed"},
|
||||
start_index=notification_start_index,
|
||||
timeout=args.timeout_seconds,
|
||||
)
|
||||
step["events"].append(
|
||||
{"type": "compacted", "notification": sanitize_for_operator(notification)}
|
||||
|
|
@ -465,6 +528,57 @@ def run_coordinator(args: argparse.Namespace) -> dict[str, Any]:
|
|||
break
|
||||
resumed = client.send("thread/resume", {"threadId": thread_id})
|
||||
step["events"].append({"type": "resume", "response": sanitize_for_operator(resumed)})
|
||||
post_compact_status = collect_coordinator_status(
|
||||
client,
|
||||
thread_id=thread_id,
|
||||
cwd=cwd,
|
||||
ephemeral=args.ephemeral,
|
||||
)
|
||||
post_compact_crrc = post_compact_status.get("crrc", {}).get("recommendation", {})
|
||||
step["events"].append(
|
||||
{"type": "postCompactCrrc", "recommendation": sanitize_for_operator(post_compact_crrc)}
|
||||
)
|
||||
final_status = post_compact_status
|
||||
if post_compact_crrc.get("action") == "launchReorientWorker":
|
||||
launch = launch_reorient(
|
||||
client,
|
||||
thread_id=thread_id,
|
||||
expected_revision=state_revision(post_compact_status),
|
||||
max_runtime_seconds=args.max_runtime_seconds,
|
||||
)
|
||||
step["events"].append(
|
||||
{"type": "reorientLaunch", "launch": sanitize_for_operator(launch)}
|
||||
)
|
||||
completed = maybe_complete_reorient_backend(args, launch)
|
||||
if completed is not None:
|
||||
step["events"].append(
|
||||
{
|
||||
"type": "testCompleteBackend",
|
||||
"payload": sanitize_for_operator(completed),
|
||||
}
|
||||
)
|
||||
result = wait_for_reorient_result(
|
||||
client,
|
||||
thread_id=thread_id,
|
||||
timeout_seconds=args.timeout_seconds,
|
||||
poll_seconds=args.poll_seconds,
|
||||
)
|
||||
step["events"].append(
|
||||
{"type": "reorientResult", "result": sanitize_for_operator(result)}
|
||||
)
|
||||
final_status = collect_coordinator_status(
|
||||
client,
|
||||
thread_id=thread_id,
|
||||
cwd=cwd,
|
||||
ephemeral=args.ephemeral,
|
||||
)
|
||||
if not args.auto_review:
|
||||
final_action = {
|
||||
"action": "reviewReorientResult",
|
||||
"reason": result.get("note"),
|
||||
}
|
||||
append_jsonl(steps_path, step)
|
||||
break
|
||||
append_jsonl(steps_path, step)
|
||||
continue
|
||||
|
||||
|
|
@ -489,6 +603,7 @@ def run_coordinator(args: argparse.Namespace) -> dict[str, Any]:
|
|||
"workspace": str(cwd),
|
||||
"threadId": final_status["threadId"] if final_status else args.thread_id,
|
||||
"mode": args.mode,
|
||||
"startupEvents": sanitize_for_operator(startup_events),
|
||||
"steps": operator_steps,
|
||||
"snapshots": snapshots,
|
||||
"finalAction": operator_final_action,
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ from __future__ import annotations
|
|||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
|
|
@ -102,6 +103,48 @@ def assert_interrupted_specialist_job(job: dict[str, Any]) -> None:
|
|||
)
|
||||
|
||||
|
||||
def read_backend_job_metadata(codex_home: Path, job_id: str) -> dict[str, Any]:
|
||||
db_paths = sorted(codex_home.glob("state_*.sqlite"))
|
||||
require(db_paths, f"state sqlite database should exist under {codex_home}")
|
||||
db_path = db_paths[-1]
|
||||
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
|
||||
conn.row_factory = sqlite3.Row
|
||||
try:
|
||||
job_row = conn.execute(
|
||||
"""
|
||||
SELECT status, last_error IS NOT NULL AS has_error
|
||||
FROM agent_jobs
|
||||
WHERE id = ?
|
||||
""",
|
||||
(job_id,),
|
||||
).fetchone()
|
||||
require(job_row is not None, f"backend job {job_id!r} should exist")
|
||||
item_row = conn.execute(
|
||||
"""
|
||||
SELECT status,
|
||||
assigned_thread_id IS NOT NULL AS has_thread,
|
||||
last_error IS NOT NULL AS has_error,
|
||||
completed_at IS NOT NULL AS has_completed_at
|
||||
FROM agent_job_items
|
||||
WHERE job_id = ?
|
||||
ORDER BY row_index ASC
|
||||
LIMIT 1
|
||||
""",
|
||||
(job_id,),
|
||||
).fetchone()
|
||||
require(item_row is not None, f"backend item for job {job_id!r} should exist")
|
||||
return {
|
||||
"jobStatus": job_row["status"],
|
||||
"jobHasError": bool(job_row["has_error"]),
|
||||
"itemStatus": item_row["status"],
|
||||
"itemHasThread": bool(item_row["has_thread"]),
|
||||
"itemHasError": bool(item_row["has_error"]),
|
||||
"itemHasCompletedAt": bool(item_row["has_completed_at"]),
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def wait_for_jobs_surface(
|
||||
client: AppServerClient,
|
||||
thread_id: str,
|
||||
|
|
@ -322,6 +365,30 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
|
|||
interrupted_job = job_by_id(interrupted_jobs["jobs"], BINDING_ID)
|
||||
assert_interrupted_specialist_job(interrupted_job)
|
||||
|
||||
backend_metadata = read_backend_job_metadata(
|
||||
codex_home, ready_job["backendJobId"]
|
||||
)
|
||||
require(
|
||||
backend_metadata["jobStatus"] == "cancelled",
|
||||
"interrupt should mark the backend job cancelled",
|
||||
)
|
||||
require(
|
||||
backend_metadata["itemStatus"] == "failed",
|
||||
"interrupt should close the running backend item instead of leaving it running",
|
||||
)
|
||||
require(
|
||||
not backend_metadata["itemHasThread"],
|
||||
"interrupt should clear the backend item thread assignment",
|
||||
)
|
||||
require(
|
||||
backend_metadata["itemHasError"],
|
||||
"interrupt should leave an item-level interruption reason",
|
||||
)
|
||||
require(
|
||||
backend_metadata["itemHasCompletedAt"],
|
||||
"interrupt should set completed_at on the closed backend item",
|
||||
)
|
||||
|
||||
final_read = client.send("thread/read", {"threadId": thread_id, "includeTurns": False})
|
||||
assert final_read is not None
|
||||
require(
|
||||
|
|
@ -344,6 +411,7 @@ def run_smoke(args: argparse.Namespace) -> dict[str, Any]:
|
|||
"interruptInterruptedThreadIds": interrupt["interruptedThreadIds"],
|
||||
"interruptedStatus": interrupted_job["status"],
|
||||
"interruptedBlockingReason": interrupted_job["blockingReason"],
|
||||
"backendAfterInterrupt": backend_metadata,
|
||||
"jobsUpdatedNotificationCount": client.count_notifications(
|
||||
"thread/epiphany/jobsUpdated",
|
||||
start_index=launch_notification_start,
|
||||
|
|
|
|||
|
|
@ -235,7 +235,13 @@ pub(crate) async fn apply_bespoke_event_handling(
|
|||
EventMsg::TurnComplete(turn_complete_event) => {
|
||||
// All per-thread requests are bound to a turn, so abort them.
|
||||
outgoing.abort_pending_server_requests().await;
|
||||
let turn_failed = thread_state.lock().await.turn_summary.last_error.is_some();
|
||||
let (turn_failed, turn_was_context_compaction) = {
|
||||
let state = thread_state.lock().await;
|
||||
(
|
||||
state.turn_summary.last_error.is_some(),
|
||||
state.turn_summary.context_compaction_started,
|
||||
)
|
||||
};
|
||||
thread_watch_manager
|
||||
.note_turn_completed(&conversation_id.to_string(), turn_failed)
|
||||
.await;
|
||||
|
|
@ -248,7 +254,7 @@ pub(crate) async fn apply_bespoke_event_handling(
|
|||
&thread_state,
|
||||
)
|
||||
.await;
|
||||
if !turn_failed {
|
||||
if !turn_failed && !turn_was_context_compaction {
|
||||
maybe_run_epiphany_coordinator_automation_for_turn_boundary(
|
||||
conversation_id,
|
||||
conversation,
|
||||
|
|
@ -1591,6 +1597,13 @@ pub(crate) async fn apply_bespoke_event_handling(
|
|||
}
|
||||
EventMsg::ItemStarted(item_started_event) => {
|
||||
let item: ThreadItem = item_started_event.item.clone().into();
|
||||
if matches!(item, ThreadItem::ContextCompaction { .. }) {
|
||||
thread_state
|
||||
.lock()
|
||||
.await
|
||||
.turn_summary
|
||||
.context_compaction_started = true;
|
||||
}
|
||||
let notification = ItemStartedNotification {
|
||||
thread_id: conversation_id.to_string(),
|
||||
turn_id: event_turn_id.clone(),
|
||||
|
|
|
|||
|
|
@ -4602,6 +4602,12 @@ impl CodexMessageProcessor {
|
|||
.as_ref()
|
||||
.and_then(|state| state.investigation_checkpoint.as_ref())
|
||||
.is_some();
|
||||
let reorient_finding_accepted = reorient_finding.as_ref().is_some_and(|finding| {
|
||||
thread
|
||||
.epiphany_state
|
||||
.as_ref()
|
||||
.is_some_and(|state| epiphany_reorient_finding_already_accepted(state, finding))
|
||||
});
|
||||
let recommendation = map_epiphany_crrc_recommendation(
|
||||
loaded,
|
||||
state_status,
|
||||
|
|
@ -4610,12 +4616,7 @@ impl CodexMessageProcessor {
|
|||
reorient_result_status,
|
||||
checkpoint_present,
|
||||
reorient_finding.is_some(),
|
||||
reorient_finding.as_ref().is_some_and(|finding| {
|
||||
thread
|
||||
.epiphany_state
|
||||
.as_ref()
|
||||
.is_some_and(|state| epiphany_reorient_finding_already_accepted(state, finding))
|
||||
}),
|
||||
reorient_finding_accepted,
|
||||
);
|
||||
let roles = map_epiphany_roles(
|
||||
thread.epiphany_state.as_ref(),
|
||||
|
|
@ -4642,22 +4643,28 @@ impl CodexMessageProcessor {
|
|||
"No authoritative Epiphany state exists for this thread.".to_string(),
|
||||
)
|
||||
};
|
||||
let (verification_result_status, _, _) = if let Some(state) = thread.epiphany_state.as_ref()
|
||||
{
|
||||
load_epiphany_role_result_snapshot(
|
||||
state,
|
||||
state_db_ctx.as_ref(),
|
||||
ThreadEpiphanyRoleId::Verification,
|
||||
EPIPHANY_VERIFICATION_ROLE_BINDING_ID,
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
(
|
||||
ThreadEpiphanyRoleResultStatus::MissingState,
|
||||
None,
|
||||
"No authoritative Epiphany state exists for this thread.".to_string(),
|
||||
)
|
||||
};
|
||||
let (verification_result_status, verification_finding, _) =
|
||||
if let Some(state) = thread.epiphany_state.as_ref() {
|
||||
load_epiphany_role_result_snapshot(
|
||||
state,
|
||||
state_db_ctx.as_ref(),
|
||||
ThreadEpiphanyRoleId::Verification,
|
||||
EPIPHANY_VERIFICATION_ROLE_BINDING_ID,
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
(
|
||||
ThreadEpiphanyRoleResultStatus::MissingState,
|
||||
None,
|
||||
"No authoritative Epiphany state exists for this thread.".to_string(),
|
||||
)
|
||||
};
|
||||
let verification_result_accepted = verification_finding.as_ref().is_some_and(|finding| {
|
||||
thread
|
||||
.epiphany_state
|
||||
.as_ref()
|
||||
.is_some_and(|state| epiphany_role_finding_already_accepted(state, finding))
|
||||
});
|
||||
|
||||
let source_signals = ThreadEpiphanyCoordinatorSignals {
|
||||
pressure_level: pressure.level,
|
||||
|
|
@ -4675,6 +4682,8 @@ impl CodexMessageProcessor {
|
|||
&recommendation,
|
||||
&roles,
|
||||
&source_signals,
|
||||
verification_result_accepted,
|
||||
reorient_finding_accepted,
|
||||
);
|
||||
let note = render_epiphany_coordinator_note(
|
||||
recommendation.action,
|
||||
|
|
@ -4960,16 +4969,14 @@ impl CodexMessageProcessor {
|
|||
binding_id,
|
||||
} = params;
|
||||
|
||||
if role_id != ThreadEpiphanyRoleId::Modeling {
|
||||
self.send_invalid_request_error(
|
||||
request_id,
|
||||
"only the modeling/checkpoint role currently has an Epiphany role acceptance path"
|
||||
.to_string(),
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
let binding_id = binding_id.unwrap_or_else(|| EPIPHANY_MODELING_ROLE_BINDING_ID.into());
|
||||
let default_binding_id = match epiphany_role_binding_id(role_id) {
|
||||
Ok(binding_id) => binding_id,
|
||||
Err(message) => {
|
||||
self.send_invalid_request_error(request_id, message).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
let binding_id = binding_id.unwrap_or_else(|| default_binding_id.into());
|
||||
|
||||
let thread_uuid = match ThreadId::from_string(&thread_id) {
|
||||
Ok(id) => id,
|
||||
|
|
@ -5037,32 +5044,54 @@ impl CodexMessageProcessor {
|
|||
}
|
||||
};
|
||||
|
||||
let mut patch = match parse_role_finding_state_patch(&finding) {
|
||||
Ok(patch) => patch,
|
||||
Err(message) => {
|
||||
self.send_invalid_request_error(request_id, message).await;
|
||||
let mut patch = match role_id {
|
||||
ThreadEpiphanyRoleId::Modeling => {
|
||||
let patch = match parse_role_finding_state_patch(&finding) {
|
||||
Ok(patch) => patch,
|
||||
Err(message) => {
|
||||
self.send_invalid_request_error(request_id, message).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
let patch_errors = modeling_role_accept_patch_errors(&patch);
|
||||
if !patch_errors.is_empty() {
|
||||
self.send_invalid_request_error(
|
||||
request_id,
|
||||
format!(
|
||||
"modeling role state patch is not acceptable: {}",
|
||||
patch_errors.join("; ")
|
||||
),
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
patch
|
||||
}
|
||||
ThreadEpiphanyRoleId::Verification => ThreadEpiphanyUpdatePatch::default(),
|
||||
ThreadEpiphanyRoleId::Implementation | ThreadEpiphanyRoleId::Reorientation => {
|
||||
self.send_invalid_request_error(
|
||||
request_id,
|
||||
format!("role {:?} cannot be accepted through roleAccept", role_id),
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
let patch_errors = modeling_role_accept_patch_errors(&patch);
|
||||
if !patch_errors.is_empty() {
|
||||
self.send_invalid_request_error(
|
||||
request_id,
|
||||
format!(
|
||||
"modeling role state patch is not acceptable: {}",
|
||||
patch_errors.join("; ")
|
||||
),
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
|
||||
let accepted_evidence_id = format!("ev-modeling-{}", Uuid::new_v4());
|
||||
let accepted_observation_id = format!("obs-modeling-{}", Uuid::new_v4());
|
||||
let accepted_kind = match role_id {
|
||||
ThreadEpiphanyRoleId::Modeling => "modeling_result",
|
||||
ThreadEpiphanyRoleId::Verification => "verification_result",
|
||||
ThreadEpiphanyRoleId::Implementation | ThreadEpiphanyRoleId::Reorientation => {
|
||||
unreachable!("unsupported roles returned above")
|
||||
}
|
||||
};
|
||||
let accepted_prefix = epiphany_role_label(role_id);
|
||||
let accepted_evidence_id = format!("ev-{accepted_prefix}-{}", Uuid::new_v4());
|
||||
let accepted_observation_id = format!("obs-{accepted_prefix}-{}", Uuid::new_v4());
|
||||
let code_refs = role_finding_code_refs(&finding);
|
||||
let evidence = EpiphanyEvidenceRecord {
|
||||
id: accepted_evidence_id.clone(),
|
||||
kind: "modeling_result".to_string(),
|
||||
kind: accepted_kind.to_string(),
|
||||
status: "accepted".to_string(),
|
||||
summary: role_finding_summary(&finding),
|
||||
code_refs: code_refs.clone(),
|
||||
|
|
@ -5070,7 +5099,7 @@ impl CodexMessageProcessor {
|
|||
let observation = EpiphanyObservation {
|
||||
id: accepted_observation_id.clone(),
|
||||
summary: role_finding_observation_summary(&finding),
|
||||
source_kind: "modeling_result".to_string(),
|
||||
source_kind: accepted_kind.to_string(),
|
||||
status: "accepted".to_string(),
|
||||
code_refs,
|
||||
evidence_ids: vec![accepted_evidence_id.clone()],
|
||||
|
|
@ -13682,24 +13711,10 @@ async fn load_epiphany_reorient_result_snapshot(
|
|||
"No authoritative Epiphany state exists for this thread.".to_string(),
|
||||
);
|
||||
};
|
||||
let Some(binding) = state
|
||||
let binding = state
|
||||
.job_bindings
|
||||
.iter()
|
||||
.find(|binding| binding.id == binding_id)
|
||||
else {
|
||||
return (
|
||||
ThreadEpiphanyReorientResultStatus::MissingBinding,
|
||||
None,
|
||||
"No matching Epiphany reorientation worker binding exists.".to_string(),
|
||||
);
|
||||
};
|
||||
let Some(agent_job_id) = binding_agent_jobs_job_id(binding) else {
|
||||
return (
|
||||
ThreadEpiphanyReorientResultStatus::BackendUnavailable,
|
||||
None,
|
||||
"The matching binding is not currently backed by the agent_jobs backend.".to_string(),
|
||||
);
|
||||
};
|
||||
.find(|binding| binding.id == binding_id);
|
||||
let Some(state_db_ctx) = state_db_ctx else {
|
||||
return (
|
||||
ThreadEpiphanyReorientResultStatus::BackendUnavailable,
|
||||
|
|
@ -13708,44 +13723,78 @@ async fn load_epiphany_reorient_result_snapshot(
|
|||
.to_string(),
|
||||
);
|
||||
};
|
||||
let agent_job = match state_db_ctx.get_agent_job(agent_job_id).await {
|
||||
Ok(Some(job)) => job,
|
||||
Ok(None) => {
|
||||
return (
|
||||
ThreadEpiphanyReorientResultStatus::BackendMissing,
|
||||
None,
|
||||
format!(
|
||||
"Bound agent_jobs backend job {:?} was not found.",
|
||||
agent_job_id
|
||||
),
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
let (agent_job, item) = if let Some(binding) = binding {
|
||||
let Some(agent_job_id) = binding_agent_jobs_job_id(binding) else {
|
||||
return (
|
||||
ThreadEpiphanyReorientResultStatus::BackendUnavailable,
|
||||
None,
|
||||
format!("Failed to read Epiphany reorientation backend job: {err}"),
|
||||
);
|
||||
}
|
||||
};
|
||||
let item = match state_db_ctx
|
||||
.get_agent_job_item(agent_job_id, binding_id)
|
||||
.await
|
||||
{
|
||||
Ok(Some(item)) => item,
|
||||
Ok(None) => {
|
||||
return (
|
||||
ThreadEpiphanyReorientResultStatus::BackendMissing,
|
||||
None,
|
||||
"Bound agent_jobs backend item was not found for this reorient worker.".to_string(),
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
return (
|
||||
ThreadEpiphanyReorientResultStatus::BackendUnavailable,
|
||||
None,
|
||||
format!("Failed to read Epiphany reorientation backend item: {err}"),
|
||||
"The matching binding is not currently backed by the agent_jobs backend."
|
||||
.to_string(),
|
||||
);
|
||||
};
|
||||
let agent_job = match state_db_ctx.get_agent_job(agent_job_id).await {
|
||||
Ok(Some(job)) => job,
|
||||
Ok(None) => {
|
||||
return (
|
||||
ThreadEpiphanyReorientResultStatus::BackendMissing,
|
||||
None,
|
||||
format!(
|
||||
"Bound agent_jobs backend job {:?} was not found.",
|
||||
agent_job_id
|
||||
),
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
return (
|
||||
ThreadEpiphanyReorientResultStatus::BackendUnavailable,
|
||||
None,
|
||||
format!("Failed to read Epiphany reorientation backend job: {err}"),
|
||||
);
|
||||
}
|
||||
};
|
||||
let item = match state_db_ctx
|
||||
.get_agent_job_item(agent_job_id, binding_id)
|
||||
.await
|
||||
{
|
||||
Ok(Some(item)) => item,
|
||||
Ok(None) => {
|
||||
return (
|
||||
ThreadEpiphanyReorientResultStatus::BackendMissing,
|
||||
None,
|
||||
"Bound agent_jobs backend item was not found for this reorient worker."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
return (
|
||||
ThreadEpiphanyReorientResultStatus::BackendUnavailable,
|
||||
None,
|
||||
format!("Failed to read Epiphany reorientation backend item: {err}"),
|
||||
);
|
||||
}
|
||||
};
|
||||
(agent_job, item)
|
||||
} else {
|
||||
match state_db_ctx
|
||||
.latest_agent_job_item_by_source_id(binding_id)
|
||||
.await
|
||||
{
|
||||
Ok(Some((agent_job, item))) => (agent_job, item),
|
||||
Ok(None) => {
|
||||
return (
|
||||
ThreadEpiphanyReorientResultStatus::MissingBinding,
|
||||
None,
|
||||
"No matching Epiphany reorientation worker binding or recovered backend item exists."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
return (
|
||||
ThreadEpiphanyReorientResultStatus::BackendUnavailable,
|
||||
None,
|
||||
format!("Failed to recover Epiphany reorientation backend item: {err}"),
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
let status = map_epiphany_reorient_result_status(agent_job.status, item.status);
|
||||
|
|
@ -13819,6 +13868,20 @@ fn map_epiphany_crrc_recommendation(
|
|||
"The reorientation finding is already accepted; re-gather from the banked checkpoint before implementation continues.",
|
||||
);
|
||||
}
|
||||
if finding_accepted {
|
||||
return build(
|
||||
ThreadEpiphanyCrrcAction::Continue,
|
||||
Some(ThreadEpiphanySceneAction::Reorient),
|
||||
"The reorientation finding is already accepted and the checkpoint remains resume-ready; continue the bounded task.",
|
||||
);
|
||||
}
|
||||
if finding_present {
|
||||
return build(
|
||||
ThreadEpiphanyCrrcAction::ReviewReorientResult,
|
||||
Some(ThreadEpiphanySceneAction::ReorientResult),
|
||||
"A completed reorientation finding is available, but it has not been accepted yet.",
|
||||
);
|
||||
}
|
||||
return build(
|
||||
ThreadEpiphanyCrrcAction::ReviewReorientResult,
|
||||
Some(ThreadEpiphanySceneAction::ReorientResult),
|
||||
|
|
@ -13919,6 +13982,8 @@ fn map_epiphany_coordinator(
|
|||
recommendation: &ThreadEpiphanyCrrcRecommendation,
|
||||
roles: &[ThreadEpiphanyRoleLane],
|
||||
signals: &ThreadEpiphanyCoordinatorSignals,
|
||||
verification_result_accepted: bool,
|
||||
reorient_finding_accepted: bool,
|
||||
) -> EpiphanyCoordinatorDecision {
|
||||
let build = |action,
|
||||
target_role,
|
||||
|
|
@ -13982,7 +14047,10 @@ fn map_epiphany_coordinator(
|
|||
| ThreadEpiphanyCrrcAction::Continue => {}
|
||||
}
|
||||
|
||||
if pressure.should_prepare_compaction {
|
||||
if pressure.should_prepare_compaction
|
||||
&& !(reorient_finding_accepted
|
||||
&& recommendation.action == ThreadEpiphanyCrrcAction::Continue)
|
||||
{
|
||||
return build(
|
||||
ThreadEpiphanyCoordinatorAction::CompactRehydrateReorient,
|
||||
Some(ThreadEpiphanyRoleId::Reorientation),
|
||||
|
|
@ -14004,7 +14072,9 @@ fn map_epiphany_coordinator(
|
|||
);
|
||||
}
|
||||
|
||||
if signals.verification_result_status == ThreadEpiphanyRoleResultStatus::Completed {
|
||||
if signals.verification_result_status == ThreadEpiphanyRoleResultStatus::Completed
|
||||
&& !verification_result_accepted
|
||||
{
|
||||
return build(
|
||||
ThreadEpiphanyCoordinatorAction::ReviewVerificationResult,
|
||||
Some(ThreadEpiphanyRoleId::Verification),
|
||||
|
|
@ -14015,7 +14085,9 @@ fn map_epiphany_coordinator(
|
|||
);
|
||||
}
|
||||
|
||||
if signals.modeling_result_status == ThreadEpiphanyRoleResultStatus::Completed {
|
||||
if signals.modeling_result_status == ThreadEpiphanyRoleResultStatus::Completed
|
||||
&& !verification_result_accepted
|
||||
{
|
||||
return build(
|
||||
ThreadEpiphanyCoordinatorAction::LaunchVerification,
|
||||
Some(ThreadEpiphanyRoleId::Verification),
|
||||
|
|
@ -14132,6 +14204,25 @@ fn epiphany_reorient_finding_already_accepted(
|
|||
})
|
||||
}
|
||||
|
||||
fn epiphany_role_finding_already_accepted(
|
||||
state: &EpiphanyThreadState,
|
||||
finding: &ThreadEpiphanyRoleFinding,
|
||||
) -> bool {
|
||||
let accepted_kind = match finding.role_id {
|
||||
ThreadEpiphanyRoleId::Modeling => "modeling_result",
|
||||
ThreadEpiphanyRoleId::Verification => "verification_result",
|
||||
ThreadEpiphanyRoleId::Implementation | ThreadEpiphanyRoleId::Reorientation => {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
let accepted_summary = role_finding_summary(finding);
|
||||
state.recent_evidence.iter().any(|evidence| {
|
||||
evidence.kind == accepted_kind
|
||||
&& evidence.status == "accepted"
|
||||
&& evidence.summary == accepted_summary
|
||||
})
|
||||
}
|
||||
|
||||
fn map_epiphany_roles(
|
||||
state: Option<&EpiphanyThreadState>,
|
||||
jobs: &[ThreadEpiphanyJob],
|
||||
|
|
@ -14263,6 +14354,7 @@ fn map_epiphany_roles(
|
|||
authority_scopes: vec![
|
||||
"thread/epiphany/roleLaunch".to_string(),
|
||||
"thread/epiphany/roleResult".to_string(),
|
||||
"thread/epiphany/roleAccept".to_string(),
|
||||
"thread/epiphany/distill".to_string(),
|
||||
"thread/epiphany/propose".to_string(),
|
||||
"thread/epiphany/promote".to_string(),
|
||||
|
|
@ -14393,52 +14485,64 @@ async fn load_completed_epiphany_reorient_finding(
|
|||
state: &EpiphanyThreadState,
|
||||
binding_id: &str,
|
||||
) -> CodexResult<ThreadEpiphanyReorientFinding> {
|
||||
let binding = state
|
||||
.job_bindings
|
||||
.iter()
|
||||
.find(|binding| binding.id == binding_id)
|
||||
.ok_or_else(|| {
|
||||
CodexErr::InvalidRequest(format!(
|
||||
"epiphany reorientation binding {:?} was not found",
|
||||
binding_id
|
||||
))
|
||||
})?;
|
||||
let agent_job_id = binding_agent_jobs_job_id(binding).ok_or_else(|| {
|
||||
CodexErr::InvalidRequest(format!(
|
||||
"epiphany reorientation binding {:?} is not backed by agent_jobs",
|
||||
binding_id
|
||||
))
|
||||
})?;
|
||||
let state_db_ctx = thread.epiphany_state_runtime().await.ok_or_else(|| {
|
||||
CodexErr::InvalidRequest(
|
||||
"sqlite state db is unavailable for Epiphany reorientation result acceptance"
|
||||
.to_string(),
|
||||
)
|
||||
})?;
|
||||
let agent_job = state_db_ctx
|
||||
.get_agent_job(agent_job_id)
|
||||
.await
|
||||
.map_err(|err| CodexErr::Fatal(format!("failed to read Epiphany backend job: {err}")))?
|
||||
.ok_or_else(|| {
|
||||
let (agent_job, item) = if let Some(binding) = state
|
||||
.job_bindings
|
||||
.iter()
|
||||
.find(|binding| binding.id == binding_id)
|
||||
{
|
||||
let agent_job_id = binding_agent_jobs_job_id(binding).ok_or_else(|| {
|
||||
CodexErr::InvalidRequest(format!(
|
||||
"bound agent_jobs backend job {:?} was not found",
|
||||
agent_job_id
|
||||
))
|
||||
})?;
|
||||
let item = state_db_ctx
|
||||
.get_agent_job_item(agent_job_id, binding_id)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
CodexErr::Fatal(format!(
|
||||
"failed to read Epiphany backend job item for {binding_id:?}: {err}"
|
||||
))
|
||||
})?
|
||||
.ok_or_else(|| {
|
||||
CodexErr::InvalidRequest(format!(
|
||||
"bound agent_jobs backend item {:?} was not found",
|
||||
"epiphany reorientation binding {:?} is not backed by agent_jobs",
|
||||
binding_id
|
||||
))
|
||||
})?;
|
||||
let agent_job = state_db_ctx
|
||||
.get_agent_job(agent_job_id)
|
||||
.await
|
||||
.map_err(|err| CodexErr::Fatal(format!("failed to read Epiphany backend job: {err}")))?
|
||||
.ok_or_else(|| {
|
||||
CodexErr::InvalidRequest(format!(
|
||||
"bound agent_jobs backend job {:?} was not found",
|
||||
agent_job_id
|
||||
))
|
||||
})?;
|
||||
let item = state_db_ctx
|
||||
.get_agent_job_item(agent_job_id, binding_id)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
CodexErr::Fatal(format!(
|
||||
"failed to read Epiphany backend job item for {binding_id:?}: {err}"
|
||||
))
|
||||
})?
|
||||
.ok_or_else(|| {
|
||||
CodexErr::InvalidRequest(format!(
|
||||
"bound agent_jobs backend item {:?} was not found",
|
||||
binding_id
|
||||
))
|
||||
})?;
|
||||
(agent_job, item)
|
||||
} else {
|
||||
state_db_ctx
|
||||
.latest_agent_job_item_by_source_id(binding_id)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
CodexErr::Fatal(format!(
|
||||
"failed to recover Epiphany backend job item for {binding_id:?}: {err}"
|
||||
))
|
||||
})?
|
||||
.ok_or_else(|| {
|
||||
CodexErr::InvalidRequest(format!(
|
||||
"epiphany reorientation binding {:?} was not found and no recovered backend item exists",
|
||||
binding_id
|
||||
))
|
||||
})?
|
||||
};
|
||||
let status = map_epiphany_reorient_result_status(agent_job.status, item.status);
|
||||
if status != ThreadEpiphanyReorientResultStatus::Completed {
|
||||
return Err(CodexErr::InvalidRequest(format!(
|
||||
|
|
@ -16185,6 +16289,9 @@ pub(crate) async fn maybe_run_epiphany_coordinator_automation_for_turn_boundary(
|
|||
EPIPHANY_REORIENT_LAUNCH_BINDING_ID,
|
||||
)
|
||||
.await;
|
||||
let reorient_finding_accepted = reorient_finding
|
||||
.as_ref()
|
||||
.is_some_and(|finding| epiphany_reorient_finding_already_accepted(&state, finding));
|
||||
let crrc_recommendation = map_epiphany_crrc_recommendation(
|
||||
true,
|
||||
state_status,
|
||||
|
|
@ -16193,9 +16300,7 @@ pub(crate) async fn maybe_run_epiphany_coordinator_automation_for_turn_boundary(
|
|||
reorient_result_status,
|
||||
state.investigation_checkpoint.as_ref().is_some(),
|
||||
reorient_finding.is_some(),
|
||||
reorient_finding
|
||||
.as_ref()
|
||||
.is_some_and(|finding| epiphany_reorient_finding_already_accepted(&state, finding)),
|
||||
reorient_finding_accepted,
|
||||
);
|
||||
let roles = map_epiphany_roles(
|
||||
Some(&state),
|
||||
|
|
@ -16213,13 +16318,16 @@ pub(crate) async fn maybe_run_epiphany_coordinator_automation_for_turn_boundary(
|
|||
EPIPHANY_MODELING_ROLE_BINDING_ID,
|
||||
)
|
||||
.await;
|
||||
let (verification_result_status, _, _) = load_epiphany_role_result_snapshot(
|
||||
let (verification_result_status, verification_finding, _) = load_epiphany_role_result_snapshot(
|
||||
&state,
|
||||
state_db_ctx.as_ref(),
|
||||
ThreadEpiphanyRoleId::Verification,
|
||||
EPIPHANY_VERIFICATION_ROLE_BINDING_ID,
|
||||
)
|
||||
.await;
|
||||
let verification_result_accepted = verification_finding
|
||||
.as_ref()
|
||||
.is_some_and(|finding| epiphany_role_finding_already_accepted(&state, finding));
|
||||
let source_signals = ThreadEpiphanyCoordinatorSignals {
|
||||
pressure_level: pressure.level,
|
||||
should_prepare_compaction: pressure.should_prepare_compaction,
|
||||
|
|
@ -16236,6 +16344,8 @@ pub(crate) async fn maybe_run_epiphany_coordinator_automation_for_turn_boundary(
|
|||
&crrc_recommendation,
|
||||
&roles,
|
||||
&source_signals,
|
||||
verification_result_accepted,
|
||||
reorient_finding_accepted,
|
||||
);
|
||||
|
||||
match map_epiphany_coordinator_automation_action(&coordinator) {
|
||||
|
|
@ -16300,12 +16410,14 @@ pub(crate) async fn maybe_run_epiphany_pre_compaction_checkpoint_intervention_fo
|
|||
if thread.epiphany_state().await.is_none() {
|
||||
return;
|
||||
}
|
||||
if !thread_state
|
||||
.lock()
|
||||
.await
|
||||
.record_epiphany_checkpoint_intervention(&turn_id)
|
||||
{
|
||||
return;
|
||||
let mut state = thread_state.lock().await;
|
||||
if state.turn_summary.context_compaction_started {
|
||||
return;
|
||||
}
|
||||
if !state.record_epiphany_checkpoint_intervention(&turn_id) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let text = render_epiphany_pre_compaction_checkpoint_intervention(&pressure);
|
||||
|
|
@ -19265,6 +19377,43 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_epiphany_crrc_recommendation_continues_after_accepted_resume_finding() {
|
||||
let pressure = map_epiphany_pressure(None);
|
||||
let decision = ThreadEpiphanyReorientDecision {
|
||||
action: ThreadEpiphanyReorientAction::Resume,
|
||||
checkpoint_status: ThreadEpiphanyReorientCheckpointStatus::ResumeReady,
|
||||
checkpoint_id: Some("ix-accepted-resume".to_string()),
|
||||
pressure_level: pressure.level,
|
||||
retrieval_status: ThreadEpiphanyRetrievalFreshnessStatus::Ready,
|
||||
graph_status: ThreadEpiphanyGraphFreshnessStatus::Ready,
|
||||
watcher_status: ThreadEpiphanyInvalidationStatus::Clean,
|
||||
reasons: Vec::new(),
|
||||
checkpoint_dirty_paths: Vec::new(),
|
||||
checkpoint_changed_paths: Vec::new(),
|
||||
active_frontier_node_ids: Vec::new(),
|
||||
next_action: "Continue from the accepted result.".to_string(),
|
||||
note: "accepted resume".to_string(),
|
||||
};
|
||||
|
||||
let recommendation = map_epiphany_crrc_recommendation(
|
||||
true,
|
||||
ThreadEpiphanyReorientStateStatus::Ready,
|
||||
&pressure,
|
||||
&decision,
|
||||
ThreadEpiphanyReorientResultStatus::Completed,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(recommendation.action, ThreadEpiphanyCrrcAction::Continue);
|
||||
assert_eq!(
|
||||
recommendation.recommended_scene_action,
|
||||
Some(ThreadEpiphanySceneAction::Reorient)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_epiphany_roles_projects_mvp_ownership_lanes() {
|
||||
let state = codex_protocol::protocol::EpiphanyThreadState {
|
||||
|
|
@ -19425,6 +19574,8 @@ mod tests {
|
|||
&recommendation,
|
||||
&roles,
|
||||
&signals,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
|
|
@ -19465,6 +19616,8 @@ mod tests {
|
|||
&recommendation,
|
||||
&roles,
|
||||
&signals,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
|
|
@ -19478,6 +19631,46 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_epiphany_coordinator_does_not_recompact_after_accepted_resume_reorient() {
|
||||
let pressure = map_epiphany_pressure(Some(&CoreTokenUsageInfo {
|
||||
total_token_usage: codex_protocol::protocol::TokenUsage {
|
||||
total_tokens: 92,
|
||||
..Default::default()
|
||||
},
|
||||
last_token_usage: codex_protocol::protocol::TokenUsage::default(),
|
||||
model_context_window: Some(200),
|
||||
model_auto_compact_token_limit: Some(100),
|
||||
}));
|
||||
let recommendation = ThreadEpiphanyCrrcRecommendation {
|
||||
action: ThreadEpiphanyCrrcAction::Continue,
|
||||
recommended_scene_action: Some(ThreadEpiphanySceneAction::Reorient),
|
||||
reason: "accepted resume finding".to_string(),
|
||||
};
|
||||
let signals = coordinator_signals(
|
||||
ThreadEpiphanyCrrcAction::Continue,
|
||||
ThreadEpiphanyReorientResultStatus::Completed,
|
||||
ThreadEpiphanyRoleResultStatus::BackendMissing,
|
||||
ThreadEpiphanyRoleResultStatus::BackendMissing,
|
||||
);
|
||||
|
||||
let decision = map_epiphany_coordinator(
|
||||
ThreadEpiphanyReorientStateStatus::Ready,
|
||||
true,
|
||||
&pressure,
|
||||
&recommendation,
|
||||
&[],
|
||||
&signals,
|
||||
false,
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
decision.action,
|
||||
ThreadEpiphanyCoordinatorAction::ContinueImplementation
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_epiphany_coordinator_launches_reorient_worker_from_crrc() {
|
||||
let pressure = map_epiphany_pressure(None);
|
||||
|
|
@ -19501,6 +19694,8 @@ mod tests {
|
|||
&recommendation,
|
||||
&roles,
|
||||
&signals,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
|
|
@ -19541,6 +19736,8 @@ mod tests {
|
|||
&recommendation,
|
||||
&roles,
|
||||
&signals,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
|
|
@ -19577,6 +19774,8 @@ mod tests {
|
|||
&recommendation,
|
||||
&roles,
|
||||
&missing,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
assert_eq!(
|
||||
launch_modeling.action,
|
||||
|
|
@ -19600,6 +19799,8 @@ mod tests {
|
|||
&recommendation,
|
||||
&roles,
|
||||
&modeling_backend_unavailable,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
assert_eq!(
|
||||
relaunch_modeling.action,
|
||||
|
|
@ -19619,6 +19820,8 @@ mod tests {
|
|||
&recommendation,
|
||||
&roles,
|
||||
&modeling_done,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
assert_eq!(
|
||||
launch_verification.action,
|
||||
|
|
@ -19642,6 +19845,8 @@ mod tests {
|
|||
&recommendation,
|
||||
&roles,
|
||||
&verification_done,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
assert_eq!(
|
||||
review_verification.action,
|
||||
|
|
@ -19649,6 +19854,22 @@ mod tests {
|
|||
);
|
||||
assert!(review_verification.requires_review);
|
||||
|
||||
let accepted_verification = map_epiphany_coordinator(
|
||||
ThreadEpiphanyReorientStateStatus::Ready,
|
||||
true,
|
||||
&pressure,
|
||||
&recommendation,
|
||||
&roles,
|
||||
&verification_done,
|
||||
true,
|
||||
false,
|
||||
);
|
||||
assert_eq!(
|
||||
accepted_verification.action,
|
||||
ThreadEpiphanyCoordinatorAction::ContinueImplementation
|
||||
);
|
||||
assert!(!accepted_verification.requires_review);
|
||||
|
||||
let reviewed = coordinator_signals(
|
||||
ThreadEpiphanyCrrcAction::Continue,
|
||||
ThreadEpiphanyReorientResultStatus::MissingBinding,
|
||||
|
|
@ -19662,6 +19883,8 @@ mod tests {
|
|||
&recommendation,
|
||||
&[],
|
||||
&reviewed,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
assert_eq!(
|
||||
continue_implementation.action,
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ Inspect source before you trust the model; when the map feels warm but the sourc
|
|||
Name the living seam, the open wound, and the next safe modeling move in plain language.
|
||||
Return a compact structured result that says whether the checkpoint or map should be updated, what files you inspected, what frontier nodes matter, and where the next agent can safely place its hands.
|
||||
Omit `statePatch` when no durable state change is needed. When the map, frontier, scratch, or checkpoint should change, include `statePatch`: a reviewable `thread/epiphany/update` patch using only modeling-safe fields (`graphs`, `graphFrontier`, `graphCheckpoint`, `scratch`, `investigationCheckpoint`, plus optional valid `observations` and `evidence`). Do not return an observations-only patch. Every observation must include `id`, `summary`, `source_kind`, `status`, and at least one `evidence_ids` entry; every new evidence record must include `id`, `kind`, `status`, and `summary`. For graph growth, return the full replacement graph object with the new or revised nodes/edges already woven into the current anatomy.
|
||||
Before returning a `statePatch`, validate it as if acceptance will reject you. `graphs.architecture.nodes[].id` defines the only valid `architecture_node_id` values. `graphs.dataflow.nodes[].id` defines the only valid `dataflow_node_id` values. Every `graphs.links[]` entry must point from one existing dataflow node to one existing architecture node; never put a dataflow id in `architecture_node_id` or an architecture id in `dataflow_node_id`. If a concept needs to exist in both layers, create or reuse one node in each layer and link them explicitly. Every frontier/checkpoint node id you name must exist in the graph you return.
|
||||
Do not edit files, do not implement product code, do not verify as if you were the reviewer, do not change jobs/subgoals/objective/invariants/churn/mode, and do not promote or accept your own output.
|
||||
'''
|
||||
|
||||
|
|
@ -14,6 +15,7 @@ Act as the Epiphany verification/review specialist for one bounded pass.
|
|||
Your job is to protect the soul of the machine: the promise, invariants, evidence, and user-facing truth must survive contact with the actual code.
|
||||
Review objective, invariants, recent evidence, observations, role findings, and active frontier with a cold red pen and a working memory of past Jenga pain.
|
||||
Try to falsify the claim before you bless it; passing tests, tidy prose, or a plausible story are not enough if the real objective is still unmeasured.
|
||||
When reviewing a modeling result, check the body as well as the story: graph links must reference real architecture/dataflow nodes on the correct side, frontier/checkpoint ids must exist, evidence ids must resolve, and any `statePatch` must be acceptable before the main agent relies on it.
|
||||
Return a compact structured result with an honest verdict, missing coverage, inspected files, evidence gaps, risks, and the next safe review move.
|
||||
Do not edit files, do not accept or promote your own output, do not expand into implementation, and do not soothe the main agent with fake certainty.
|
||||
'''
|
||||
|
|
|
|||
|
|
@ -50,6 +50,7 @@ pub(crate) enum ThreadListenerCommand {
|
|||
#[derive(Default, Clone)]
|
||||
pub(crate) struct TurnSummary {
|
||||
pub(crate) started_at: Option<i64>,
|
||||
pub(crate) context_compaction_started: bool,
|
||||
pub(crate) file_change_started: HashSet<String>,
|
||||
pub(crate) command_execution_started: HashSet<String>,
|
||||
pub(crate) last_error: Option<TurnError>,
|
||||
|
|
|
|||
|
|
@ -53,10 +53,8 @@ fn finalize_active_segment<'a>(
|
|||
// Thread rollback drops the newest surviving real user-message boundaries. In replay, that
|
||||
// means skipping the next finalized segments that contain a non-contextual
|
||||
// `EventMsg::UserMessage`.
|
||||
if *pending_rollback_turns > 0 {
|
||||
if active_segment.counts_as_user_turn {
|
||||
*pending_rollback_turns -= 1;
|
||||
}
|
||||
if *pending_rollback_turns > 0 && active_segment.counts_as_user_turn {
|
||||
*pending_rollback_turns -= 1;
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -93,6 +91,18 @@ fn finalize_active_segment<'a>(
|
|||
}
|
||||
}
|
||||
|
||||
fn is_out_of_band_epiphany_segment(active_segment: &ActiveReplaySegment<'_>) -> bool {
|
||||
active_segment.turn_id.is_none()
|
||||
&& !active_segment.counts_as_user_turn
|
||||
&& active_segment.epiphany_state.is_some()
|
||||
&& active_segment.previous_turn_settings.is_none()
|
||||
&& active_segment.base_replacement_history.is_none()
|
||||
&& matches!(
|
||||
active_segment.reference_context_item,
|
||||
TurnReferenceContextItem::NeverSet
|
||||
)
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub(super) async fn reconstruct_history_from_rollout(
|
||||
&self,
|
||||
|
|
@ -119,6 +129,24 @@ impl Session {
|
|||
let mut active_segment: Option<ActiveReplaySegment<'_>> = None;
|
||||
|
||||
for (index, item) in rollout_items.iter().enumerate().rev() {
|
||||
if active_segment
|
||||
.as_ref()
|
||||
.is_some_and(is_out_of_band_epiphany_segment)
|
||||
&& let Some(active_segment) = active_segment.take()
|
||||
{
|
||||
finalize_active_segment(
|
||||
active_segment,
|
||||
&mut base_replacement_history,
|
||||
&mut previous_turn_settings,
|
||||
&mut reference_context_item,
|
||||
&mut epiphany_state,
|
||||
&mut pending_rollback_turns,
|
||||
);
|
||||
}
|
||||
if epiphany_state.is_some() {
|
||||
break;
|
||||
}
|
||||
|
||||
match item {
|
||||
RolloutItem::Compacted(compacted) => {
|
||||
let active_segment =
|
||||
|
|
|
|||
|
|
@ -210,6 +210,58 @@ async fn record_initial_history_resumed_hydrates_out_of_band_epiphany_state_befo
|
|||
assert_eq!(session.epiphany_state().await, Some(epiphany_state));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn record_initial_history_resumed_hydrates_out_of_band_epiphany_state_after_completed_turn() {
|
||||
let (session, _turn_context) = make_session_and_context().await;
|
||||
let turn_id = "turn-before-control-plane-update".to_string();
|
||||
let turn_state = sample_epiphany_state("turn-before-control-plane-update");
|
||||
let control_plane_state = sample_epiphany_state("control-plane-update");
|
||||
|
||||
session
|
||||
.record_initial_history(InitialHistory::Resumed(ResumedHistory {
|
||||
conversation_id: ThreadId::default(),
|
||||
history: vec![
|
||||
RolloutItem::EventMsg(EventMsg::TurnStarted(
|
||||
codex_protocol::protocol::TurnStartedEvent {
|
||||
turn_id: turn_id.clone(),
|
||||
started_at: None,
|
||||
model_context_window: Some(128_000),
|
||||
collaboration_mode_kind: ModeKind::Default,
|
||||
},
|
||||
)),
|
||||
RolloutItem::EventMsg(EventMsg::UserMessage(
|
||||
codex_protocol::protocol::UserMessageEvent {
|
||||
message: "before control-plane update".to_string(),
|
||||
images: None,
|
||||
local_images: Vec::new(),
|
||||
text_elements: Vec::new(),
|
||||
},
|
||||
)),
|
||||
RolloutItem::EpiphanyState(EpiphanyStateItem {
|
||||
turn_id: Some(turn_id.clone()),
|
||||
state: turn_state,
|
||||
}),
|
||||
RolloutItem::EventMsg(EventMsg::TurnComplete(
|
||||
codex_protocol::protocol::TurnCompleteEvent {
|
||||
turn_id,
|
||||
last_agent_message: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
time_to_first_token_ms: None,
|
||||
},
|
||||
)),
|
||||
RolloutItem::EpiphanyState(EpiphanyStateItem {
|
||||
turn_id: None,
|
||||
state: control_plane_state.clone(),
|
||||
}),
|
||||
],
|
||||
rollout_path: PathBuf::from("resumed.jsonl"),
|
||||
}))
|
||||
.await;
|
||||
|
||||
assert_eq!(session.epiphany_state().await, Some(control_plane_state));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn record_initial_history_resumed_hydrates_previous_turn_settings_from_lifecycle_turn_with_missing_turn_context_id()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -613,7 +613,19 @@ pub(crate) async fn run_agent_job_loop(
|
|||
loop {
|
||||
let mut progressed = false;
|
||||
|
||||
if !cancel_requested && db.is_agent_job_cancelled(job_id.as_str()).await? {
|
||||
if cancel_requested {
|
||||
if clear_cancelled_active_items(
|
||||
session.clone(),
|
||||
db.clone(),
|
||||
job_id.as_str(),
|
||||
&mut active_items,
|
||||
"agent job was cancelled before the worker completed",
|
||||
)
|
||||
.await?
|
||||
{
|
||||
progressed = true;
|
||||
}
|
||||
} else if db.is_agent_job_cancelled(job_id.as_str()).await? {
|
||||
cancel_requested = true;
|
||||
let _ = session
|
||||
.notify_background_event(
|
||||
|
|
@ -621,6 +633,17 @@ pub(crate) async fn run_agent_job_loop(
|
|||
format!("agent job {job_id} cancellation requested; stopping new workers"),
|
||||
)
|
||||
.await;
|
||||
if clear_cancelled_active_items(
|
||||
session.clone(),
|
||||
db.clone(),
|
||||
job_id.as_str(),
|
||||
&mut active_items,
|
||||
"agent job was cancelled before the worker completed",
|
||||
)
|
||||
.await?
|
||||
{
|
||||
progressed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if !cancel_requested && active_items.len() < options.max_concurrency {
|
||||
|
|
@ -972,6 +995,33 @@ async fn reap_stale_active_items(
|
|||
Ok(true)
|
||||
}
|
||||
|
||||
async fn clear_cancelled_active_items(
|
||||
session: Arc<Session>,
|
||||
db: Arc<codex_state::StateRuntime>,
|
||||
job_id: &str,
|
||||
active_items: &mut HashMap<ThreadId, ActiveJobItem>,
|
||||
error_message: &str,
|
||||
) -> anyhow::Result<bool> {
|
||||
if active_items.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
let active: Vec<(ThreadId, String)> = active_items
|
||||
.iter()
|
||||
.map(|(thread_id, item)| (*thread_id, item.item_id.clone()))
|
||||
.collect();
|
||||
for (thread_id, item_id) in active {
|
||||
db.mark_agent_job_item_failed(job_id, item_id.as_str(), error_message)
|
||||
.await?;
|
||||
let _ = session
|
||||
.services
|
||||
.agent_control
|
||||
.shutdown_live_agent(thread_id)
|
||||
.await;
|
||||
active_items.remove(&thread_id);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
async fn finalize_finished_item(
|
||||
session: Arc<Session>,
|
||||
db: Arc<codex_state::StateRuntime>,
|
||||
|
|
|
|||
|
|
@ -204,6 +204,48 @@ WHERE job_id = ? AND item_id = ?
|
|||
row.map(AgentJobItem::try_from).transpose()
|
||||
}
|
||||
|
||||
pub async fn latest_agent_job_item_by_source_id(
|
||||
&self,
|
||||
source_id: &str,
|
||||
) -> anyhow::Result<Option<(AgentJob, AgentJobItem)>> {
|
||||
let row: Option<AgentJobItemRow> = sqlx::query_as::<_, AgentJobItemRow>(
|
||||
r#"
|
||||
SELECT
|
||||
job_id,
|
||||
item_id,
|
||||
row_index,
|
||||
source_id,
|
||||
row_json,
|
||||
status,
|
||||
assigned_thread_id,
|
||||
attempt_count,
|
||||
result_json,
|
||||
last_error,
|
||||
created_at,
|
||||
updated_at,
|
||||
completed_at,
|
||||
reported_at
|
||||
FROM agent_job_items
|
||||
WHERE source_id = ? OR item_id = ?
|
||||
ORDER BY updated_at DESC, created_at DESC
|
||||
LIMIT 1
|
||||
"#,
|
||||
)
|
||||
.bind(source_id)
|
||||
.bind(source_id)
|
||||
.fetch_optional(self.pool.as_ref())
|
||||
.await?;
|
||||
let Some(row) = row else {
|
||||
return Ok(None);
|
||||
};
|
||||
let item = AgentJobItem::try_from(row)?;
|
||||
let job = self
|
||||
.get_agent_job(item.job_id.as_str())
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("agent job {} was missing", item.job_id))?;
|
||||
Ok(Some((job, item)))
|
||||
}
|
||||
|
||||
pub async fn mark_agent_job_running(&self, job_id: &str) -> anyhow::Result<()> {
|
||||
let now = Utc::now().timestamp();
|
||||
sqlx::query(
|
||||
|
|
@ -274,6 +316,7 @@ WHERE id = ?
|
|||
reason: &str,
|
||||
) -> anyhow::Result<bool> {
|
||||
let now = Utc::now().timestamp();
|
||||
let mut tx = self.pool.begin().await?;
|
||||
let result = sqlx::query(
|
||||
r#"
|
||||
UPDATE agent_jobs
|
||||
|
|
@ -288,9 +331,33 @@ WHERE id = ? AND status IN (?, ?)
|
|||
.bind(job_id)
|
||||
.bind(AgentJobStatus::Pending.as_str())
|
||||
.bind(AgentJobStatus::Running.as_str())
|
||||
.execute(self.pool.as_ref())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
Ok(result.rows_affected() > 0)
|
||||
let cancelled = result.rows_affected() > 0;
|
||||
if cancelled {
|
||||
sqlx::query(
|
||||
r#"
|
||||
UPDATE agent_job_items
|
||||
SET
|
||||
status = ?,
|
||||
completed_at = ?,
|
||||
updated_at = ?,
|
||||
last_error = ?,
|
||||
assigned_thread_id = NULL
|
||||
WHERE job_id = ? AND status = ?
|
||||
"#,
|
||||
)
|
||||
.bind(AgentJobItemStatus::Failed.as_str())
|
||||
.bind(now)
|
||||
.bind(now)
|
||||
.bind(reason)
|
||||
.bind(job_id)
|
||||
.bind(AgentJobItemStatus::Running.as_str())
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(cancelled)
|
||||
}
|
||||
|
||||
pub async fn is_agent_job_cancelled(&self, job_id: &str) -> anyhow::Result<bool> {
|
||||
|
|
@ -681,4 +748,49 @@ mod tests {
|
|||
assert_eq!(item.last_error, Some("missing report".to_string()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mark_agent_job_cancelled_fails_running_items() -> anyhow::Result<()> {
|
||||
let codex_home = unique_temp_dir();
|
||||
let runtime = StateRuntime::init(codex_home, "test-provider".to_string()).await?;
|
||||
let (job_id, item_id, _thread_id) =
|
||||
create_running_single_item_job(runtime.as_ref()).await?;
|
||||
|
||||
let cancelled = runtime
|
||||
.mark_agent_job_cancelled(job_id.as_str(), "operator interrupted job")
|
||||
.await?;
|
||||
assert!(cancelled);
|
||||
|
||||
let job = runtime
|
||||
.get_agent_job(job_id.as_str())
|
||||
.await?
|
||||
.expect("job should exist");
|
||||
assert_eq!(job.status, AgentJobStatus::Cancelled);
|
||||
assert_eq!(job.last_error, Some("operator interrupted job".to_string()));
|
||||
|
||||
let item = runtime
|
||||
.get_agent_job_item(job_id.as_str(), item_id.as_str())
|
||||
.await?
|
||||
.expect("job item should exist");
|
||||
assert_eq!(item.status, AgentJobItemStatus::Failed);
|
||||
assert_eq!(item.assigned_thread_id, None);
|
||||
assert_eq!(
|
||||
item.last_error,
|
||||
Some("operator interrupted job".to_string())
|
||||
);
|
||||
assert!(item.completed_at.is_some());
|
||||
|
||||
let progress = runtime.get_agent_job_progress(job_id.as_str()).await?;
|
||||
assert_eq!(
|
||||
progress,
|
||||
AgentJobProgress {
|
||||
total_items: 1,
|
||||
pending_items: 0,
|
||||
running_items: 0,
|
||||
completed_items: 0,
|
||||
failed_items: 1,
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Reference in a new issue