A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
honor /new arguments and keep /goal images (#3560)
Sebastian Müllerd590887681bc
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a546d5a451..40f4a51230 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -353,6 +353,13 @@ jobs:GH_TOKEN: ${{ github.token }}run: |set -euo pipefail+ mkdir -p "${RUNNER_TEMP}/lifecycle-parity-receipts"+ comparison_status=0+ if [ -f scripts/review_new_goal_parity.py ]; then+ PA_COMPACTION_TRACE=stderr RUST_BACKTRACE=1 cargo test --locked -p pa-daemon --lib \+ lazy_build_restores_only_the_pre_admission_prompt_context -- --nocapture \+ 2>&1 | tee "${RUNNER_TEMP}/lifecycle-parity-receipts/new-goal-regression.log" || comparison_status=1+ fireference="${RUNNER_TEMP}/lifecycle-ts-reference"mkdir -p "${reference}"gh release download v0.9.8 --repo "${GITHUB_REPOSITORY}" \@@ -369,8 +376,6 @@ jobs:export PA_E2E_KERNEL_PYTHON="${PRIME_AGENT_KERNEL_PYTHON}"export PYTHONPATH="${reference}/package/skills/goal/src"test -x "${PRIME_AGENT_KERNEL_PYTHON}"- mkdir -p "${RUNNER_TEMP}/lifecycle-parity-receipts"- comparison_status=0# Discover independently added verifiers so feature PRs do not# overwrite or conflict with each other's comparison selection.for verifier in scripts/review_*_parity.py; do@@ -389,7 +394,7 @@ jobs:uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2with:name: lifecycle-parity-receipts-attempt-${{ github.run_attempt }}- path: ${{ runner.temp }}/lifecycle-parity-receipts/*.json+ path: ${{ runner.temp }}/lifecycle-parity-receipts/if-no-files-found: error- name: Run this shard's test subsetif: ${{ !cancelled() && (success() || steps.lifecycle_parity.outcome == 'failure') }}diff --git a/crates/pa-cli/src/print_runtime.rs b/crates/pa-cli/src/print_runtime.rsindex b447fdd95e..aa06d33418 100644--- a/crates/pa-cli/src/print_runtime.rs+++ b/crates/pa-cli/src/print_runtime.rs@@ -1490,6 +1490,7 @@ async fn run_prompts_and_emit(global_harness_dir.clone(),&autonomous_state,&command,+ &images,).await;if let Some(error) = execution.error {diff --git a/crates/pa-cli/src/print_session_command.rs b/crates/pa-cli/src/print_session_command.rsindex 58146d213a..fe63356fbd 100644--- a/crates/pa-cli/src/print_session_command.rs+++ b/crates/pa-cli/src/print_session_command.rs@@ -87,6 +87,7 @@ pub(crate) async fn execute_prompt_session_command(global_harness_dir: std::path::PathBuf,autonomous: &Arc<tokio::sync::Mutex<AutonomousRuntimeState>>,command: &SessionSlashCommand,+ images: &[pa_agent::types::ImageContent],) -> SessionCommandExecution {// The `preparing`/`running` phase frames bookend the durable echo row, and// `/compact`'s `compaction_start` goes out before the summarizer runs.@@ -113,7 +114,7 @@ pub(crate) async fn execute_prompt_session_command(global_harness_dir,autonomous: &mut autonomous,};- execute_session_command(engine, &mut params, command).await+ execute_session_command(engine, &mut params, command, images).await};// `/compact`: the settled `compaction_end` precedes any failure result row; a skip stays silent// beyond the event.@@ -406,6 +407,7 @@ mod tests {bed.harness_dir.clone(),&bed.autonomous,&command(text),+ &[],).await;if execution.error.is_some() {diff --git a/crates/pa-cli/tests/interactive_daemon_e2e.rs b/crates/pa-cli/tests/interactive_daemon_e2e.rsindex 960ec8db1b..dcd07229a3 100644--- a/crates/pa-cli/tests/interactive_daemon_e2e.rs+++ b/crates/pa-cli/tests/interactive_daemon_e2e.rs@@ -3069,6 +3069,164 @@ async fn tui_renames_session_through_slash_command() {assert_eq!(state["sessionName"], "my session");}+// `/new` with arguments (TS `parseNewSessionCommand`): the `--name` value renames+// the new session through the `/name` path, the verbatim suffix submits as the+// initial prompt, and a parse error keeps the draft without creating a session.+#[tokio::test]+async fn tui_new_command_honors_name_and_prompt() {+ let dir = tempfile::TempDir::new().expect("temp dir");+ let agent_dir = dir.path().join("agent");+ let session_dir = agent_dir.join("sessions");+ std::fs::create_dir_all(&session_dir).expect("session dir");+ let supervisor = spawn_supervisor(dir.path());+ // Each created session replays the script from its first response, so one+ // shared reply serves both prompt-bearing runs.+ let script = serde_json::json!({ "engine": "faux", "responses": [+ { "text": "scripted reply" },+ ] });+ std::fs::write(dir.path().join("script.json"), script.to_string()).expect("write script");+ let options = base_options(&supervisor, dir.path(), &session_dir);+ let plan = pa_tui::interactive::HeadlessPlan {+ steps: vec![+ // A parse error must not create a session.+ pa_tui::interactive::HeadlessStep::Submit(+ r#"/new --name "one" --name "two""#.to_string(),+ ),+ pa_tui::interactive::HeadlessStep::WaitIdle { timeout_ms: 30_000 },+ // `--name` plus the `--`-separated initial prompt.+ pa_tui::interactive::HeadlessStep::Submit(+ r#"/new --name "my session" -- do something"#.to_string(),+ ),+ pa_tui::interactive::HeadlessStep::WaitIdle { timeout_ms: 30_000 },+ // A bare suffix is the initial prompt; the session stays unnamed.+ pa_tui::interactive::HeadlessStep::Submit("/new plain prompt".to_string()),+ pa_tui::interactive::HeadlessStep::WaitIdle { timeout_ms: 30_000 },+ // A name without a prompt names the new session and submits nothing.+ pa_tui::interactive::HeadlessStep::Submit("/new --name solo".to_string()),+ pa_tui::interactive::HeadlessStep::WaitIdle { timeout_ms: 30_000 },+ ],+ width: 120,+ height: 36,+ };+ let outcome = run_headless_bounded(options, plan)+ .await+ .expect("interactive run");+ let rendered = outcome.frames.join("\n");+ assert!(+ rendered.contains(r#"Duplicate /new option: "--name""#),+ "the duplicate --name error row rendered:\n{rendered}"+ );+ assert!(+ rendered.contains("do something"),+ "the initial prompt's user message rendered:\n{rendered}"+ );+ assert!(+ rendered.contains("plain prompt"),+ "the bare-suffix prompt's user message rendered:\n{rendered}"+ );+ assert!(+ rendered.contains("scripted reply"),+ "the scripted replies rendered:\n{rendered}"+ );+ // The create arm persists each session's file eagerly, so one file per+ // created session: the startup session plus the three /new runs; the+ // parse error added none.+ let mut files: Vec<(String, String)> = Vec::new();+ for entry in std::fs::read_dir(&session_dir)+ .expect("read session dir")+ .flatten()+ {+ let path = entry.path();+ if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {+ continue;+ }+ let content = std::fs::read_to_string(&path).unwrap_or_default();+ let id = content+ .lines()+ .next()+ .and_then(|header| serde_json::from_str::<serde_json::Value>(header).ok())+ .and_then(|header| header["id"].as_str().map(str::to_string))+ .unwrap_or_default();+ files.push((id, content));+ }+ assert_eq!(files.len(), 4, "the parse error created no session");+ // The name-and-prompt run: its file carries the initial prompt, the+ // scripted reply, and the session_info rename.+ let (named_id, named) = files+ .iter()+ .find(|(_, content)| content.contains("do something"))+ .map(|(id, content)| (id.clone(), content.as_str()))+ .expect("the named run persisted the initial prompt");+ assert!(+ named.contains("scripted reply"),+ "the scripted reply persisted alongside the prompt"+ );+ assert!(+ named.lines().any(|line| {+ serde_json::from_str::<serde_json::Value>(line)+ .is_ok_and(|value| value["type"] == "session_info" && value["name"] == "my session")+ }),+ "the session_info row named the new session"+ );+ // The bare-suffix run: the prompt submitted, the session left unnamed.+ let (_, bare) = files+ .iter()+ .find(|(_, content)| content.contains("plain prompt"))+ .map(|(id, content)| (id.clone(), content.as_str()))+ .expect("the bare-suffix run persisted the initial prompt");+ assert!(+ bare.contains("scripted reply"),+ "the bare-suffix scripted reply persisted"+ );+ assert!(+ bare.lines().all(|line| {+ serde_json::from_str::<serde_json::Value>(line)+ .map_or(true, |value| value["type"] != "session_info")+ }),+ "the bare-suffix session stayed unnamed"+ );+ // The name-only run: named, and no prompt ever submitted.+ let (_, solo) = files+ .iter()+ .find(|(_, content)| {+ content.lines().any(|line| {+ serde_json::from_str::<serde_json::Value>(line)+ .is_ok_and(|value| value["type"] == "session_info" && value["name"] == "solo")+ })+ })+ .map(|(id, content)| (id.clone(), content.as_str()))+ .expect("the name-only run persisted the rename");+ assert!(+ solo.lines().all(|line| {+ serde_json::from_str::<serde_json::Value>(line)+ .map_or(true, |value| value["type"] != "message")+ }),+ "the name-only run submitted no prompt"+ );+ // The daemon state reports the names (the roster summary's field).+ let (client, _client_events) = pa_tui::daemon_client::DaemonClient::connect(&supervisor.socket)+ .await+ .expect("connect");+ let state = client+ .request_ok(DaemonCommand::GetState {+ id: None,+ active_session_id: named_id,+ rest: serde_json::Map::default(),+ })+ .await+ .expect("get_state");+ assert_eq!(state["sessionName"], "my session");+ let state = client+ .request_ok(DaemonCommand::GetState {+ id: None,+ active_session_id: outcome.active_session_id.clone(),+ rest: serde_json::Map::default(),+ })+ .await+ .expect("get_state");+ assert_eq!(state["sessionName"], "solo");+}+#[tokio::test]async fn tui_side_question_pane_flow() {let dir = tempfile::TempDir::new().expect("temp dir");diff --git a/crates/pa-core/src/goals.rs b/crates/pa-core/src/goals.rsindex b1ff61468a..8322c08777 100644--- a/crates/pa-core/src/goals.rs+++ b/crates/pa-core/src/goals.rs@@ -271,15 +271,39 @@ pub fn goal_host_response(goal: &GoalState, include_completion_report: bool) ->pub fn create_goal_context_message(goal: &GoalState,kind: GoalContextKind,+ images: &[pa_agent::types::ImageContent],) -> anyhow::Result<pa_types::session::CustomMessage> {let Some(objective) = &goal.objective else {anyhow::bail!("Cannot create goal context without an objective.");};let prompt = goal_context_prompt(goal, kind);let text = format!("[goal: {}]\n\n{prompt}", kind.label());+ // TS parity (`createGoalContextMessage`): the images attach as content+ // blocks after the text — the row is the turn's only image carrier.+ let content = if images.is_empty() {+ pa_types::ai::UserContent::Text(text)+ } else {+ let mut blocks = vec![pa_types::ai::UserContentBlock::Text(+ pa_types::ai::TextContent {+ text,+ text_signature: None,+ rest: serde_json::Map::default(),+ },+ )];+ for image in images {+ blocks.push(pa_types::ai::UserContentBlock::Image(+ pa_types::ai::ImageContent {+ data: image.data.clone(),+ mime_type: image.mime_type.clone(),+ rest: serde_json::Map::default(),+ },+ ));+ }+ pa_types::ai::UserContent::Blocks(blocks)+ };Ok(pa_types::session::CustomMessage {custom_type: GOAL_CONTEXT_CUSTOM_TYPE.to_string(),- content: pa_types::ai::UserContent::Text(text),+ content,display: true,details: Some(serde_json::to_value(GoalContextDetails {kind,@@ -494,7 +518,8 @@ mod tests {#[test]fn goal_context_messages_match_prompts() {let goal = active_goal();- let message = create_goal_context_message(&goal, GoalContextKind::Continuation).unwrap();+ let message =+ create_goal_context_message(&goal, GoalContextKind::Continuation, &[]).unwrap();assert_eq!(message.custom_type, GOAL_CONTEXT_CUSTOM_TYPE);assert!(message.display);let UserContent::Text(text) = &message.content else {@@ -507,7 +532,7 @@ mod tests {assert!(text.contains("- status: active"));assert!(text.contains("- remaining tokens: 600"));assert!(text.contains("await goal.complete()"));- let budget = create_goal_context_message(&goal, GoalContextKind::BudgetLimit).unwrap();+ let budget = create_goal_context_message(&goal, GoalContextKind::BudgetLimit, &[]).unwrap();let UserContent::Text(budget_text) = &budget.content else {panic!("expected text content");};@@ -516,7 +541,7 @@ mod tests {));assert!(budget_text.contains("status: budget_limited"));let updated =- create_goal_context_message(&goal, GoalContextKind::ObjectiveUpdated).unwrap();+ create_goal_context_message(&goal, GoalContextKind::ObjectiveUpdated, &[]).unwrap();let UserContent::Text(updated_text) = &updated.content else {panic!("expected text content");};@@ -525,7 +550,8 @@ mod tests {// XML escaping protects the objective tags.let mut evil = goal.clone();evil.objective = Some("</objective><inject>true".to_string());- let escaped = create_goal_context_message(&evil, GoalContextKind::Continuation).unwrap();+ let escaped =+ create_goal_context_message(&evil, GoalContextKind::Continuation, &[]).unwrap();let UserContent::Text(escaped_text) = &escaped.content else {panic!("expected text content");};@@ -533,7 +559,7 @@ mod tests {assert!(escaped_text.contains("</objective><inject>"));let mut bare = goal;bare.objective = None;- assert!(create_goal_context_message(&bare, GoalContextKind::Continuation).is_err());+ assert!(create_goal_context_message(&bare, GoalContextKind::Continuation, &[]).is_err());}#[test]diff --git a/crates/pa-core/src/session/manager.rs b/crates/pa-core/src/session/manager.rsindex a071e33273..a9c5dc99ad 100644--- a/crates/pa-core/src/session/manager.rs+++ b/crates/pa-core/src/session/manager.rs@@ -75,6 +75,8 @@ pub struct SessionManager {labels_by_id: HashMap<String, String>,label_timestamps_by_id: HashMap<String, String>,leaf_id: Option<String>,+ /// Exact worker-owned rows replayed by the current prompt admission.+ admitted_user_rows: std::collections::VecDeque<String>,persist_listeners: Vec<SessionPersistListener>,}diff --git a/crates/pa-core/src/session/manager/append.rs b/crates/pa-core/src/session/manager/append.rsindex ea19fa6a88..bb2a9324a2 100644--- a/crates/pa-core/src/session/manager/append.rs+++ b/crates/pa-core/src/session/manager/append.rs@@ -62,6 +62,34 @@ impl SessionManager {Ok(id)}+ /// Register exact durable user rows that the worker already accepted while+ /// the lazy engine built. The current prompt replays them into the agent in+ /// this order; their `MessageEnd` events must reuse these rows rather than+ /// append another copy. This is admission identity, never content deduplication.+ ///+ /// # Errors+ /// An ID does not name a retained user row.+ pub fn replay_admitted_user_rows(&mut self, ids: Vec<String>) -> std::io::Result<()> {+ for id in &ids {+ if !matches!(+ self.retained_entries()+ .iter()+ .find(|entry| entry.id() == Some(id.as_str())),+ Some(FileEntry::Message {+ message: AgentMessage::User(_),+ ..+ })+ ) {+ return Err(std::io::Error::new(+ std::io::ErrorKind::InvalidInput,+ format!("admitted user row {id} is absent from the retained transcript"),+ ));+ }+ }+ self.admitted_user_rows = ids.into();+ Ok(())+ }+/// Append a conversation message with the TS `_appendEntry` retained-write/// contract: a failed disk write keeps the row in the live index (the loop/// already owns it), the error surfacing for logging only.@@ -69,6 +97,18 @@ impl SessionManager {&mut self,message: AgentMessage,) -> (String, Option<std::io::Error>) {+ let admitted = match &message {+ AgentMessage::User(_) => self.admitted_user_rows.pop_front(),+ AgentMessage::Assistant(_)+ | AgentMessage::ToolResult(_)+ | AgentMessage::BashExecution(_)+ | AgentMessage::Custom(_)+ | AgentMessage::BranchSummary(_)+ | AgentMessage::CompactionSummary(_) => None,+ };+ if let Some(id) = admitted {+ return (id, None);+ }if matches!(message, AgentMessage::Assistant(_)) {self.has_assistant_entry = true;}diff --git a/crates/pa-core/src/session/manager/lifecycle.rs b/crates/pa-core/src/session/manager/lifecycle.rsindex 0d4a404900..27e20e1722 100644--- a/crates/pa-core/src/session/manager/lifecycle.rs+++ b/crates/pa-core/src/session/manager/lifecycle.rs@@ -126,6 +126,7 @@ impl SessionManager {labels_by_id: HashMap::new(),label_timestamps_by_id: HashMap::new(),leaf_id: None,+ admitted_user_rows: std::collections::VecDeque::new(),persist_listeners: Vec::new(),};match session_file {@@ -279,6 +280,7 @@ impl SessionManager {/// manager: rows go straight to disk, never deferred behind the/// bootstrap rule.pub fn adopt_window(&mut self, mut window: super::window::WindowedSessionStore) {+ self.admitted_user_rows.clear();// One-copy adoption: the parsed trees move in (no `to_vec` clone); the// window stays attached for its snapshot/settings/metadata state, and// `active_context` walks `file_entries` with the window's settings overlay.@@ -408,6 +410,7 @@ impl SessionManager {},};self.file_entries = vec![header];+ self.admitted_user_rows.clear();self.window = None;self.has_assistant_entry = false;self.by_id.clear();@@ -489,6 +492,7 @@ impl SessionManager {/// replaces every entry with the given chain, and re-indexes so the leaf/// is the last adopted entry. In-memory only — the caller owns persistence.pub fn adopt_entries(&mut self, entries: Vec<FileEntry>) {+ self.admitted_user_rows.clear();// The caller supplies the complete selected branch after explicit navigation.self.window = None;let header = selfdiff --git a/crates/pa-core/src/session/manager/tests.rs b/crates/pa-core/src/session/manager/tests.rsindex 94380ac15e..3f0abcce76 100644--- a/crates/pa-core/src/session/manager/tests.rs+++ b/crates/pa-core/src/session/manager/tests.rs@@ -397,3 +397,68 @@ fn open_treats_a_path_shaped_header_id_as_corrupted() {);}}++/// Replay validation must stay on the retained index: the full-history query+/// panics after window adoption. Replaying a registered row once does not+/// suppress a later legitimate submission of the same text.+#[test]+fn replay_admitted_user_rows_stays_windowed_and_reuses_only_registered_ids() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("session.jsonl");+ let mut rows = vec![serde_json::json!({+ "type":"session", "id":"session", "version":3, "cwd":"/tmp",+ "timestamp":"2026-01-01T00:00:00Z",+ })];+ let mut parent = None;+ for index in 0..220 {+ let id = format!("user-{index}");+ rows.push(serde_json::json!({+ "type":"message", "id":id, "parentId":parent,+ "message":{"role":"user", "content":"repeat this prompt", "timestamp":index},+ }));+ parent = Some(id);+ }+ rows.push(serde_json::json!({+ "type":"compaction", "id":"compacted", "parentId":parent,+ "summary":"earlier turns", "firstKeptEntryId":"user-215", "tokensBefore":9000,+ }));+ rows.push(serde_json::json!({+ "type":"message", "id":"accepted", "parentId":"compacted",+ "message":{"role":"user", "content":"repeat this prompt", "timestamp":220},+ }));+ let bytes = rows+ .iter()+ .map(ToString::to_string)+ .collect::<Vec<_>>()+ .join("\n")+ + "\n";+ std::fs::write(&path, &bytes).unwrap();+ let window = super::super::window::WindowedSessionStore::open(&path)+ .unwrap()+ .expect("windowed transcript");+ let mut manager = SessionManager::in_memory(dir.path());+ manager.adopt_window(window);+ assert!(manager.retained_entries().len() < rows.len());+ let retained = manager.retained_entries().to_vec();+ let message: AgentMessage = serde_json::from_value(serde_json::json!({+ "role":"user", "content":"repeat this prompt", "timestamp":221,+ }))+ .unwrap();+ manager+ .replay_admitted_user_rows(vec!["accepted".to_string()])+ .unwrap();+ let (id, error) = manager.append_message_retained(message.clone());+ assert_eq!(id, "accepted");+ assert!(error.is_none());+ assert_eq!(manager.retained_entries(), retained);+ let (next_id, error) = manager.append_message_retained(message);+ assert_ne!(next_id, "accepted");+ assert!(error.is_none());+ assert_eq!(manager.retained_entries().len(), retained.len() + 1);+ assert!(manager.window.is_some(), "no full-history hydration");+ assert_eq!(+ std::fs::read_to_string(&path).unwrap(),+ bytes,+ "the worker-owned durable file is untouched by mirrored replay"+ );+}diff --git a/crates/pa-core/src/session_engine/admission.rs b/crates/pa-core/src/session_engine/admission.rsindex 44b8ebb8c5..647c5791b8 100644--- a/crates/pa-core/src/session_engine/admission.rs+++ b/crates/pa-core/src/session_engine/admission.rs@@ -46,9 +46,10 @@ impl AgentSession {prompt_messages.extend(self.take_next_turn_rows().await);let custom_row = session_message_to_loop(&SessionAgentMessage::Custom(message.clone())).ok_or_else(|| anyhow::anyhow!("injected custom message conversion failed"))?;- // The dispatch-time routing fires for every dispatched turn; an- // injected row never carries images, so it clears a route left by- // the previous turn.+ // The dispatch-time routing fires for every dispatched turn; injected+ // rows do not re-run the route decision (a goal objective start's+ // images ride the row's content and the row runs on the session's+ // model), so a route left by the previous turn clears here.self.apply_image_model_routing(&[], &[]).await?;prompt_messages.push(custom_row);self.agentdiff --git a/crates/pa-core/src/session_engine/goal_boundary.rs b/crates/pa-core/src/session_engine/goal_boundary.rsindex 6d9b771f6a..9c173ad9eb 100644--- a/crates/pa-core/src/session_engine/goal_boundary.rs+++ b/crates/pa-core/src/session_engine/goal_boundary.rs@@ -45,7 +45,7 @@ impl SessionEngine {let state = driver.start(&mut session, objective, token_budget)?;drop(session);drop(driver);- let context = create_goal_context_message(&state, GoalContextKind::Continuation)?;+ let context = create_goal_context_message(&state, GoalContextKind::Continuation, &[])?;self.session.queue_next_turn_row(context);Ok(true)}@@ -79,6 +79,7 @@ impl SessionEngine {create_goal_context_message(&driver.state_with_creation_elapsed(),GoalContextKind::BudgetLimit,+ &[],).ok()}diff --git a/crates/pa-core/src/session_engine/goal_driver.rs b/crates/pa-core/src/session_engine/goal_driver.rsindex b6b78dcb18..f6da3334d4 100644--- a/crates/pa-core/src/session_engine/goal_driver.rs+++ b/crates/pa-core/src/session_engine/goal_driver.rs@@ -436,9 +436,12 @@ impl GoalDriver {},)?;if next_status == GoalStatus::Active {- return Ok(- create_goal_context_message(&self.state, GoalContextKind::Continuation).ok(),- );+ return Ok(create_goal_context_message(+ &self.state,+ GoalContextKind::Continuation,+ &[],+ )+ .ok());}Ok(None)}@@ -559,7 +562,8 @@ impl GoalDriver {..self.state.clone()},)?;- let message = create_goal_context_message(&self.state, GoalContextKind::Continuation).ok();+ let message =+ create_goal_context_message(&self.state, GoalContextKind::Continuation, &[]).ok();// The mint is owed to the calling surface until it admits the turn; a rollback un-mints it.if message.is_some() {self.mark_continuation_pending();diff --git a/crates/pa-core/src/session_engine/session_commands.rs b/crates/pa-core/src/session_engine/session_commands.rsindex 892b5a9041..d2f30a019c 100644--- a/crates/pa-core/src/session_engine/session_commands.rs+++ b/crates/pa-core/src/session_engine/session_commands.rs@@ -167,6 +167,7 @@ pub async fn execute_session_command(engine: &SessionEngine,params: &mut SessionCommandParams<'_>,command: &SessionSlashCommand,+ images: &[pa_agent::types::ImageContent],) -> SessionCommandExecution {let mut execution = SessionCommandExecution::default();// The echo row is recorded BEFORE the command runs, so the command's@@ -180,7 +181,7 @@ pub async fn execute_session_command(let result = match command.name {"compact" => execute_compact(engine, params, command, &mut execution).await,"refine" => execute_refine(engine, params, command, &mut execution).await,- "goal" => execute_goal(engine, command, &mut execution).await,+ "goal" => execute_goal(engine, command, images, &mut execution).await,"autonomous" => execute_autonomous(params, command, &mut execution),other => Err(format!("Unknown session command: {other}")),};@@ -307,6 +308,7 @@ async fn execute_refine(async fn execute_goal(engine: &SessionEngine,command: &SessionSlashCommand,+ images: &[pa_agent::types::ImageContent],execution: &mut SessionCommandExecution,) -> Result<(), String> {let goal = parse_goal_command(&command.args)?;@@ -361,8 +363,10 @@ async fn execute_goal(let state = driver.start(&mut session, &objective, token_budget).map_err(|error| format!("{error:#}"))?;+ // TS `_startGoal`: only the objective-start context takes the+ // prompt's attached images; the other goal arms ignore them.context_message = Some(- create_goal_context_message(&state, GoalContextKind::Continuation)+ create_goal_context_message(&state, GoalContextKind::Continuation, images).map_err(|error| format!("{error:#}"))?,);}diff --git a/crates/pa-daemon/src/agent_engine.rs b/crates/pa-daemon/src/agent_engine.rsindex 3d60c705f2..efab15e28a 100644--- a/crates/pa-daemon/src/agent_engine.rs+++ b/crates/pa-daemon/src/agent_engine.rs@@ -99,6 +99,14 @@ pub(crate) const QUOTA_WAKE_MAX_RETRIES: u32 = 3;pub(crate) type SettledKernelRelease =std::sync::Arc<dyn Fn() -> futures::future::BoxFuture<'static, ()> + Send + Sync>;+/// A captured prompt boundary: an empty transcript or a stable durable leaf.+/// The owning slot's None means no worker boundary has been supplied.+#[derive(Clone, PartialEq, Eq)]+enum PromptContextBoundary {+ Empty,+ Leaf(String),+}+/// A [`SessionEngine`] running real agent turns.pub struct AgentSessionEngine {pub(crate) runtime: crate::async_safe_runtime::AsyncSafeRuntime,@@ -201,6 +209,8 @@ pub struct AgentSessionEngine {/// A branch move that landed before the first turn: consumed at build so/// the session starts on the moved branch.pending_branch: std::sync::Mutex<Option<Vec<pa_types::session::FileEntry>>>,+ /// The worker's captured pre-admission boundary; None means unset.+ prompt_context_boundary: std::sync::Mutex<Option<PromptContextBoundary>>,/// The `goal_update` payload a branch rebuild's goal reload stashed,/// taken by the worker that announces it. `None` when it changed nothing.reloaded_goal_update: std::sync::Mutex<Option<Value>>,diff --git a/crates/pa-daemon/src/agent_engine/lifecycle.rs b/crates/pa-daemon/src/agent_engine/lifecycle.rsindex a320932e1b..fc2be0556b 100644--- a/crates/pa-daemon/src/agent_engine/lifecycle.rs+++ b/crates/pa-daemon/src/agent_engine/lifecycle.rs@@ -8,9 +8,9 @@ use super::{register_agent_message_host_handlers, register_agent_observe_host_handlers,switchable_stream_fn, AgentEngineConfig, AgentSessionEngine, Arc, CoreSessionEngine,EngineModelSelection, HostRequestHandlers, LinkAgentMessageController,- LinkAgentObserveController, Model, OverflowRecovery, ProducerUsageSink, ProviderTarget,- QuotaParkState, SessionCommandExecution, SessionCommandParams, SessionEngineConfig,- SupervisorChildSessions, Value,+ LinkAgentObserveController, Model, OverflowRecovery, ProducerUsageSink, PromptContextBoundary,+ ProviderTarget, QuotaParkState, SessionCommandExecution, SessionCommandParams,+ SessionEngineConfig, SupervisorChildSessions, Value,};/// The instruction the floor appends to a bare skill invocation: ask what@@ -162,6 +162,7 @@ impl AgentSessionEngine {)),session_build: tokio::sync::Mutex::new(()),pending_branch: std::sync::Mutex::new(None),+ prompt_context_boundary: std::sync::Mutex::new(None),provider_target: std::sync::Arc::new(std::sync::RwLock::new(None)),image_route: std::sync::Mutex::new(None),reload_lock: std::sync::Mutex::new(()),@@ -474,6 +475,92 @@ impl AgentSessionEngine {shared_branch = branch;}}+ // The worker persisted accepted rows while this lazy session built.+ // Keep its whole durable window, but seed the loop only through the+ // stable pre-admission leaf. Content/timestamps are never deduplicated.+ let prompt_context_boundary = self+ .prompt_context_boundary+ .lock()+ .expect("prompt context boundary lock")+ .clone();+ let entries = pending_branch+ .as_deref()+ .or_else(|| {+ shared_window+ .as_ref()+ .map(pa_core::session::window::WindowedSessionStore::entries)+ })+ .or(shared_branch.as_deref());+ let mut admitted_user_ids = Vec::new();+ if std::env::var_os("PA_COMPACTION_TRACE").is_some() {+ pa_core::session_engine::compaction_trace::trace(+ "daemon.lazy_restore_boundary",+ &serde_json::json!({+ "kind": match &prompt_context_boundary {+ Some(PromptContextBoundary::Empty) => "empty",+ Some(PromptContextBoundary::Leaf(_)) => "leaf",+ None => "unset",+ },+ "retainedUserRows": entries.map_or(0, |entries| entries.iter().filter(|entry|+ matches!(entry, pa_types::session::FileEntry::Message {+ message: pa_types::session::AgentMessage::User(_), ..+ })).count()),+ }),+ );+ }+ let prompt_context = match prompt_context_boundary.as_ref() {+ Some(boundary) => {+ let mut after_boundary = matches!(boundary, PromptContextBoundary::Empty);+ if let Some(entries) = entries {+ for entry in entries {+ if after_boundary {+ if let Some(id) = entry.id().filter(|_| {+ matches!(+ entry,+ pa_types::session::FileEntry::Message {+ message: pa_types::session::AgentMessage::User(_),+ ..+ }+ )+ }) {+ admitted_user_ids.push(id.to_string());+ }+ } else if matches!(boundary, PromptContextBoundary::Leaf(leaf)+ if entry.id() == Some(leaf.as_str()))+ {+ after_boundary = true;+ }+ }+ }+ match boundary {+ PromptContextBoundary::Leaf(leaf) => {+ anyhow::ensure!(+ after_boundary,+ "prompt context boundary {leaf} is absent from the retained transcript"+ );+ Some(+ pa_core::session::build_session_context(+ entries.expect("a found boundary has entries"),+ Some(leaf),+ )+ .messages,+ )+ }+ PromptContextBoundary::Empty => Some(Vec::new()),+ }+ }+ None => None,+ };+ if std::env::var_os("PA_COMPACTION_TRACE").is_some() {+ pa_core::session_engine::compaction_trace::trace(+ "daemon.lazy_restore_context",+ &serde_json::json!({+ "priorUserRows": prompt_context.as_ref().map(|messages| messages.iter().filter(|message|+ matches!(message, pa_types::session::AgentMessage::User(_))).count()),+ "replayedUserRows": admitted_user_ids.len(),+ }),+ );+ }if let Some(state) = seed {// The restore-resurrection guard: an active seed whose// trailing turn settled as a terminal provider failure adopts@@ -531,10 +618,24 @@ impl AgentSessionEngine {}if let Some(entries) = pending_branch {built.session.rebuild_branch_context(entries).await?;+ built+ .session+ .shared_persistence()+ .lock()+ .await+ .replay_admitted_user_rows(admitted_user_ids)?;+ if let Some(messages) = prompt_context {+ built+ .session+ .agent()+ .set_messages(messages.iter().filter_map(json_round_trip).collect())+ .await;+ }// A moved branch restores its own park (the early return would leave the previous// branch's park armed).self.restore_quota_park(built).await;self.flush_pending_stale_goal_terminal().await;+ self.finish_prompt_context_adoption(prompt_context_boundary.as_ref());return Ok(());}// Restore the retained context and certified metadata without loading discarded bodies.@@ -554,13 +655,39 @@ impl AgentSessionEngine {built.session.rebuild_branch_context(entries).await?;self.flush_pending_stale_goal_terminal().await;}+ built+ .session+ .shared_persistence()+ .lock()+ .await+ .replay_admitted_user_rows(admitted_user_ids)?;+ if let Some(messages) = prompt_context {+ built+ .session+ .agent()+ .set_messages(messages.iter().filter_map(json_round_trip).collect())+ .await;+ }self.restore_quota_park(built).await;// The walk and replay allocated transient trees several times the// retained size: release the freed heap.pa_types::memory_release::trim_freed_heap();+ self.finish_prompt_context_adoption(prompt_context_boundary.as_ref());Ok(())}+ /// Clear only the boundary this completed adoption observed. A failed+ /// build keeps it for the demand retry, and a newer captured leaf survives.+ fn finish_prompt_context_adoption(&self, adopted: Option<&PromptContextBoundary>) {+ let mut current = self+ .prompt_context_boundary+ .lock()+ .expect("prompt context boundary lock");+ if current.as_ref() == adopted {+ *current = None;+ }+ }+/// Scan the branch entries for the park this branch ended on and re-arm the live park state./// A previous build's park is cleared first, so it never survives onto a/// branch that did not park.@@ -627,6 +754,10 @@ impl AgentSessionEngine {pub(crate) async fn retire_session_runtime(&self) {let _build = self.session_build.lock().await;let built = self.session.lock().await.take();+ *self+ .prompt_context_boundary+ .lock()+ .expect("prompt context boundary lock") = None;*self.quota_park.lock()@@ -767,6 +898,7 @@ impl AgentSessionEngine {pub(crate) fn execute_session_command(&self,command: &pa_core::session_engine::slash_commands::SessionSlashCommand,+ images: &[pa_agent::types::ImageContent],) -> anyhow::Result<SessionCommandExecution> {let model = self.session_model()?;self.ensure_core_session(&model)?;@@ -787,7 +919,7 @@ impl AgentSessionEngine {.expect("session built by ensure_core_session");Ok(self.runtime- .block_on(async { execute_session_command(&core, &mut params, command).await }))+ .block_on(async { execute_session_command(&core, &mut params, command, images).await }))}/// The current explicit selection (create-config flags over thediff --git a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs b/crates/pa-daemon/src/agent_engine/session_engine_impl.rsindex dd3a5a3f90..01fac0aade 100644--- a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs+++ b/crates/pa-daemon/src/agent_engine/session_engine_impl.rs@@ -6,8 +6,8 @@ use super::{artifact_reference, json, map_thinking_level, now_millis, AgentSessionEngine, Arc,BranchSummaryOutcome, BranchSummaryRequest, BranchSummaryRun, CompactionOutcome,CompactionRequest, CompactionRun, EngineEvent, EngineModelSelection, ParentIdentity,- PromptRequest, ProviderTarget, SessionEngine, SideQuestionOutcome, SideQuestionRequest,- StartupScope, TurnPrompt, Value, DEFAULT_RLM_MAX_DEPTH,+ PromptContextBoundary, PromptRequest, ProviderTarget, SessionEngine, SideQuestionOutcome,+ SideQuestionRequest, StartupScope, TurnPrompt, Value, DEFAULT_RLM_MAX_DEPTH,};impl SessionEngine for AgentSessionEngine {@@ -256,6 +256,28 @@ impl SessionEngine for AgentSessionEngine {.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(path);}+ fn set_prompt_context_boundary(&self, leaf_id: Option<String>) {+ let boundary = match leaf_id {+ Some(leaf) => PromptContextBoundary::Leaf(leaf),+ None => PromptContextBoundary::Empty,+ };+ if std::env::var_os("PA_COMPACTION_TRACE").is_some() {+ pa_core::session_engine::compaction_trace::trace(+ "daemon.prompt_boundary",+ &json!({+ "kind": match &boundary {+ PromptContextBoundary::Empty => "empty",+ PromptContextBoundary::Leaf(_) => "leaf",+ },+ }),+ );+ }+ *self+ .prompt_context_boundary+ .lock()+ .expect("prompt context boundary lock") = Some(boundary);+ }+/// Restore through the bounded readiness wait. An explicit create flag/// wins; a failed restore is never silent/// ([`Self::model_fallback_message`]).@@ -918,6 +940,21 @@ impl SessionEngine for AgentSessionEngine {/// The worker's turn completed: release child prompt tasks waiting on the boundary.fn on_turn_done(&self) {+ *self+ .prompt_context_boundary+ .lock()+ .expect("prompt context boundary lock") = None;+ self.runtime.block_on(async {+ let core = self.session.lock().await.clone();+ if let Some(core) = core {+ core.session+ .shared_persistence()+ .lock()+ .await+ .replay_admitted_user_rows(Vec::new())+ .expect("clearing admitted rows cannot fail");+ }+ });if let Some(children) = &self.children {children.notify_turn_done();}@@ -1294,9 +1331,12 @@ impl SessionEngine for AgentSessionEngine {if let Some(command) =crate::session_commands::parse_prompt_session_command(&request.message){- let Some(execution) =- crate::session_commands::run_session_command(self, &command, &mut emit)- else {+ let Some(execution) = crate::session_commands::run_session_command(+ self,+ &command,+ &request.images,+ &mut emit,+ ) else {return;};if let Some(error) = &execution.error {diff --git a/crates/pa-daemon/src/agent_engine/tests/goal.rs b/crates/pa-daemon/src/agent_engine/tests/goal.rsindex b4b2577ee7..79f2a8e52a 100644--- a/crates/pa-daemon/src/agent_engine/tests/goal.rs+++ b/crates/pa-daemon/src/agent_engine/tests/goal.rs@@ -94,6 +94,78 @@ fn recovery_rebuild_rehydrates_the_goal_from_the_session_file() {);}+/// The `/goal` objective start keeps the prompt's attached images on the+/// injected context row (TS `createGoalContextMessage`: text first, images+/// after) — the row is the turn's only image carrier, session commands+/// never admit a user row.+#[test]+fn goal_start_keeps_the_prompt_images_on_the_context_row() {+ let _faux = FAUX_TEST_LOCK+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let dir = tempfile::TempDir::new().unwrap();+ let engine = std::sync::Arc::new(+ AgentSessionEngine::new(AgentEngineConfig {+ cwd: dir.path().to_path_buf(),+ agent_dir: dir.path().join("agent"),+ provider: None,+ model: None,+ api_key: None,+ thinking: None,+ session_dir: None,+ session_file: None,+ faux_script: Some(r#"{"responses": [{"text": "goal reply"}]}"#.to_string()),+ supervisor_link: None,+ telemetry_disabled: None,+ cron_store: None,+ queued_steering_probe: None,+ })+ .unwrap(),+ );+ let mut events: Vec<EngineEvent> = Vec::new();+ engine.run_prompt(+ 0,+ PromptRequest {+ batch: Vec::new(),+ images: vec![pa_agent::types::ImageContent {+ data: "aGVsbG8gZ29hbA==".to_string(),+ mime_type: "image/png".to_string(),+ }],+ message: "/goal describe the attachment".to_string(),+ source: "user".to_string(),+ agent_message_id: None,+ custom_message: None,+ },+ &|| false,+ &mut |event| {+ events.push(event);+ true+ },+ );+ let context = events+ .iter()+ .find_map(|event| match event {+ EngineEvent::CustomMessage(value) if value["customType"] == "goal_context" => {+ Some(value.clone())+ }+ _ => None,+ })+ .expect("the goal start emitted its context row");+ let blocks = context["content"]+ .as_array()+ .expect("the context row carries the attached image as content blocks");+ assert_eq!(blocks[0]["type"], "text");+ let text = blocks[0]["text"].as_str().expect("text block content");+ assert!(+ text.contains("[goal: continuation]") && text.contains("describe the attachment"),+ "the continuation prompt names the objective: {text}"+ );+ assert_eq!(+ blocks[1],+ json!({ "type": "image", "data": "aGVsbG8gZ29hbA==", "mimeType": "image/png" })+ );+}+/// A durable message row in the worker's persisted wire shape.fn wire_user_message(text: String) -> Value {serde_json::to_value(pa_types::session::AgentMessage::User(diff --git a/crates/pa-daemon/src/agent_engine/tests/streaming.rs b/crates/pa-daemon/src/agent_engine/tests/streaming.rsindex a182cd611b..ee70f6af7b 100644--- a/crates/pa-daemon/src/agent_engine/tests/streaming.rs+++ b/crates/pa-daemon/src/agent_engine/tests/streaming.rs@@ -187,3 +187,161 @@ fn agent_engine_streams_updates_and_final_message() {assert_eq!(message["stopReason"], "stop");assert_eq!(events.last(), Some(&EngineEvent::Done(Ok(()))));}++/// The worker persists the accepted row before the lazy core builds. Its+/// pre-admission leaf must keep that row out of restored model history, while+/// repeated text and image blocks remain distinct turns after a runtime rebuild.+#[test]+fn lazy_build_restores_only_the_pre_admission_prompt_context() {+ let _faux = FAUX_TEST_LOCK+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let dir = tempfile::TempDir::new().unwrap();+ let path = dir.path().join("session.jsonl");+ let mut store =+ crate::session_store::SessionFile::create(dir.path().to_str().unwrap(), None, 0);+ store.set_path(path.clone());+ store.rewrite().expect("initialize worker-owned transcript");+ let engine = AgentSessionEngine::new(AgentEngineConfig {+ cwd: dir.path().to_path_buf(),+ agent_dir: dir.path().join("agent"),+ provider: None,+ model: None,+ api_key: None,+ thinking: None,+ session_dir: None,+ session_file: Some(path),+ faux_script: Some(+ r#"{"responses":[{"text":"first"},{"text":"second"},{"text":"restored"}]}"#.to_string(),+ ),+ supervisor_link: None,+ telemetry_disabled: None,+ cron_store: None,+ queued_steering_probe: None,+ })+ .unwrap();+ let expected_content = json!([+ { "type": "text", "text": "repeat this exact prompt" },+ { "type": "image", "mimeType": "image/png", "data": "QUJD" },+ ]);+ for prompt_index in 0..3 {+ if prompt_index == 2 {+ engine.runtime.block_on(engine.retire_session_runtime());+ }+ engine.set_prompt_context_boundary(store.leaf_id().map(str::to_string));+ let mut accepted = false;+ let mut model_user_content = None;+ let mut result = None;+ engine.run_prompt(+ prompt_index,+ PromptRequest {+ batch: Vec::new(),+ images: vec![pa_agent::types::ImageContent {+ data: "QUJD".to_string(),+ mime_type: "image/png".to_string(),+ }],+ message: "repeat this exact prompt".to_string(),+ source: "user".to_string(),+ agent_message_id: None,+ custom_message: None,+ },+ &|| false,+ &mut |event| {+ match event {+ EngineEvent::UserMessage(message) => {+ if prompt_index != 1 {+ assert!(+ engine.session.blocking_lock().is_none(),+ "accepted prompt must render before the lazy session builds"+ );+ }+ accepted = true;+ store+ .persist_entry("message", json!({ "message": message }))+ .expect("worker persists accepted prompt");+ }+ EngineEvent::AssistantMessage(message)+ | EngineEvent::ToolResultMessage(message) => {+ store+ .persist_entry("message", json!({ "message": message }))+ .expect("worker persists settled message");+ }+ EngineEvent::AgentEnd { messages } => {+ model_user_content = Some(+ messages+ .into_iter()+ .filter(|message| message["role"] == "user")+ .map(|message| message["content"].clone())+ .collect::<Vec<_>>(),+ );+ }+ EngineEvent::Done(done) => result = Some(done),+ _ => {}+ }+ true+ },+ );+ engine.on_turn_done();+ assert!(accepted);+ assert_eq!(result, Some(Ok(())));+ assert_eq!(+ model_user_content,+ Some(vec![expected_content.clone()]),+ "each run emits exactly its own admitted prompt/image pair"+ );+ let core = engine.session.blocking_lock().clone().expect("core built");+ let live_content = engine.runtime.block_on(async {+ core.session+ .agent()+ .state()+ .await+ .messages+ .into_iter()+ .filter_map(|message| match message {+ pa_agent::types::AgentMessage::Standard(pa_agent::types::Message::User(+ user,+ )) => Some(+ serde_json::to_value(user).expect("user serializes")["content"].clone(),+ ),+ _ => None,+ })+ .collect::<Vec<_>>()+ });+ assert_eq!(+ live_content,+ vec![expected_content.clone(); prompt_index + 1],+ "live model history keeps each repeated prompt/image pair once"+ );+ let persistence = core.session.shared_persistence();+ let inner = persistence.blocking_lock();+ let is_user = |entry: &&pa_types::session::FileEntry| {+ matches!(+ entry,+ pa_types::session::FileEntry::Message {+ message: pa_types::session::AgentMessage::User(_),+ ..+ }+ )+ };+ assert_eq!(+ inner.retained_entries().iter().filter(is_user).count(),+ prompt_index + 1,+ "inner retained history must not double append the accepted row"+ );+ assert_eq!(+ inner+ .active_context()+ .messages+ .iter()+ .filter(|message| matches!(message, pa_types::session::AgentMessage::User(_)))+ .count(),+ prompt_index + 1,+ "compact/refine context must retain each repeated prompt once"+ );+ assert_eq!(+ store.branch_file_entries().iter().filter(is_user).count(),+ prompt_index + 1,+ "the worker-owned durable branch remains single-copy"+ );+ }+}diff --git a/crates/pa-daemon/src/agent_engine/turn/run_once.rs b/crates/pa-daemon/src/agent_engine/turn/run_once.rsindex 720ab13921..98a76510f9 100644--- a/crates/pa-daemon/src/agent_engine/turn/run_once.rs+++ b/crates/pa-daemon/src/agent_engine/turn/run_once.rs@@ -330,6 +330,17 @@ impl AgentSessionEngine {// dogfood failure); the Arc clone keeps reads free.let session = self.session.lock().await.clone();let engine = session.expect("session built");+ if std::env::var_os("PA_COMPACTION_TRACE").is_some() {+ let state = engine.session.agent().state().await;+ pa_core::session_engine::compaction_trace::trace(+ "daemon.before_prompt_admission",+ &json!({+ "liveUserRows": state.messages.iter().filter(|message|+ matches!(message, pa_agent::types::AgentMessage::Standard(+ pa_agent::types::Message::User(_)))).count(),+ }),+ );+ }match &prompt {// A plain turn admits a user prompt; an injected turn admits the// custom row itself — ONE representation.diff --git a/crates/pa-daemon/src/compact_autorefine.rs b/crates/pa-daemon/src/compact_autorefine.rsindex 046909bb99..0f6849661e 100644--- a/crates/pa-daemon/src/compact_autorefine.rs+++ b/crates/pa-daemon/src/compact_autorefine.rs@@ -426,6 +426,7 @@ mod tests {let execution = crate::session_commands::run_session_command(&engine,&refine_command(),+ &[],&mut |event| {events.push(event);true@@ -467,10 +468,15 @@ mod tests {let (engine, _dir) =trigger_engine(&json!({ "responses": [ {"text": "not json"} ] }), 1, true);let mut events: Vec<EngineEvent> = Vec::new();- crate::session_commands::run_session_command(&engine, &refine_command(), &mut |event| {- events.push(event);- true- });+ crate::session_commands::run_session_command(+ &engine,+ &refine_command(),+ &[],+ &mut |event| {+ events.push(event);+ true+ },+ );let errors: Vec<String> = events.iter().filter_map(|event| match event {diff --git a/crates/pa-daemon/src/engine.rs b/crates/pa-daemon/src/engine.rsindex 890684d73f..fd94870eb8 100644--- a/crates/pa-daemon/src/engine.rs+++ b/crates/pa-daemon/src/engine.rs@@ -226,6 +226,11 @@ pub trait SessionEngine: Send + Sync {let _ = path;}+ /// Capture the worker-owned durable leaf before the current prompt rows+ /// persist. Lazy engines restore model context only through this boundary;+ /// admission supplies the current rows once. This must not build a session.+ fn set_prompt_context_boundary(&self, _leaf_id: Option<String>) {}+/// A session being revived restores the model its file pins before the/// startup chain, so it does not silently land on the startup-chain/// default. `saved` skips a second windowed open; `None` reads the file.diff --git a/crates/pa-daemon/src/goal_continuation.rs b/crates/pa-daemon/src/goal_continuation.rsindex a7c1cd1d4b..77f5dd4182 100644--- a/crates/pa-daemon/src/goal_continuation.rs+++ b/crates/pa-daemon/src/goal_continuation.rs@@ -396,6 +396,7 @@ impl AgentSessionEngine {pa_core::goals::create_goal_context_message(&state,pa_core::goals::GoalContextKind::BudgetLimit,+ &[],).ok()})?;diff --git a/crates/pa-daemon/src/rpc/prompt_commands.rs b/crates/pa-daemon/src/rpc/prompt_commands.rsindex b745a5e28e..3dbaf6eb60 100644--- a/crates/pa-daemon/src/rpc/prompt_commands.rs+++ b/crates/pa-daemon/src/rpc/prompt_commands.rs@@ -38,7 +38,7 @@ pub async fn prompt(state: &Arc<RpcState>, payload: &Value) -> Result<ResponseDa.session.prompt_with_images(message,- images,+ images.clone(),PromptOptions {streaming_behavior: behavior,return_after_accepted: true,@@ -60,8 +60,15 @@ pub async fn prompt(state: &Arc<RpcState>, payload: &Value) -> Result<ResponseDa// would deadlock.let model = handle.model.clone();let api_key = handle.api_key.clone();- let command_result =- run_session_command(state.as_ref(), engine.clone(), &command, model, api_key).await;+ let command_result = run_session_command(+ state.as_ref(),+ engine.clone(),+ &command,+ model,+ api_key,+ &images,+ )+ .await;drop(handle);// The pump is scheduled only after the command settles: an earlier// kick would deliver parked rows into the rebuild's window.@@ -102,6 +109,7 @@ async fn run_session_command(command: &pa_core::session_engine::slash_commands::SessionSlashCommand,model: pa_types::ai::Model,api_key: Option<String>,+ images: &[pa_agent::types::ImageContent],) -> Result<(), String> {let is_compact = command.name == "compact";// The compact frames carry the command's arguments as the@@ -146,7 +154,7 @@ async fn run_session_command(};// The executor never errors out of the call: failures ride// `execution.error` and the session events.- execute_session_command(&engine, &mut params, command).await+ execute_session_command(&engine, &mut params, command, images).await};if is_compact {// The post-compaction kernel notice rides between the start anddiff --git a/crates/pa-daemon/src/session_commands.rs b/crates/pa-daemon/src/session_commands.rsindex f6261c84b4..4d8eac63e2 100644--- a/crates/pa-daemon/src/session_commands.rs+++ b/crates/pa-daemon/src/session_commands.rs@@ -20,6 +20,7 @@ use crate::engine::EngineEvent;pub(crate) fn run_session_command(engine: &AgentSessionEngine,command: &SessionSlashCommand,+ images: &[pa_agent::types::ImageContent],emit: &mut dyn FnMut(EngineEvent) -> bool,) -> Option<SessionCommandExecution> {let is_compact = command.name == "compact";@@ -38,7 +39,7 @@ pub(crate) fn run_session_command(return None;}}- let execution = match engine.execute_session_command(command) {+ let execution = match engine.execute_session_command(command, images) {Ok(execution) => execution,// Pre-execution failures (model resolution, session build) still record the// attempted command as a failure result row (the echo row above already went out).diff --git a/crates/pa-daemon/src/worker/turn.rs b/crates/pa-daemon/src/worker/turn.rsindex f325489962..b2fb42e0d3 100644--- a/crates/pa-daemon/src/worker/turn.rs+++ b/crates/pa-daemon/src/worker/turn.rs@@ -1006,6 +1006,23 @@ impl TurnRunner {}}emitting_prefix_rows.set(false);+ // Sample the worker-owned leaf in memory before accepted rows+ // persist. The engine stays lazy and the accepted event stays first.+ let (file_backed, prompt_context_leaf) = {+ let core = core.lock().unwrap();+ core.store.as_ref().map_or((false, None), |store| {+ (+ !store.path.as_os_str().is_empty(),+ store.leaf_id().map(str::to_string),+ )+ })+ };+ // noSession's in-memory prefix IDs do not identify any durable+ // context the engine can restore. Only file-backed stores supply+ // this boundary; their missing-ID validation remains strict.+ if file_backed {+ engine.set_prompt_context_boundary(prompt_context_leaf);+ }engine.run_prompt(prompt_index, request, &aborted_probe, &mut emit);});let _ = turn.await;diff --git a/crates/pa-daemon/src/worker/turn_stream_tests.rs b/crates/pa-daemon/src/worker/turn_stream_tests.rsindex ba610ab6f9..3dd138abb7 100644--- a/crates/pa-daemon/src/worker/turn_stream_tests.rs+++ b/crates/pa-daemon/src/worker/turn_stream_tests.rs@@ -124,9 +124,14 @@ fn positions_of(events: &[Value], frame_type: &str) -> Vec<usize> {// race is deterministic.struct GateProbeEngine {frames: Vec<EngineEvent>,+ boundaries: Mutex<Vec<Option<String>>>,}impl SessionEngine for GateProbeEngine {+ fn set_prompt_context_boundary(&self, leaf_id: Option<String>) {+ self.boundaries.lock().unwrap().push(leaf_id);+ }+fn run_prompt(&self,_prompt_index: usize,@@ -189,7 +194,10 @@ async fn gate_sighting_events(abort_requested: bool,suppress_aborted_row: bool,) -> Vec<Value> {- let engine: Arc<dyn SessionEngine> = Arc::new(GateProbeEngine { frames });+ let engine: Arc<dyn SessionEngine> = Arc::new(GateProbeEngine {+ frames,+ boundaries: Mutex::new(Vec::new()),+ });let runner = burst_runner(Arc::clone(&engine));{let mut core = runner.core.lock().unwrap();@@ -283,3 +291,72 @@ async fn the_suppressed_row_sighting_drops_and_arms_the_silence() {"the suppressed-row sighting arms the silence: {events:?}");}++/// noSession keeps its prefix IDs in the worker's in-memory store; they+/// cannot fence the engine's durable restore. File-backed prompts capture the+/// leaf after next-turn prefix rows have persisted.+#[tokio::test]+async fn prompt_restore_boundary_is_supplied_only_for_file_backed_stores() {+ let dir = tempfile::tempdir().unwrap();+ for file_backed in [false, true] {+ let engine = Arc::new(GateProbeEngine {+ frames: vec![EngineEvent::Done(Ok(()))],+ boundaries: Mutex::new(Vec::new()),+ });+ let dynamic: Arc<dyn SessionEngine> = engine.clone();+ let runner = burst_runner(Arc::clone(&dynamic));+ let mut store = crate::session_store::SessionFile::create("/tmp", None, 0);+ store.append_session_info("prefix");+ assert!(store.leaf_id().is_some(), "in-memory prefixes have IDs too");+ if file_backed {+ store.set_path(dir.path().join("backed.jsonl"));+ store.rewrite().unwrap();+ }+ {+ let mut core = runner.core.lock().unwrap();+ core.store = Some(store);+ core.pending_next_turn.push(json!({+ "role":"custom", "customType":"prior_context", "content":"keep this prefix",+ "display":false,+ }));+ }+ runner+ .run_turn(+ dynamic,+ vec![QueuedItem {+ priority: QueuePriority::Human,+ preview: None,+ message: "go".to_string(),+ custom_message: None,+ agent_message: None,+ queue_key: None,+ admission_id: None,+ images: Vec::new(),+ done: None,+ queue_visible: true,+ policy: TurnPolicy::Queued,+ forced_batch: false,+ }],+ )+ .await;+ let expected = if file_backed {+ let path = dir.path().join("backed.jsonl");+ let persisted = crate::session_store::SessionFile::open(&path).unwrap();+ assert!(+ std::fs::read_to_string(&path)+ .unwrap()+ .contains("prior_context"),+ "the captured boundary follows the prefix on disk"+ );+ vec![persisted.leaf_id().map(str::to_string)]+ } else {+ assert!(!dir.path().join("backed.jsonl").exists());+ Vec::new()+ };+ assert_eq!(+ *engine.boundaries.lock().unwrap(),+ expected,+ "boundary capture must match durable ownership (file_backed={file_backed})"+ );+ }+}diff --git a/crates/pa-tui/src/lib.rs b/crates/pa-tui/src/lib.rsindex 4c02b052ce..7ed92eb25b 100644--- a/crates/pa-tui/src/lib.rs+++ b/crates/pa-tui/src/lib.rs@@ -85,6 +85,7 @@ mod menu_panel;pub mod model_picker;pub(crate) mod mouse;pub(crate) mod mouse_tracking;+mod new_session_command;pub mod onboarding;pub mod onboarding_choice;pub mod onboarding_flow;diff --git a/crates/pa-tui/src/new_session_command.rs b/crates/pa-tui/src/new_session_command.rsnew file mode 100644index 0000000000..6931c883d3--- /dev/null+++ b/crates/pa-tui/src/new_session_command.rs@@ -0,0 +1,191 @@+//! `/new` argument parsing (TS `new-session-command.ts`): the `--name`+//! option plus the verbatim initial prompt, with `--` separating the two.++/// A parsed `/new` suffix: the `--name` value and the initial prompt, both+/// verbatim (never trimmed).+#[derive(Debug, Default, PartialEq, Eq)]+pub(crate) struct NewSessionCommand {+ pub(crate) name: Option<String>,+ pub(crate) prompt: Option<String>,+}++/// Parse the raw suffix after the `/new` command name+/// (TS `parseNewSessionCommand`).+pub(crate) fn parse_new_session_command(raw_args: &str) -> Result<NewSessionCommand, String> {+ if raw_args.is_empty() {+ return Ok(NewSessionCommand::default());+ }+ let args = consume_new_separator(raw_args, "Expected whitespace after /new")?;+ if !args.starts_with('-') {+ return Ok(NewSessionCommand {+ name: None,+ prompt: Some(args.to_string()),+ });+ }+ if starts_with_token(args, "--") {+ let prompt = require_new_prompt(&args["--".len()..])?;+ return Ok(NewSessionCommand {+ name: None,+ prompt: Some(prompt),+ });+ }+ if !starts_with_token(args, "--name") {+ let option = first_word(args);+ return Err(format!("Unknown /new option: {option}"));+ }+ let rest = consume_new_separator(+ &args["--name".len()..],+ "Missing value for /new option \"--name\"",+ )?;+ if starts_with_token(rest, "--name") {+ return Err("Duplicate /new option: \"--name\"".to_string());+ }+ if rest.is_empty() || rest.starts_with('-') {+ return Err("Missing value for /new option \"--name\"".to_string());+ }+ let (name, rest) = split_name(rest)?;+ if name.trim().is_empty() {+ return Err("/new option \"--name\" cannot be empty".to_string());+ }+ if rest.is_empty() {+ return Ok(NewSessionCommand {+ name: Some(name),+ prompt: None,+ });+ }+ let rest = consume_new_separator(rest, "Expected \"--\" before the /new prompt")?;+ if starts_with_token(rest, "--name") {+ return Err("Duplicate /new option: \"--name\"".to_string());+ }+ if !starts_with_token(rest, "--") {+ if rest.starts_with('-') {+ let option = first_word(rest);+ return Err(format!("Unknown /new option: {option}"));+ }+ return Err("Expected \"--\" before the /new prompt".to_string());+ }+ let prompt = require_new_prompt(&rest["--".len()..])?;+ Ok(NewSessionCommand {+ name: Some(name),+ prompt: Some(prompt),+ })+}++/// TS `consumeNewSeparator`: any run of spaces/tabs, then at most one+/// newline — a zero-length consumption is the given error.+fn consume_new_separator<'a>(value: &'a str, error: &str) -> Result<&'a str, String> {+ let trimmed = value.trim_start_matches([' ', '\t']);+ let offset = value.len() - trimmed.len();+ let offset = if trimmed.starts_with("\r\n") {+ offset + 2+ } else if trimmed.starts_with('\n') || trimmed.starts_with('\r') {+ offset + 1+ } else {+ offset+ };+ if offset == 0 {+ return Err(error.to_string());+ }+ Ok(&value[offset..])+}++/// TS `requireNewPrompt`: a separator, then a prompt with non-whitespace+/// content, returned verbatim.+fn require_new_prompt(value: &str) -> Result<String, String> {+ let prompt = consume_new_separator(value, "Missing prompt after /new \"--\"")?;+ if prompt.trim().is_empty() {+ return Err("Missing prompt after /new \"--\"".to_string());+ }+ Ok(prompt.to_string())+}++/// TS's `/^<token>(?:\s|$)/` checks: the token starts the value and is+/// followed by whitespace or the end.+fn starts_with_token(value: &str, token: &str) -> bool {+ value+ .strip_prefix(token)+ .is_some_and(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace))+}++/// TS `args.match(/^\S+/)?.[0] ?? args`: the first non-whitespace run.+fn first_word(value: &str) -> &str {+ value+ .find(char::is_whitespace)+ .map_or(value, |end| &value[..end])+}++/// The `--name` value: quoted (the quote pair preserved spaces) or the first+/// word, with the remainder after it.+fn split_name(rest: &str) -> Result<(String, &str), String> {+ if let Some(quote @ ('"' | '\'')) = rest.chars().next() {+ let Some(closing) = rest[1..].find(quote) else {+ return Err("Unterminated quote in /new --name".to_string());+ };+ Ok((rest[1..=closing].to_string(), &rest[closing + 2..]))+ } else {+ let end = rest.find(char::is_whitespace).unwrap_or(rest.len());+ Ok((rest[..end].to_string(), &rest[end..]))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_names_prompts_and_errors_like_ts() {+ let ok = [+ (+ " write a\n multiline prompt ",+ NewSessionCommand {+ name: None,+ prompt: Some("write a\n multiline prompt ".to_string()),+ },+ ),+ (+ " --name stable",+ NewSessionCommand {+ name: Some("stable".to_string()),+ prompt: None,+ },+ ),+ (+ " --name \"stable name\" -- \n --keep\nformat ",+ NewSessionCommand {+ name: Some("stable name".to_string()),+ prompt: Some(" --keep\nformat ".to_string()),+ },+ ),+ // The bare `--` form the TS wiring depends on.+ (+ " -- prompt",+ NewSessionCommand {+ name: None,+ prompt: Some("prompt".to_string()),+ },+ ),+ // The bare `/new`.+ ("", NewSessionCommand::default()),+ ];+ for (raw, expected) in ok {+ assert_eq!(parse_new_session_command(raw), Ok(expected), "raw: {raw:?}");+ }+ let errors = [+ (" --name", "Missing value for /new option \"--name\""),+ (+ " --name \"one\" --name \"two\"",+ "Duplicate /new option: \"--name\"",+ ),+ (" --other value", "Unknown /new option: --other"),+ (" --name \"broken", "Unterminated quote in /new --name"),+ (" --name x prompt", "Expected \"--\" before the /new prompt"),+ ];+ for (raw, expected) in errors {+ assert_eq!(+ parse_new_session_command(raw),+ Err(expected.to_string()),+ "raw: {raw:?}"+ );+ }+ }+}diff --git a/crates/pa-tui/src/session_ui/commands.rs b/crates/pa-tui/src/session_ui/commands.rsindex 1d782679a6..9371c1c4e0 100644--- a/crates/pa-tui/src/session_ui/commands.rs+++ b/crates/pa-tui/src/session_ui/commands.rs@@ -128,7 +128,38 @@ impl SessionUi {self.note("Usage: /clear", view);}"new" => {+ // The raw suffix after the typed command name (TS parses+ // `text.slice(4)`): the leading separator and the verbatim+ // prompt survive, where the trimmed `resolved.args` would+ // lose them.+ let options = match crate::new_session_command::parse_new_session_command(+ &text[1 + resolved.original_name.len()..],+ ) {+ Ok(options) => options,+ Err(message) => {+ // The draft the submit drained restores next to the+ // error row (TS `editor.setText(text)` + `showError`).+ view.editor.set_text(text);+ self.error_row(&message, view);+ return Ok(());+ }+ };self.start_new_session(view).await?;+ if let Some(name) = options.name {+ if !self.set_session_name(&name, view).await {+ // TS parity (`handleClearCommand`'s catch): the+ // rename failed after the session exists — the+ // prompt restores into the editor and never submits.+ if let Some(prompt) = options.prompt.as_deref() {+ view.editor.set_text(prompt);+ }+ return Ok(());+ }+ }+ if let Some(prompt) = options.prompt {+ view.editor.add_to_history(&prompt);+ self.send_prompt(&prompt, SubmitBehavior::Steer, view)?;+ }}// `/quit` detaches and exits (the session keeps running in the daemon)."quit" => {@@ -737,26 +768,7 @@ impl SessionUi {}return Ok(());}- match self- .bounded_request(- Duration::from_millis(UI_REQUEST_TIMEOUT_MS),- DaemonCommand::SetSessionName {- id: None,- active_session_id: self.active_session_id.clone(),- name: name.to_string(),- worker_token: None,- rest: Map::default(),- },- )- .await- {- Ok(_) => {- self.session_name = Some(name.to_string());- view.chrome.chat_name = self.session_display();- self.plain_row(&format!("Session name set: {name}"), view);- }- Err(error) => self.error_row(&format!("{error:#}"), view),- }+ self.set_session_name(name, view).await;}"fast" => {if !resolved.args.is_empty() {@@ -829,6 +841,38 @@ impl SessionUi {Ok(())}+ /// Rename the active session through the daemon's `SetSessionName` seam —+ /// the one path the `/name` and `/new --name` arms share. On success the+ /// local name, the chrome's chat title, and the `Session name set:` row+ /// update; on failure the error row reports and the caller learns the+ /// rename did not land.+ async fn set_session_name(&mut self, name: &str, view: &mut AgentView) -> bool {+ match self+ .bounded_request(+ Duration::from_millis(UI_REQUEST_TIMEOUT_MS),+ DaemonCommand::SetSessionName {+ id: None,+ active_session_id: self.active_session_id.clone(),+ name: name.to_string(),+ worker_token: None,+ rest: Map::default(),+ },+ )+ .await+ {+ Ok(_) => {+ self.session_name = Some(name.to_string());+ view.chrome.chat_name = self.session_display();+ self.plain_row(&format!("Session name set: {name}"), view);+ true+ }+ Err(error) => {+ self.error_row(&format!("{error:#}"), view);+ false+ }+ }+ }+/// Report a menu surface opening (`tui menu opened`), fire-and-forget;/// `menu` names the surface, `source` how it opened.pub(super) fn track_menu_opened(&self, menu: &'static str, source: &'static str) {diff --git a/scripts/review_new_goal_parity.py b/scripts/review_new_goal_parity.pynew file mode 100644index 0000000000..2fee65e553--- /dev/null+++ b/scripts/review_new_goal_parity.py@@ -0,0 +1,341 @@+#!/usr/bin/env python3+"""Compare /new PTY behavior and /goal image rows in actual TS/Rust binaries.++Owned daemons, homes, kernel state and loopback providers only. Receipts retain+full model requests and terminal output; no product state or credentials are used.+Requires the same pinned TS archive and kernel provisioned by lifecycle CI.+"""+import argparse+import http.server+import json+import os+from pathlib import Path+import queue+import socket+import subprocess+import sys+import tempfile+import threading+import time++from review_draft_disconnect_parity import Terminal, env_for, stop, LIMIT+from review_goal_backoff_parity import TS_ARCHIVE_SHA256, sha256++PROMPT = 'NEW_GOAL_PARITY_INITIAL_PROMPT'+SETTLED = 'Parity fixture settled'+NAME = 'Parity named session'+OBJECTIVE = 'Describe the attached parity image'+IMAGE = {'type': 'image', 'mimeType': 'image/png', 'data':+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j3ioAAAAASUVORK5CYII='}+++class Provider(http.server.ThreadingHTTPServer):+ daemon_threads = True++ def __init__(self, goal):+ super().__init__(('127.0.0.1', 0), Handler)+ self.goal = goal+ self.requests = []+ self.errors = []+ self.thread = threading.Thread(target=self.serve_forever, daemon=True)+ self.thread.start()++ def close(self):+ self.shutdown()+ self.server_close()+ self.thread.join(timeout=2)+++class Handler(http.server.BaseHTTPRequestHandler):+ def log_message(self, *_args):+ pass++ def do_POST(self):+ try:+ assert self.path == '/v1/chat/completions', self.path+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ self.server.requests.append(body)+ assert len(self.server.requests) <= 6, 'unexpected continuation loop'+ if self.server.goal and len(self.server.requests) == 1:+ offered = {t.get('function', {}).get('name') for t in body.get('tools', [])}+ name = next((n for n in ('python_repl', 'ipython') if n in offered), None)+ assert name, 'No supported REPL offered'+ delta = {'tool_calls': [{'index': 0, 'id': 'complete_goal', 'type': 'function',+ 'function': {'name': name, 'arguments': json.dumps({'code':+ 'import goal\nawait goal.complete()'})}}]}+ finish = 'tool_calls'+ else:+ delta, finish = {'content': SETTLED}, 'stop'+ def chunk(value, reason=None):+ return {'id': 'new-goal-parity', 'object': 'chat.completion.chunk', 'created': 1,+ 'model': 'parity-1', 'choices': [{'index': 0, 'delta': value,+ 'finish_reason': reason}]}+ wire = ''.join('data: ' + json.dumps(row) + '\n\n' for row in (+ chunk({'role': 'assistant', **delta}), chunk({}, finish))) + 'data: [DONE]\n\n'+ self.send_response(200)+ self.send_header('Content-Type', 'text/event-stream')+ self.send_header('Content-Length', str(len(wire.encode())))+ self.end_headers()+ self.wfile.write(wire.encode())+ except (BrokenPipeError, ConnectionResetError):+ pass+ except Exception as exc:+ self.server.errors.append(str(exc))+ self.send_error(500, str(exc))+++def setup(root, label, provider):+ root.mkdir(parents=True)+ env = env_for(root, label)+ if label == 'rust':+ env['PA_COMPACTION_TRACE'] = 'stderr'+ for key in ('PYTHONPATH', 'PRIME_AGENT_KERNEL_PYTHON', 'PA_E2E_KERNEL_PYTHON'):+ if key in os.environ:+ env[key] = os.environ[key]+ library = Path(os.environ['PI_PACKAGE_DIR']) / 'skills'+ env['PYTHONPATH'] = os.pathsep.join(sorted(str(p) for p in library.glob('*/src'))+ + [env.get('PYTHONPATH', '')])+ env['PI_SESSION_DIR'] = env['PRIME_AGENT_SESSION_DIR'] = str(root / 'agent/sessions')+ (root / 'agent/models.json').write_text(json.dumps({'providers': {'parity-local': {+ 'api': 'openai-completions', 'apiKey': 'fixture-only',+ 'baseUrl': 'http://127.0.0.1:%s/v1' % provider.server_address[1],+ 'models': [{'id': 'parity-1', 'name': 'Parity 1', 'input': ['text', 'image'],+ 'reasoning': False, 'contextWindow': 128000, 'maxTokens': 4096}]}}}))+ (root / 'agent/settings.json').write_text(json.dumps({'defaultProvider': 'parity-local',+ 'defaultModel': 'parity-1', 'prewarmPythonKernel': False,+ 'onboardingCompleted': True, 'onboardingShown': True,+ 'telemetry': {'noticeShown': True}}))+ return env+++def wait_for(predicate, label, process=None):+ deadline = time.monotonic() + LIMIT+ while time.monotonic() < deadline:+ if predicate():+ return+ if process is not None and process.poll() is not None:+ raise RuntimeError('binary exited while waiting for ' + label)+ threading.Event().wait(0.025)+ raise TimeoutError(label)+++def session_rows(root):+ result = []+ for path in sorted((root / 'agent/sessions').rglob('*.jsonl')):+ rows = [json.loads(line) for line in path.read_text().splitlines() if line.strip()]+ if rows and rows[0].get('type') == 'session':+ result.append({'path': str(path), 'rows': rows})+ return result+++def new_case(binary, label, root, observation):+ provider = Provider(False)+ terminal = daemon = None+ path = root / 'daemon.sock'+ try:+ env = setup(root, label, provider)+ with (root / 'daemon.log').open('wb') as log:+ daemon = subprocess.Popen([str(binary), '--mode', 'daemon', '--daemon-socket', str(path)],+ cwd=root, env=env, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)+ def ready():+ try:+ with socket.socket(socket.AF_UNIX) as sock:+ sock.settimeout(1)+ sock.connect(str(path))+ with sock.makefile('rb') as stream:+ hello = json.loads(stream.readline())+ assert hello.get('type') == 'daemon_hello', hello+ observation['daemon_hello'] = hello+ return True+ except (FileNotFoundError, ConnectionRefusedError, socket.timeout):+ return False+ wait_for(ready, 'owned daemon readiness', daemon)+ terminal = Terminal([str(binary), '--daemon-socket', str(path), '--provider', 'parity-local',+ '--model', 'parity-1'], root, env)+ terminal.wait('initial session attached', lambda: len(session_rows(root)) == 1+ and bool(terminal.screen.text().strip()), provider)+ command = '/new --name "' + NAME + '" -- ' + PROMPT+ terminal.send(command)+ terminal.wait('command visibly typed', lambda: PROMPT in terminal.screen.text(), provider)+ observation['typed_screen'] = terminal.screen.text()+ terminal.send('\r')+ terminal.wait('new prompt visibly settled', lambda: SETTLED in terminal.screen.text(), provider)+ rows = session_rows(root)+ observation.update(screen=terminal.screen.text(), raw_terminal=terminal.raw.decode(errors='replace'),+ sessions=rows, requests=provider.requests)+ named = [r for r in rows if any(e.get('type') == 'session_info' and e.get('name') == NAME+ for e in r['rows'])]+ assert len(rows) == 2 and len(named) == 1, 'new session/name did not persist'+ assert len(provider.requests) == 1, 'initial prompt did not execute exactly once'+ messages = provider.requests[0]['messages']+ content = [m['content'] for m in messages if m.get('role') == 'user'+ and PROMPT in json.dumps(m.get('content'))]+ assert any(PROMPT in json.dumps(c) for c in content), 'initial prompt missing from provider'+ assert NAME in observation['screen'], 'named session not rendered'+ return {'session_count': len(rows), 'name': NAME, 'user_content': content,+ 'settled_text': SETTLED, 'request_count': len(provider.requests)}+ finally:+ if terminal:+ observation.setdefault('screen', terminal.screen.text())+ observation.setdefault('raw_terminal', terminal.raw.decode(errors='replace'))+ terminal.close()+ if daemon:+ stop(daemon)+ observation['daemon_log'] = (root / 'daemon.log').read_text(errors='replace')+ observation['worker_stderr_logs'] = {str(path.relative_to(root)): path.read_text(errors='replace')+ for path in (root / 'agent').rglob('worker-*.stderr.log')}+ observation.setdefault('requests', provider.requests)+ observation['provider_errors'] = provider.errors+ provider.close()+++class Rpc:+ def __init__(self, binary, root, env):+ self.process = subprocess.Popen([str(binary), '--mode', 'rpc', '--provider', 'parity-local',+ '--model', 'parity-1'], cwd=root, env=env, stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, start_new_session=True)+ self.lines = queue.Queue()+ self.frames, self.errors = [], []+ def read():+ for line in self.process.stdout:+ self.lines.put(line)+ def read_errors():+ for line in self.process.stderr:+ self.errors.append(line)+ self.readers = [threading.Thread(target=fn, daemon=True) for fn in (read, read_errors)]+ for thread in self.readers:+ thread.start()++ def send(self, frame):+ self.process.stdin.write(json.dumps(frame) + '\n')+ self.process.stdin.flush()++ def until(self, predicate):+ deadline = time.monotonic() + LIMIT+ while time.monotonic() < deadline:+ try:+ line = self.lines.get(timeout=0.1)+ except queue.Empty:+ if self.process.poll() is not None:+ raise RuntimeError('RPC exited: ' + ''.join(self.errors)[-2000:])+ continue+ frame = json.loads(line)+ self.frames.append(frame)+ if predicate(frame):+ return frame+ raise TimeoutError('RPC event/response readiness')++ def close(self):+ stop(self.process)+ for thread in self.readers:+ thread.join(timeout=2)+ self.process.stdin.close()+ self.process.stdout.close()+ self.process.stderr.close()+++def goal_case(binary, label, root, observation):+ provider = Provider(True)+ rpc = None+ try:+ env = setup(root, label, provider)+ rpc = Rpc(binary, root, env)+ rpc.send({'type': 'prompt', 'id': 'goal-image', 'message': '/goal ' + OBJECTIVE,+ 'images': [IMAGE]})+ response = rpc.until(lambda f: f.get('type') == 'response' and f.get('id') == 'goal-image')+ assert response.get('success'), response+ # The changed surface is the goal-context carrier. RPC's existing Rust+ # continuation path publishes an active update before the model turn,+ # but not the tool's final complete update. Preserve that difference;+ # query authoritative host state after agent_end rather than assuming+ # the TS event-publication sequence or trusting fixture answer text.+ rpc.until(lambda f: f.get('type') == 'agent_end')+ rpc.send({'type': 'get_state', 'id': 'settled-goal-state'})+ settled = rpc.until(lambda f: f.get('type') == 'response'+ and f.get('id') == 'settled-goal-state')+ assert settled.get('success'), settled+ final_goal = settled.get('data', {}).get('goal', {})+ observation['final_goal'] = final_goal+ observation['goal_update_statuses'] = [f.get('goal', {}).get('status')+ for f in rpc.frames if f.get('type') == 'goal_update']+ assert final_goal.get('status') == 'complete', final_goal+ contexts = [f['message'] for f in rpc.frames if f.get('type') == 'message_end'+ and f.get('message', {}).get('customType') == 'goal_context']+ observation.update(frames=rpc.frames, requests=provider.requests, sessions=session_rows(root))+ assert len(contexts) == 1, 'expected the actual goal-context message_end'+ content = contexts[0]['content']+ assert isinstance(content, list) and content[0]['type'] == 'text', content+ assert OBJECTIVE in content[0]['text'] and '[goal: continuation]' in content[0]['text'], content+ assert content[1:] == [IMAGE], 'goal image blocks changed/dropped'+ assert len(provider.requests) == 2, 'goal complete tool did not settle the turn'+ image_urls = [block.get('image_url') for m in provider.requests[0].get('messages', [])+ for block in (m.get('content') if isinstance(m.get('content'), list) else [])+ if block.get('type') == 'image_url']+ # The existing custom-message/provider image-routing limitation is recorded+ # separately; this PR repairs the goal context carrier, not model routing.+ observation['provider_image_urls'] = image_urls+ return {'content': content, 'display': contexts[0].get('display'),+ 'complete': True, 'request_count': len(provider.requests)}+ finally:+ if rpc:+ rpc.close()+ observation.setdefault('frames', rpc.frames)+ observation['stderr'] = ''.join(rpc.errors)+ observation.setdefault('requests', provider.requests)+ observation['provider_errors'] = provider.errors+ provider.close()+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--receipt', type=Path, required=True)+ args = parser.parse_args()+ result = {'runs': {}, 'differences': {}, 'verified': False,+ 'scope': {'new': 'Real PTY command, owned real daemon, persisted name and model initial prompt.',+ 'goal': 'Actual RPC image-bearing goal_context row and completed goal.',+ 'provider_images': 'Recorded independently; existing model-routing limitation is not normalized into context-row evidence.',+ 'goal_updates': 'Recorded independently: Rust RPC publishes before continuation, not on goal.complete; final completion is verified by get_state after agent_end.'}}+ try:+ assert sys.platform == 'linux', 'requires Linux hosted CI'+ archive_hash = sha256(os.environ['PA_TS_ARCHIVE'])+ assert archive_hash == TS_ARCHIVE_SHA256, 'TS archive checksum mismatch'+ result['ts_release_archive_sha256'] = archive_hash+ binaries = {label: Path(os.environ['PA_' + label.upper() + '_BINARY']).resolve()+ for label in ('ts', 'rust')}+ result['binaries'] = {label: {'path': str(binary), 'sha256': sha256(binary)}+ for label, binary in binaries.items()}+ with tempfile.TemporaryDirectory(prefix='new-goal-parity-', dir='/tmp') as temp:+ for scenario, run in (('new', new_case), ('goal_images', goal_case)):+ result['runs'][scenario] = {}+ for label, binary in binaries.items():+ observation = {}+ result['runs'][scenario][label] = observation+ try:+ observation['surface'] = run(binary, label, Path(temp) / (scenario + '-' + label), observation)+ except Exception as exc:+ observation['error'] = str(exc)+ ts, rust = result['runs'][scenario]['ts'], result['runs'][scenario]['rust']+ if ts.get('surface') != rust.get('surface'):+ result['differences'][scenario] = {'ts': ts.get('surface'), 'rust': rust.get('surface')}+ failures = {scenario + '/' + label: run['error'] for scenario, runs in result['runs'].items()+ for label, run in runs.items() if 'error' in run}+ images = result['runs']['goal_images']+ if all('provider_image_urls' in run for run in images.values()):+ result['provider_image_routing_equal'] = (images['ts']['provider_image_urls']+ == images['rust']['provider_image_urls'])+ if all('goal_update_statuses' in run for run in images.values()):+ result['goal_update_event_sequence_equal'] = (images['ts']['goal_update_statuses']+ == images['rust']['goal_update_statuses'])+ assert not failures, failures+ assert not result['differences'], 'changed-surface parity mismatch'+ result['verified'] = True+ except Exception as exc:+ result['error'] = str(exc)+ args.receipt.parent.mkdir(parents=True, exist_ok=True)+ args.receipt.write_text(json.dumps(result, indent=2) + '\n')+ print(json.dumps({'receipt': str(args.receipt), 'verified': result['verified'], 'error': result.get('error')}))+ return 0 if result['verified'] else 1+++if __name__ == '__main__':+ sys.exit(main())