diff --git a/apps/presentation/dashboard/smoke/managed-task-entry-browser-smoke.mjs b/apps/presentation/dashboard/smoke/managed-task-entry-browser-smoke.mjs
new file mode 100644
index 0000000000..edcae5bd14
--- /dev/null
+++ b/apps/presentation/dashboard/smoke/managed-task-entry-browser-smoke.mjs
@@ -0,0 +1,166 @@
+#!/usr/bin/env node
+// The original Task's primary control reads its typed owner; only explicit launch
+// submits the original Todo, and recovery observes the same native operation.
+// Synthetic HTTP replies isolate the browser contract; owning-backend qualification
+// remains a separate packaged journey.
+import assert from "node:assert/strict";
+import {dirname, resolve} from "node:path";
+import {fileURLToPath} from "node:url";
+import {cleanupBrowserSmoke, launchBrowser, loadPlaywright, startViteDashboardServer, waitForHttp} from "../../../../examples/dashboard-browser-smoke-support.mjs";
+
+const dashboardDir = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+const port = Number(process.env.LOOPX_MANAGED_TASK_TEST_PORT ?? 5371);
+const origin = `http://127.0.0.1:${port}`;
+const server = await startViteDashboardServer({dashboardDir, port});
+const storageKey = `loopx-managed-task:${JSON.stringify(["cart-repair", "codex", "original-session"])}`;
+const session = {session_id: "original-session", goal_id: "cart-repair", goal_instance_id: null,
+ managed_agent_id: "codex", channel_id: "agent.codex", session_mode: "managed_runtime"};
+const ready = {todo_id: "original-cart-task", state: "ready", source: "goal-creation",
+ canonical_done: false, observation: {check_count: 6, pinned_file_count: 1, basis_sha256: "confirmed-check-source"}};
+const unbound = {todo_id: "original-cart-task", state: "unbound", source: null, canonical_done: false};
+const native = (operationId, status = "queued") => ({session_id: session.session_id, turn_id: "original-native-turn",
+ client_turn_id: `managed.${operationId}`, status, origin: "native_loopx", loopx_execution: true,
+ loopx_request: {operation: "native_turn", todo_id: ready.todo_id,
+ actor: {goal_id: session.goal_id, agent_id: "codex", session_id: session.session_id}}});
+let browser;
+async function probe(initial = {}) {
+ const page = await browser.newPage();
+ await page.clock.install();
+ await page.addInitScript(({key, attempt}) => {
+ localStorage.setItem("loopx-pw-locale", "en");
+ if (attempt !== undefined && sessionStorage.getItem(key) === null) sessionStorage.setItem(key, attempt);
+ }, {key: storageKey, attempt: initial.attempt});
+ const state = {task: ready, turn: null, available: true, loseAck: false, sessions: [session], ...initial};
+ const reads = [], writes = [], errors = [];
+ page.on("pageerror", error => errors.push(error.message));
+ await page.route("**/api/**", async route => {
+ const request = route.request(), url = new URL(request.url());
+ if (url.pathname === "/api/chat/sessions") return route.fulfill({json: {ok: true,
+ schema_version: "loopx_chat_session_list_v1", goal_id: session.goal_id, managed_agent_id: "codex",
+ goal_instance_id: null, sessions: state.sessions}});
+ assert.equal(url.pathname, "/api/chat/sessions/original-session/native-turn", "No coordinator/settings/Task/session creation endpoint");
+ if (request.method() === "GET") {
+ reads.push(Object.fromEntries(url.searchParams));
+ assert.equal(url.searchParams.get("original_task"), "true");
+ assert.equal(url.searchParams.get("agent_id"), "codex");
+ assert.equal(url.searchParams.has("todo_id"), false, "Task selection belongs to Core");
+ return route.fulfill({json: {ok: true, session_id: session.session_id, managed_agent_id: "codex",
+ registered_agents: ["codex"], available: state.available, task: state.task, turn: state.turn}});
+ }
+ const body = request.postDataJSON(); writes.push(body);
+ assert.deepEqual(Object.keys(body).sort(), ["agent_id", "operation_id", "todo_id"]);
+ assert.equal(body.agent_id, "codex"); assert.equal(body.todo_id, ready.todo_id);
+ state.turn = native(body.operation_id);
+ if (state.loseAck) return route.abort("failed");
+ return route.fulfill({status: 202, json: {ok: true, session_id: session.session_id, turn: state.turn, created: true}});
+ });
+ const firstRead = initial.attempt === "{malformed" ? null : page.waitForResponse(row => row.url().includes("native-turn"));
+ await page.goto(origin + "/smoke/managed-task-entry-smoke.html");
+ if (firstRead) await firstRead;
+ await page.waitForFunction(() => document.querySelector('output[aria-label="History observations"]'));
+ const section = page.getByRole("region", {name: "Current Task", exact: true});
+ const button = section.locator("button.goal-loopx-primary");
+ const poll = async () => {
+ const response = page.waitForResponse(row => new URL(row.url()).pathname.endsWith("/native-turn") && row.request().method() === "GET");
+ await page.clock.fastForward(5100); await response;
+ await page.clock.runFor(30);
+ };
+ return {page, state, reads, writes, errors, section, button, poll,
+ async finish() {assert.deepEqual(errors, []); await page.close();}};
+}
+try {
+ await waitForHttp(origin + "/smoke/managed-task-entry-smoke.html");
+ browser = await launchBrowser(loadPlaywright().chromium);
+ {
+ const p = await probe({task: unbound, available: false});
+ assert.equal(await p.section.count(), 0, "Unconfirmed checks expose no launch control");
+ await p.page.clock.fastForward(16000); await p.page.clock.runFor(30);
+ assert.equal(p.reads.length, 1, "An unconfigured default Goal has one initial native read and no empty background queries");
+ assert.deepEqual(p.writes, []); await p.finish();
+ }
+ {
+ const p = await probe(); await p.button.waitFor();
+ assert.equal(await p.button.isDisabled(), false, "A ready definition permits repair despite a failed baseline");
+ await p.page.clock.fastForward(16000); await p.page.clock.runFor(30);
+ assert.equal(p.reads.length, 1, "A ready idle Task also waits for an explicit operation");
+ p.state.task = unbound; p.state.available = false;
+ await p.button.click();
+ await p.page.waitForFunction(() => document.querySelector("button.goal-loopx-primary")?.disabled);
+ assert.deepEqual(p.writes, [], "A stale ready viewport cannot launch against changed current checks");
+ await p.finish();
+ }
+ {
+ const p = await probe({loseAck: true}); await p.button.waitFor(); await p.button.click();
+ await p.page.waitForFunction(() => document.querySelector(".goal-loopx-mode-status")?.textContent.includes("waiting to run"));
+ assert.equal(p.writes.length, 1); const operation = p.writes[0].operation_id;
+ assert.match(operation, /^task\./); assert.equal(await p.button.isDisabled(), true);
+ assert.equal(await p.section.locator('[data-active="true"]').count(), 0, "Queued ACK recovery does not imply running");
+ await p.page.reload(); await p.button.waitFor();
+ assert.equal(await p.button.isDisabled(), true); assert.equal(p.writes.length, 1);
+ assert.equal(p.reads.at(-1).operation_id, operation, "Reload reads the retained operation");
+ await p.page.evaluate(() => {
+ Object.defineProperty(document, "hidden", {configurable: true, value: true});
+ document.dispatchEvent(new Event("visibilitychange"));
+ });
+ const hiddenReads = p.reads.length;
+ await p.page.clock.fastForward(16000); await p.page.clock.runFor(30);
+ assert.equal(p.reads.length, hiddenReads, "Hidden pending Tasks do not poll");
+ const returned = p.page.waitForResponse(row => row.url().includes("native-turn"));
+ await p.page.evaluate(() => {
+ Object.defineProperty(document, "hidden", {configurable: true, value: false});
+ document.dispatchEvent(new Event("visibilitychange"));
+ });
+ await returned;
+ p.state.turn = native(operation, "running"); await p.poll();
+ assert.equal(await p.section.locator('[data-active="true"]').count(), 1);
+ p.state.turn = native(operation, "failed"); await p.poll();
+ assert.equal(await p.button.isDisabled(), false); assert.equal(p.writes.length, 1, "Failure never launches automatically");
+ const terminalReads = p.reads.length;
+ await p.page.clock.fastForward(16000); await p.page.clock.runFor(30);
+ assert.equal(p.reads.length, terminalReads, "Known terminal Turns stop readback polling");
+ await p.button.click();
+ await p.page.waitForFunction(() => document.querySelector(".goal-loopx-mode-status")?.textContent.includes("waiting to run"));
+ assert.equal(p.writes.length, 2); assert.notEqual(p.writes[1].operation_id, operation, "Explicit retry owns a fresh operation after a confirmed terminal Turn");
+ assert.ok(Number(await p.page.getByLabel("History observations").textContent()) >= 3);
+ await p.finish();
+ }
+ for (const mutation of ["operation", "agent", "goal", "session", "todo", "turn-id", "missing-turn", "ordinary-turn"]) {
+ const saved = {operationId: "retained-request", todoId: ready.todo_id, turnId: "original-native-turn", status: "running"};
+ const turn = native(saved.operationId, "failed");
+ if (mutation === "operation") turn.client_turn_id = "managed.unrelated-request";
+ if (mutation === "agent") turn.loopx_request.actor.agent_id = "other-agent";
+ if (mutation === "goal") turn.loopx_request.actor.goal_id = "other-goal";
+ if (mutation === "session") turn.session_id = "other-session";
+ if (mutation === "todo") turn.loopx_request.todo_id = "other-task";
+ if (mutation === "turn-id") turn.turn_id = "different-turn";
+ if (mutation === "ordinary-turn") turn.loopx_execution = false;
+ const p = await probe({attempt: JSON.stringify(saved), turn: mutation === "missing-turn" ? null : turn});
+ await p.section.getByRole("alert").waitFor();
+ assert.equal(await p.button.textContent(), "Refresh"); await p.button.click();
+ await p.poll(); assert.deepEqual(p.writes, [], `${mutation}: unverifiable recovery only rereads`);
+ assert.equal(await p.section.locator('[data-active="true"]').count(), 0); await p.finish();
+ }
+ {
+ const p = await probe(); await p.button.waitFor();
+ await p.page.evaluate(key => sessionStorage.setItem(key, "{malformed"), storageKey);
+ await p.button.click(); await p.section.getByRole("alert").waitFor();
+ assert.deepEqual(p.writes, [], "Storage corruption immediately before launch also holds the request");
+ await p.finish();
+ }
+ {
+ const p = await probe({attempt: "{malformed"}); await p.section.getByRole("alert").waitFor();
+ await p.button.click(); await p.page.clock.fastForward(5100);
+ assert.deepEqual(p.writes, []); assert.equal(p.reads.length, 0, "Unreadable saved operation is held without inventing another request");
+ await p.finish();
+ }
+ {
+ const p = await probe({attempt: JSON.stringify({operationId: "old-failed", todoId: ready.todo_id, status: "running"}), turn: native("old-failed", "failed")});
+ await p.button.waitFor(); assert.equal(await p.button.isDisabled(), false, "A saved running label cannot override fresh terminal readback");
+ assert.equal(await p.section.locator('[data-active="true"]').count(), 0);
+ await p.page.evaluate(key => sessionStorage.setItem(key, "[]"), storageKey);
+ await p.button.click();
+ await p.section.getByRole("alert").waitFor(); await p.button.click();
+ assert.deepEqual(p.writes, [], "Later storage corruption also revokes execution"); await p.finish();
+ }
+ console.log("managed-task-entry: check-readiness, original identity, explicit native launch, ACK recovery, liveness, reload, retry and malformed-storage boundaries passed");
+} finally {await cleanupBrowserSmoke({browser, server, fixturePaths: []});}
diff --git a/apps/presentation/dashboard/smoke/managed-task-entry-smoke.html b/apps/presentation/dashboard/smoke/managed-task-entry-smoke.html
new file mode 100644
index 0000000000..ee482f3fd5
--- /dev/null
+++ b/apps/presentation/dashboard/smoke/managed-task-entry-smoke.html
@@ -0,0 +1,3 @@
+
+
Original Task entry
+
diff --git a/apps/presentation/dashboard/smoke/managed-task-entry-smoke.tsx b/apps/presentation/dashboard/smoke/managed-task-entry-smoke.tsx
new file mode 100644
index 0000000000..9bcc4fba89
--- /dev/null
+++ b/apps/presentation/dashboard/smoke/managed-task-entry-smoke.tsx
@@ -0,0 +1,16 @@
+import {useState} from "react";
+import {createRoot} from "react-dom/client";
+import {GoalLoopXMode} from "../src/features/personal-workspace/goal-loopx-mode";
+import {WorkspaceI18nProvider} from "../src/features/personal-workspace/i18n";
+
+function OriginalTaskProbe() {
+ const [observations, setObservations] = useState(0);
+ const forbidden = () => {throw new Error("Managed Task entered the coordinator owner");};
+ return
+ {forbidden(); return "";}} onExecute={forbidden} onChange={forbidden}
+ managed={{target: {goalId: "cart-repair", agentId: "codex", sessionId: "original-session"},
+ onObserve: async () => {setObservations(value => value + 1);}}}/>
+
+ ;
+}
+createRoot(document.getElementById("root")!).render();
diff --git a/apps/presentation/dashboard/src/data/chat.ts b/apps/presentation/dashboard/src/data/chat.ts
index 02c0deed71..63658a8920 100644
--- a/apps/presentation/dashboard/src/data/chat.ts
+++ b/apps/presentation/dashboard/src/data/chat.ts
@@ -1697,6 +1697,59 @@ export async function steerChatTurn(sessionId: string, turnId: string, message:
return receipt;
}
+const managedTaskTurnSchema = z.object({
+ session_id: z.string().min(1), turn_id: z.string().min(1), client_turn_id: z.string().min(1), status: z.string().min(1),
+ origin: z.literal("native_loopx"), loopx_execution: z.literal(true),
+ loopx_request: z.object({operation: z.literal("native_turn"), todo_id: z.string().min(1),
+ actor: z.object({goal_id: z.string().min(1), agent_id: z.string().min(1), session_id: z.string().min(1)})}),
+}).passthrough();
+const managedTaskEntrySchema = z.object({ok: z.literal(true), session_id: z.string().min(1),
+ managed_agent_id: z.string().nullable(), registered_agents: z.array(z.string()), available: z.boolean(), reason: z.string().optional(),
+ task: z.discriminatedUnion("state", [
+ z.object({todo_id: z.string().min(1), state: z.literal("ready"), source: z.string().min(1), canonical_done: z.boolean(),
+ observation: z.object({check_count: z.number().int().nonnegative(), pinned_file_count: z.number().int().nonnegative(),
+ basis_sha256: z.string().min(1)}), reason: z.string().optional()}),
+ z.object({todo_id: z.string().nullable(), state: z.literal("unbound"), source: z.null(), canonical_done: z.literal(false), reason: z.string().optional()}),
+ ]), turn: managedTaskTurnSchema.nullable(),
+});
+export type ManagedTaskEntry = z.infer;
+export type ManagedTaskTurn = z.infer;
+
+function verifyManagedTaskTurn(turn: ManagedTaskTurn, target: ManagedConversationTarget, operationId: string, todoId?: string) {
+ const actor = turn.loopx_request.actor;
+ if (turn.session_id !== target.sessionId || turn.client_turn_id !== `managed.${operationId}`
+ || actor.session_id !== target.sessionId || actor.goal_id !== target.goalId || actor.agent_id !== target.agentId
+ || todoId !== undefined && turn.loopx_request.todo_id !== todoId) throw new Error("The original Task Turn identity changed.");
+}
+
+/** Read the Core-selected original Task; preparation and check adoption grant no launch. */
+export async function fetchManagedTaskEntry(target: ManagedConversationTarget, options: {operationId?: string; todoId?: string; signal?: AbortSignal} = {}) {
+ await resolveManagedChatSession(target, options.signal);
+ const query = new URLSearchParams({original_task: "true", agent_id: target.agentId});
+ if (options.operationId !== undefined) query.set("operation_id", options.operationId);
+ const result = managedTaskEntrySchema.parse(await requestJson(
+ `/api/chat/sessions/${encodeURIComponent(target.sessionId)}/native-turn?${query}`, {signal: options.signal}));
+ if (result.session_id !== target.sessionId || result.managed_agent_id !== target.agentId || !result.registered_agents.includes(target.agentId)) {
+ throw new Error("The original Task entry is unavailable from this Agent.");
+ }
+ if (result.turn) {
+ if (!options.operationId) throw new Error("The Task read returned an unrelated operation.");
+ verifyManagedTaskTurn(result.turn, target, options.operationId, options.todoId);
+ }
+ return result;
+}
+
+/** Only an explicit owner operation calls the existing native Task admission. */
+export async function startManagedTaskTurn(target: ManagedConversationTarget, todoId: string, operationId: string, signal?: AbortSignal) {
+ await resolveManagedChatSession(target, signal);
+ const result = z.object({ok: z.literal(true), session_id: z.string(), turn: managedTaskTurnSchema, created: z.boolean()}).parse(
+ await requestJson(`/api/chat/sessions/${encodeURIComponent(target.sessionId)}/native-turn`, {method: "POST", signal,
+ body: JSON.stringify({agent_id: target.agentId, operation_id: operationId, todo_id: todoId})}));
+ if (result.session_id !== target.sessionId) throw new Error("The original Task Session changed during launch.");
+ verifyManagedTaskTurn(result.turn, target, operationId, todoId);
+ return result;
+}
+
export type LoopXModeSnapshot = {
ok: true; session_id: string; enabled: boolean; active_turn_id: string | null; conversation_busy: boolean;
settings: Partial & { execution_config?: string };
diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-loopx-mode.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-loopx-mode.tsx
index 9d5a11924f..50f6fb78d4 100644
--- a/apps/presentation/dashboard/src/features/personal-workspace/goal-loopx-mode.tsx
+++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-loopx-mode.tsx
@@ -1,17 +1,174 @@
import {ContextHelp} from "./context-help";
import {useEffect, useRef, useState} from "react";
import {Pause, Play, Settings2, Users, X} from "lucide-react";
-import {fetchLoopXMode, updateLoopXMode, type LoopXModeSnapshot, type LoopXModeSettings} from "../../data/chat";
+import {fetchLoopXMode, updateLoopXMode, fetchManagedTaskEntry, startManagedTaskTurn,
+ type ManagedConversationTarget, type ManagedTaskEntry, type ManagedTaskTurn, type LoopXModeSnapshot, type LoopXModeSettings} from "../../data/chat";
import {useWorkspaceI18n} from "./i18n";
import {GoalTeamWork} from "./goal-team-work";
import "./goal-loopx-mode.css";
-export function GoalLoopXMode({sessionId, onPrepare, onExecute, onChange}: {
+type GoalLoopXModeProps = {
sessionId?: string;
onPrepare: () => Promise;
onExecute: (operation: "start" | "resume", settings?: LoopXModeSettings) => void;
onChange: (snapshot: LoopXModeSnapshot | null) => void;
-}) {
+ managed?: {target: ManagedConversationTarget; onObserve: () => Promise};
+};
+
+/** The existing primary control has distinct native and coordinator owners. */
+export function GoalLoopXMode(props: GoalLoopXModeProps) {
+ return props.managed ?
+ : ;
+}
+
+type TaskAttempt = {operationId: string; todoId: string; turnId?: string; status?: string};
+const terminalTaskTurn = (status?: string) => ["completed", "failed", "interrupted", "timed_out"].includes(status ?? "");
+function readTaskAttempt(key: string): TaskAttempt | null {
+ const stored = sessionStorage.getItem(key);
+ if (stored === null) return null;
+ const value: unknown = JSON.parse(stored);
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Unreadable original Task request");
+ const attempt = value as Record;
+ if (Object.keys(attempt).some(field => !["operationId", "todoId", "turnId", "status"].includes(field))
+ || typeof attempt.operationId !== "string" || !/^[A-Za-z0-9._:-]{1,100}$/.test(attempt.operationId)
+ || typeof attempt.todoId !== "string" || !attempt.todoId
+ || attempt.turnId !== undefined && (typeof attempt.turnId !== "string" || !attempt.turnId)
+ || attempt.status !== undefined && (typeof attempt.status !== "string" || !attempt.status)) throw new Error("Unreadable original Task request");
+ return attempt as TaskAttempt;
+}
+
+function ManagedTaskMode({target, onObserve}: NonNullable) {
+ const zh = useWorkspaceI18n().locale === "zh-CN";
+ const storageKey = `loopx-managed-task:${JSON.stringify([target.goalId, target.agentId, target.sessionId])}`;
+ const [retained, setRetained] = useState<{attempt: TaskAttempt | null; unreadable: boolean}>(() => {
+ try {return {attempt: readTaskAttempt(storageKey), unreadable: false};} catch {return {attempt: null, unreadable: true};}
+ });
+ const attempt = retained.attempt;
+ const attemptRef = useRef(attempt); attemptRef.current = attempt;
+ const [read, setRead] = useState(null);
+ const [busy, setBusy] = useState(false), [error, setError] = useState("");
+ const flight = useRef(false), live = useRef(true), revision = useRef(0);
+ const observe = useRef(onObserve); observe.current = onObserve;
+ const seenTurn = useRef("");
+ const shown = useRef(retained.unreadable || Boolean(attempt));
+ const [refresh, setRefresh] = useState(0);
+ function retain(next: TaskAttempt) {
+ sessionStorage.setItem(storageKey, JSON.stringify(next));
+ if (sessionStorage.getItem(storageKey) !== JSON.stringify(next)) throw new Error("Original request could not be retained");
+ attemptRef.current = next; setRetained({attempt: next, unreadable: false});
+ }
+ async function accept(turn: ManagedTaskTurn) {
+ if (!live.current) return;
+ const current = attemptRef.current!;
+ retain({...current, turnId: turn.turn_id, status: turn.status});
+ const signature = JSON.stringify([turn.turn_id, turn.status]);
+ if (seenTurn.current !== signature) {
+ // The existing history/recovery owner adopts this exact Session and stream.
+ await observe.current();
+ seenTurn.current = signature;
+ }
+ }
+ useEffect(() => {
+ live.current = true;
+ const controller = new AbortController();
+ let reading = false, needsReadback = false, timer: number | undefined;
+ function scheduleReadback() {
+ window.clearTimeout(timer);
+ if (needsReadback && !document.hidden && !controller.signal.aborted) {
+ timer = window.setTimeout(() => void load(), 5000);
+ }
+ }
+ async function load() {
+ if (reading || flight.current) return;
+ reading = true;
+ const generation = ++revision.current;
+ let storageRead = false;
+ try {
+ const current = readTaskAttempt(storageKey);
+ storageRead = true;
+ needsReadback = Boolean(current);
+ attemptRef.current = current;
+ setRetained({attempt: current, unreadable: false});
+ const result = await fetchManagedTaskEntry(target, {operationId: current?.operationId, todoId: current?.todoId,
+ signal: AbortSignal.any([controller.signal, AbortSignal.timeout(8000)])});
+ if (controller.signal.aborted || generation !== revision.current) return;
+ if (current?.turnId && result.turn?.turn_id !== current.turnId) throw new Error("The original Task Turn is unavailable");
+ needsReadback = Boolean(current && (!result.turn || !terminalTaskTurn(result.turn.status)));
+ setRead(result); setError("");
+ if (result.turn) await accept(result.turn);
+ } catch {
+ if (!controller.signal.aborted && generation === revision.current) {
+ if (!storageRead) {needsReadback = false; setRetained(previous => ({...previous, unreadable: true}));}
+ setRead(null); setError(zh ? "当前任务或原请求暂时无法读取。重新读取不会启动任务。" : "The Task or original request could not be read. Refreshing does not launch it.");
+ }
+ } finally {reading = false; scheduleReadback();}
+ }
+ void load();
+ const visibility = () => {if (document.hidden) window.clearTimeout(timer); else if (needsReadback) void load();};
+ document.addEventListener("visibilitychange", visibility);
+ return () => {live.current = false; revision.current++; controller.abort(); window.clearTimeout(timer); document.removeEventListener("visibilitychange", visibility);};
+ }, [storageKey, refresh]);
+
+ const ready = read?.available === true && read.task.state === "ready" && read.task.canonical_done === false
+ && read.task.observation.check_count > 0 && !retained.unreadable;
+ const waiting = Boolean(read?.turn && !terminalTaskTurn(read.turn.status));
+ const running = read?.turn?.status === "running";
+ async function start() {
+ if (flight.current || !ready || waiting || retained.unreadable) return;
+ flight.current = true; revision.current++; setBusy(true); setError("");
+ try {
+ let prior: TaskAttempt | null;
+ try {prior = readTaskAttempt(storageKey);} catch {
+ setRetained(previous => ({...previous, unreadable: true}));
+ throw new Error("The original Task request is unreadable");
+ }
+ attemptRef.current = prior;
+ const current = await fetchManagedTaskEntry(target, {operationId: prior?.operationId,
+ todoId: prior?.todoId, signal: AbortSignal.timeout(8000)});
+ if (!live.current) return;
+ setRead(current);
+ if (prior?.turnId && current.turn?.turn_id !== prior.turnId) throw new Error("The original Task Turn is unavailable");
+ if (current.turn && !terminalTaskTurn(current.turn.status)) {await accept(current.turn); return;}
+ if (!current.available || current.task.state !== "ready" || current.task.canonical_done || current.task.observation.check_count < 1
+ || prior && current.task.todo_id !== prior.todoId) throw new Error("Original Task source changed");
+ const next = prior && !current.turn ? prior : {operationId: `task.${crypto.randomUUID()}`, todoId: current.task.todo_id};
+ retain(next);
+ const accepted = await startManagedTaskTurn(target, next.todoId, next.operationId, AbortSignal.timeout(15000));
+ if (live.current) await accept(accepted.turn);
+ } catch {
+ if (live.current) {setRead(null); setError(zh ? "执行结果尚未确认。先读取原请求,不会自动重发。" : "Launch is unconfirmed. Read the original request first; it will not be resent automatically.");}
+ } finally {
+ flight.current = false;
+ if (live.current) {setBusy(false); setRefresh(value => value + 1);}
+ }
+ }
+ const confirmed = read?.task.state === "ready" && read.task.observation.check_count > 0;
+ if (confirmed || retained.unreadable || attempt) shown.current = true;
+ if (!shown.current) return null;
+ return
+
+
+ {running ? (zh ? "正在推进当前任务" : "Working on the current Task") : waiting ? (zh ? "已提交,等待执行" : "Submitted; waiting to run") : read?.task.state === "ready" && read.task.canonical_done
+ ? (zh ? "当前任务已完成" : "Current Task completed") : (zh ? "当前任务" : "Current Task")}
+
+
+
+ {zh ? "在原会话推进当前任务,使用已确认的检查和现有额度。" : "Advance the current Task in its original conversation using its confirmed checks and existing allowance."}
+ {read?.task.state === "ready" ? {zh ? `${read.task.observation.check_count} 项检查 · ${read.task.observation.pinned_file_count} 个固定来源文件` : `${read.task.observation.check_count} checks · ${read.task.observation.pinned_file_count} pinned source files`}
: null}
+
+
+
+
+ {error ? {error}
: null}
+ {read && !ready && !waiting && !read.task.canonical_done ? {zh ? "当前任务暂不能执行,请读取检查或原会话状态。" : "The Task cannot run yet. Read its checks or original conversation state."}
: null}
+ ;
+}
+
+function CoordinatorMode({sessionId, onPrepare, onExecute, onChange}: GoalLoopXModeProps) {
const {locale} = useWorkspaceI18n();
const zh = locale === "zh-CN";
const [snapshot, setSnapshot] = useState(null);
diff --git a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx
index 4a427fe472..3fbd3cd1d4 100644
--- a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx
+++ b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx
@@ -2988,7 +2988,9 @@ export function PersonalWorkspacePage({
: !runtimeSourceUnavailable && selectedGoal?.loadState === "loading" && selectedGoalTab === "overview" ? : null}
{!readOnly ? openSettings({ kind: "settings", tab: "machine" })} /> : null}
- {selectedGoalId && selectedGoalTab === "chat" && !agentWorkActive && !readOnly && selectedAgentId === "codex" && callbacks.onStartLoopX ? {await callbacks.onObserveConversationQueue!(conversationKey, workspaceConversations.managed!.target.sessionId);}} : undefined}
onPrepare={() => callbacks.onPrepareLoopX!(selectedAgentId, selectedGoalId)}
key={`${selectedGoalId}:${selectedAgentId}`} sessionId={conversationSessionId} onChange={setLoopxMode}
onExecute={(operation, settings) => callbacks.onStartLoopX?.(operation, selectedAgentId, selectedGoalId, settings)}
diff --git a/docs/architecture/rfcs/assets/goal-entry-original-task-desktop.webp b/docs/architecture/rfcs/assets/goal-entry-original-task-desktop.webp
new file mode 100644
index 0000000000..5ef8d150f4
Binary files /dev/null and b/docs/architecture/rfcs/assets/goal-entry-original-task-desktop.webp differ
diff --git a/docs/architecture/rfcs/assets/goal-entry-original-task-narrow.webp b/docs/architecture/rfcs/assets/goal-entry-original-task-narrow.webp
new file mode 100644
index 0000000000..b8ea37fd83
Binary files /dev/null and b/docs/architecture/rfcs/assets/goal-entry-original-task-narrow.webp differ
diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.md
index 5d5536f400..e270bc7612 100644
--- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md
+++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md
@@ -4306,3 +4306,57 @@ qualification.


+
+### 2026-11-15 — Prepare existing checks and execute the original authorized Task
+
+- **Gap:** the original registered conversation could read work but could not
+ prepare its existing acceptance proposal without entering legacy coordinator
+ mode. Its frontend also lacked a caller for the existing native Task endpoint.
+ A scripted repair exposed an additional gap: native work inherited the
+ conversation's read-only prompt and sandbox without requesting Task permissions.
+- **Delta:** new managed Codex conversations advertise only the existing
+ `prepare_check` action. The host rechecks the original Session, active owner
+ Turn, registration, lifetime and workspace, and pins the actual existing
+ checker source. The existing acceptance owner resolves retained requirements
+ and the original Task. Owner check adoption remains separate from Task launch.
+ The existing primary control starts that Task in the original Session, using
+ its current checks, lease and allowance; lost replies retain the same operation.
+ An idle page reads once instead of adding continuous empty polling. Creation
+ shows the confirmed objective while retaining the internal execution request;
+ recorded historical display messages remain unchanged on recovery.
+- **Authority:** check preparation and adoption grant no writes. The existing
+ native Session owner maps an already approved whole-workspace boundary to the
+ host policy; absent or narrower approval remains read-only. Network and
+ temporary-directory writes remain disabled on this bounded native path.
+ Subsequent ordinary sends explicitly restore read-only policy, including after
+ uncertain native publication and direct callers. Session defaults and native
+ thread identity are preserved; older threads receive no new dynamic tools.
+- **Evidence:** real HTTP/Chat/Core/File/SQLite cases prepare a repository's
+ unchanged six-behavior cart checker, confirm its initial failure, then execute
+ the original Task after a separate existing owner workspace approval. The
+ repaired artifact passes those independent checks. Unconfirmed checks, changed
+ source, wrong output and missing write approval preserve an open Task without
+ debit. Packaged desktop/narrow journeys cover the same result, original history,
+ repeated operations, ordinary follow-up and bounded idle reads. Models and
+ editing are scripted; this does not qualify live-model or OS sandbox behavior.
+- **Maintainability:** identity, acceptance, native admission and settlement
+ retain their existing owners, including C1 composition. Prompt/input adaptation
+ stays in the native adapter; attached attachment refusal moves to its queue
+ owner. Runtime and Chat Agent stay within their existing reviewed ceilings.
+- **Boundary:** this delivers an existing-checker, already-authorized original
+ Task path for V2/V4/R1. It does not infer arbitrary validation from natural
+ language, promote a new Goal's write authority, support unenforceable narrow
+ write scopes, or qualify unsupported source-inspection hosts. The original ten
+ requirements, live model/account and context retention, D2/D5 closure,
+ progressive Standard journeys, comparable complete costs, full V1–V5/V10,
+ R1/M3 and C1 cutover remain open. Full original-goal regression still precedes
+ completion and the subsequent external benchmark work.
+
+These current design references show the packaged frontend with real SQLite and
+Chat owners, an explicit prior workspace approval and scripted model work. The
+desktop view exposes the original Task control after check adoption; the narrow
+view shows its independently checked result in the same conversation.
+
+
+
+
diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md
index 0f8de6b1b8..b5f20163e0 100644
--- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md
+++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md
@@ -3341,3 +3341,43 @@ R1/M3、C1 切换和原目标回归仍未完成资格验证。


+
+### 2026-11-15 — 准备既有检查并执行原已授权 Task
+
+- **缺口:**原注册会话能读取工作,但准备既有验收方案仍需进入旧协调模式;
+ 前端也没有调用既有原生 Task endpoint 的入口。合成修复还暴露了另一处缺口:
+ 原生工作继承会话的只读 prompt 和 sandbox,没有请求本次 Task 权限。
+- **增量:**新 managed Codex 会话仅提供既有 `prepare_check` action。Host
+ 复核原 Session、活动 owner Turn、注册身份、生命周期和 workspace,并固定实际
+ 已有检查器的源码。既有验收 owner 解析保留要求及原 Task;owner 采用检查与启动
+ Task 继续分开。既有主控件沿原 Session 启动该 Task,使用当前检查、lease 和额度;
+ 响应丢失保留原 operation。空闲页面只读取一次,不新增持续空查。创建时显示用户
+ 确认的目标,内部执行请求继续保留;恢复不改写历史已记录的展示消息。
+- **权限:**准备和采用检查都不授予写权限。既有原生 Session owner 仅将已经批准
+ 的完整 workspace 边界映射到 host policy;缺少批准或只有更窄批准时保持只读。
+ 此限定原生路径仍禁用网络和临时目录写入。后续普通 send 显式恢复只读,包括原生
+ 发布结果未知之后以及直接调用者。Session 默认值和原生 thread 身份保留,旧 thread
+ 不新增 dynamic tools。
+- **证据:**真实 HTTP/Chat/Core/File/SQLite 用例从仓库保留的六行为购物车检查器
+ 准备方案,确认初始失败,再经独立的既有 owner workspace 批准执行原 Task。
+ 修复产物通过未改变的独立检查。检查未确认、来源改变、错误产物和缺少写批准时,
+ Task 保持 open 且不扣额度。Packaged 桌面/窄屏旅程覆盖同一结果、原历史、重复
+ operation、普通追问和有界空闲读取。模型解释与编辑由脚本模拟,不构成真实模型
+ 或 OS sandbox 资格验证。
+- **可维护性:**身份、验收、原生准入和结算仍由既有 owner 管理,并沿用 C1
+ composition。Prompt/input 适配放在原生 adapter,attached 附件拒绝归其 queue
+ owner。Runtime 和 Chat Agent 都保持在既有 reviewed ceiling 内。
+- **边界:**本次交付 V2/V4/R1 中“既有检查器、原已授权 Task”的路径,不从任意
+ 自然语言推断验收,不提升新 Goal 的写权限,不支持 host 无法落实的窄写范围,也
+ 不为不支持安全来源检查的 host 取得资格。原十项要求、真实 model/account 与
+ context 保留、D2/D5 闭包、渐进 Standard 旅程、可比完整成本、完整 V1–V5/V10、
+ R1/M3 和 C1 切换仍未闭合。完成前仍需完整原目标回归,随后才进入外部 benchmark
+ 工作。
+
+下方当前设计参考使用 packaged frontend、真实 SQLite/Chat owner、明确的先行
+workspace 批准和脚本模型工作。桌面视图在采用检查后显示原 Task 主控件;窄屏视图
+在同一会话显示经独立检查的结果。
+
+
+
+
diff --git a/loopx/attached_session.py b/loopx/attached_session.py
index 6ba0bdeeff..7c0f7ba627 100644
--- a/loopx/attached_session.py
+++ b/loopx/attached_session.py
@@ -767,7 +767,10 @@ def _enqueue_attached_agent_turn_under_grant(
def enqueue_attached_agent_turn(*, store: ChatSessionStore, registry_path: Path | None,
session_id: str, client_turn_id: str, message: str, origin: str,
- external_agent_target: dict[str, Any] | None = None) -> tuple[dict[str, Any], bool]:
+ external_agent_target: dict[str, Any] | None = None,
+ attachments: object = None) -> tuple[dict[str, Any], bool]:
+ if attachments:
+ raise ValueError("attached host session queue does not yet accept attachments")
kwargs = dict(store=store, registry_path=registry_path, session_id=session_id,
client_turn_id=client_turn_id, message=message, origin=origin,
external_agent_target=external_agent_target)
diff --git a/loopx/capabilities/native_chat/codex_adapter.py b/loopx/capabilities/native_chat/codex_adapter.py
index ca62c0f7b1..7fd5dd5d58 100644
--- a/loopx/capabilities/native_chat/codex_adapter.py
+++ b/loopx/capabilities/native_chat/codex_adapter.py
@@ -5,7 +5,9 @@
"""
from __future__ import annotations
-from dataclasses import dataclass, replace
+from contextlib import contextmanager
+from copy import deepcopy
+from dataclasses import dataclass, field, replace
import hashlib
import json
import logging
@@ -737,6 +739,7 @@ def turns() -> list[dict[str, Any]]:
class CodexAppServerAdapter:
session: CodexChatAgentSession
goal_driver: CodexGoalDriver | None = None
+ _managed_read_turn_guard: Callable[[], None] | None = field(default=None, repr=False)
def completed_work_observation(self, *, thread_ids: list[str], turn_id: str,
known_turn_ids: set[str] | None = None) -> dict[str, Any] | None:
@@ -1004,7 +1007,32 @@ def capabilities(self) -> dict[str, Any]:
}
def start_turn(self, message: str, event_sink: Callable[[str, dict[str, Any]], None]) -> dict[str, Any]:
- return self.session.send(message, on_event=event_sink)
+ return self.session.send(message, on_event=event_sink, **self._ordinary_turn_arguments())
+
+ def _ordinary_turn_arguments(self):
+ check = self._managed_read_turn_guard
+ if check is None:
+ return {}
+ previous_guard = self.session._launch_guard
+ @contextmanager
+ def read_turn():
+ check()
+ if previous_guard is None:
+ yield
+ else:
+ with previous_guard():
+ check()
+ yield
+ # Native sandboxPolicy is sticky across subsequent Turns. Reassert the
+ # current managed Chat read boundary without changing Session defaults.
+ return {"sandbox_policy": {"type": "readOnly", "networkAccess": False},
+ "turn_start_guard": read_turn}
+
+ def start_native_task_turn(self, message: str,
+ event_sink: Callable[[str, dict[str, Any]], None], policy: dict[str, object]) -> dict[str, Any]:
+ """Transport one Core-admitted Task through its existing launch fence."""
+ return self.session.send(message, on_event=event_sink, _native_task=True,
+ sandbox_policy=deepcopy(policy), turn_start_guard=self.session._launch_guard)
def steer_turn(self, message: str, expected_turn_id: str, client_message_id: str | None = None) -> str:
return self.session.steer(message, expected_turn_id=expected_turn_id,
@@ -1021,7 +1049,8 @@ def start_turn_with_attachments(
event_sink: Callable[[str, dict[str, Any]], None],
attachments: list[dict[str, Any]],
) -> dict[str, Any]:
- return self.session.send(message, attachments=attachments, on_event=event_sink)
+ return self.session.send(message, attachments=attachments, on_event=event_sink,
+ **self._ordinary_turn_arguments())
def interrupt_turn(self, turn_id: str | None = None) -> None:
driver = self.goal_driver
@@ -1053,6 +1082,60 @@ def start_attachment_turn(adapter: Any, session: dict[str, Any], turn: dict[str,
return adapter.start_turn_with_attachments(message, event_sink, attachments)
+def prepare_native_turn_text(session: CodexChatAgentSession, user_message: str, *,
+ output_schema, project_collaboration: bool, native_task: bool,
+ sandbox_policy, turn_start_guard):
+ """Preserve Chat input validation; adapt only the fenced Task invocation.
+
+ The Core caller owns Task/lease/permission admission. This transport cannot
+ manufacture that grant from a policy dictionary or a model/browser payload.
+ """
+ text = str(user_message or "")
+ if not text.strip():
+ raise ValueError("user message is required")
+ if native_task:
+ workspace_policy = {"type": "workspaceWrite", "writableRoots": [str(session.work_dir.resolve())],
+ "networkAccess": False, "excludeTmpdirEnvVar": True, "excludeSlashTmp": True}
+ if (turn_start_guard is None or session._launch_guard is None
+ or turn_start_guard is not session._launch_guard
+ or sandbox_policy not in ({"type": "readOnly", "networkAccess": False}, workspace_policy)
+ or session.execution_mode or session.read_only_review or session.project_context is not None
+ or session.permissions_profile is not None or session.sandbox != "read-only"):
+ raise ValueError("native Task transport requires the original read-only Session, bound workspace policy and current host launch guard")
+ elif sandbox_policy is not None and sandbox_policy != {"type": "readOnly", "networkAccess": False}:
+ raise ValueError("an ordinary Chat Turn cannot install a native execution policy")
+ if sandbox_policy is not None and session.permissions_profile is not None:
+ raise ValueError("a native sandbox policy cannot replace an existing named permissions profile")
+ if session.read_only_review and not session.metadata_review and not session.answer_review:
+ text = (
+ "Review the existing results of the interrupted original request below. "
+ "Its earlier execution may have already changed files or external systems. "
+ "Use the original native history and current local artifacts to verify what actually happened. "
+ "This Turn is read-only: do not re-execute the business request, write, send, delegate or start background work. "
+ "Return a clear answer to the original user, distinguishing verified results from remaining gaps. "
+ "If verification is incomplete, report the concrete limitation; do not claim completion. "
+ "Original request: " + text
+ )
+ if project_collaboration:
+ if (session.execution_mode or session.read_only_review or output_schema is not None
+ or not session.project_context or session.project_context.get("audience") != "bound_owner"):
+ raise ValueError("original project collaboration requires its existing bound project session")
+ from ...control_plane.effect_runtime import effect_runtime_result
+ output_schema = effect_runtime_result("collaboration.project.response_schema", {})
+ if output_schema is not None and not session.execution_mode and not project_collaboration and not native_task:
+ raise ValueError("structured Turn output requires an execution session")
+ return text, output_schema
+
+
+def native_runtime_context(controller: ChatRuntimeController, *, goal_id: str | None,
+ objective: str, manager_profile: Mapping[str, object] | None,
+ project_coordination: bool, execution_mode: bool) -> dict[str, str]:
+ """Compose the shared native adapter inputs in their construction owner."""
+ return {"objective": controller._session_objective(goal_id=goal_id, objective=objective,
+ project_coordination=project_coordination and not execution_mode),
+ "runtime_profile": str(manager_profile["runtime_profile"]) if manager_profile else "restricted"}
+
+
def start_runtime_adapter(controller: ChatRuntimeController, *, work_dir: Path, goal_id: str | None,
native_context: Mapping[str, str], manager_profile: Mapping[str, object] | None,
model_config: Mapping[str, str | None], history: list[dict[str, str]] | None,
@@ -1061,13 +1144,16 @@ def start_runtime_adapter(controller: ChatRuntimeController, *, work_dir: Path,
read_only_review: bool, metadata_review_context: dict[str, object] | None,
answer_review_context: dict[str, object] | None,
history_check: Callable[[], None] | None = None,
- working_continuation: NativeWorkingContinuation | None = None) -> CodexAppServerAdapter:
+ working_continuation: NativeWorkingContinuation | None = None,
+ check_preparation: bool = False,
+ managed_read_default: bool = False) -> CodexAppServerAdapter:
"""Build the native adapter from already-authorized runtime arguments."""
from ...chat_manager import MANAGER_AGENT_GOAL_ID
from ..manager_context.inspection import READ_TOOL, CONTEXT_READ_TOOL
from ...chat_loopx_mode import TOOL as COLLABORATION_TOOL
+ from ...chat.coordination import check_preparation_tool
review_context = metadata_review_context or answer_review_context
- return CodexAppServerAdapter.start(
+ adapter = CodexAppServerAdapter.start(
codex_bin=controller.codex_bin,
account_runtime_root=controller.coordination_runtime_root,
account_consumer="steward" if manager_profile is not None or review_context is not None else "worker",
@@ -1101,8 +1187,13 @@ def start_runtime_adapter(controller: ChatRuntimeController, *, work_dir: Path,
service_tier=model_config.get("service_tier"),
dynamic_tools=[READ_TOOL] if answer_review_context else (
[READ_TOOL] if goal_id == MANAGER_AGENT_GOAL_ID
- else [CONTEXT_READ_TOOL, *([COLLABORATION_TOOL] if loopx_tools else [])]
+ else [CONTEXT_READ_TOOL, *([COLLABORATION_TOOL] if loopx_tools else
+ [check_preparation_tool()] if check_preparation and resume_thread_id is None
+ and working_continuation is None else [])]
) if not execution_mode and not read_only_review and (
goal_id == MANAGER_AGENT_GOAL_ID or project_coordination
) else None,
)
+ if managed_read_default:
+ adapter.session._managed_goal_read_default = True
+ return adapter
diff --git a/loopx/capabilities/native_chat/queue_api.py b/loopx/capabilities/native_chat/queue_api.py
index 17be78f6d3..805fab86cb 100644
--- a/loopx/capabilities/native_chat/queue_api.py
+++ b/loopx/capabilities/native_chat/queue_api.py
@@ -1,11 +1,42 @@
-"""HTTP projection and explicit steering of the existing persisted queue."""
+"""HTTP transport for original Session Tasks and the existing persisted queue."""
from typing import Any
+from urllib.parse import parse_qs, urlparse
from ...chat_store import CHAT_STORE_SCHEMA_VERSION
class ChatQueueRequestMixin:
+ def _managed_native_turn(self, session_id: str, *, execute: bool = False) -> None:
+ from .steward_managed_mode import ManagedSessionTurn
+ service = ManagedSessionTurn(self.server.runtime_controller)
+ try:
+ if execute:
+ body = self._read_json()
+ if set(body) - {"agent_id", "operation_id", "todo_id"}:
+ raise ValueError("unsupported managed Turn arguments")
+ turn, created = service.submit(session_id, **body)
+ return self._send_json({"ok": True, "session_id": session_id, "turn": turn, "created": created}, status=202)
+ query = parse_qs(urlparse(self.path).query, keep_blank_values=True)
+ sources = query.get("calendar_task_sources", ["false"])
+ if sources not in (["true"], ["false"]):
+ raise ValueError("calendar_task_sources must be one true or false value")
+ include_sources = sources == ["true"]
+ original_task = query.get("original_task", ["false"])
+ if original_task not in (["true"], ["false"]):
+ raise ValueError("original_task must be one true or false value")
+ include_original_task = original_task == ["true"]
+ if (include_sources or include_original_task) and (set(query) - {"calendar_task_sources", "original_task", "agent_id", "operation_id"}
+ or any(len(values) != 1 for values in query.values())):
+ raise ValueError("select one original managed Session and Agent for Task sources")
+ self._send_json(service.inspect(session_id, agent_id=query.get("agent_id", [None])[0],
+ operation_id=query.get("operation_id", [None])[0], include_calendar_task_sources=include_sources,
+ include_original_task=include_original_task))
+ except KeyError:
+ self._send_error("chat session was not found", status=404)
+ except (TypeError, ValueError, RuntimeError) as exc:
+ self._send_error(str(exc), status=409, error_code="managed_turn_unavailable")
+
def _dispatch_chat_queue(self, path: str, *, apply: bool) -> bool:
parts = path.strip("/").split("/")
if parts[:3] != ["api", "chat", "sessions"] or len(parts) < 5 or parts[4] != "queue":
diff --git a/loopx/capabilities/native_chat/steward_managed_mode.py b/loopx/capabilities/native_chat/steward_managed_mode.py
index 5eea668732..7801fa3445 100644
--- a/loopx/capabilities/native_chat/steward_managed_mode.py
+++ b/loopx/capabilities/native_chat/steward_managed_mode.py
@@ -304,7 +304,8 @@ def admit(self, request: dict[str, Any], *, turn: dict[str, Any] | None = None,
"queued_turn_count": len(self.store.queued_turns(actor["session_id"]))})
def inspect(self, session_id: str, *, agent_id: str | None = None,
- operation_id: str | None = None, include_calendar_task_sources: bool = False) -> dict[str, Any]:
+ operation_id: str | None = None, include_calendar_task_sources: bool = False,
+ include_original_task: bool = False) -> dict[str, Any]:
session = self.store.load_session(session_id)
if not session:
raise KeyError("chat session was not found")
@@ -322,6 +323,10 @@ def inspect(self, session_id: str, *, agent_id: str | None = None,
result["available"] = True
except ValueError as exc:
result["reason"] = str(exc)
+ if include_original_task:
+ if agent_id is not None and agent_id != session.get("managed_agent_id"):
+ raise ValueError("select the original registered Agent for Task entry")
+ result["task"] = self._original_task_entry(session_id)
if session.get("managed_agent_id"):
from .steward_reports import ManagedSessionReports
from .session_calendar_tasks import SessionCalendarTasks
@@ -336,6 +341,40 @@ def inspect(self, session_id: str, *, agent_id: str | None = None,
result["calendar_task_sources"] = SessionCalendarTasks(self.controller).source_options(session_id)
return result
+ def _original_task_entry(self, session_id: str) -> dict[str, Any]:
+ """Observe the existing creation/validation owners without any effects.
+
+ The returned plan does not claim a Task or authorize a model. Native
+ submit still rechecks current admission and every validation source.
+ """
+ from ...control_plane.effect_runtime import effect_runtime_result
+ from ...control_plane.goals.acceptance import inspect_goal_acceptance
+
+ session = self.store.load_session(session_id) or {}
+ request = self._request(session_id, session.get("managed_agent_id") or "", "original-task-preview")
+ actor = request["actor"]
+ unavailable: dict[str, Any] = {"todo_id": None, "state": "unbound", "source": None,
+ "canonical_done": False}
+ try:
+ self.admit(request)
+ basis = inspect_goal_acceptance(registry_path=self.controller.registry_path,
+ runtime_root=str(self.controller.coordination_runtime_root), goal_id=actor["goal_id"],
+ agent_id=actor["agent_id"], validation_workspace_path=Path(actor["workspace_path"]))
+ selected = effect_runtime_result("goal.task.creation_selection", {"basis": basis})
+ if selected["todo_id"] is None:
+ return {**unavailable, "reason": selected["reason"]}
+ todo_id = selected["todo_id"]
+ unavailable["todo_id"] = todo_id
+ request["todo_id"] = todo_id
+ self.admit(request)
+ plan = self._validation_source(request, todo_id)["plan"]
+ # Return only the display observation; commands, pins and private
+ # declarations stay with their existing owner.
+ self.admit(request)
+ return {key: plan[key] for key in ("todo_id", "state", "source", "observation", "canonical_done")}
+ except (ValueError, ManagedTaskValidationUnavailable) as exc:
+ return {**unavailable, "reason": str(exc)}
+
def submit(self, session_id: str, *, agent_id: str, operation_id: str,
todo_id: str | None = None, monitor_deadline: str | None = None,
report_window: dict[str, Any] | None = None,
diff --git a/loopx/capabilities/native_chat/steward_turn.py b/loopx/capabilities/native_chat/steward_turn.py
index b6f68efa18..77c7a49fb4 100644
--- a/loopx/capabilities/native_chat/steward_turn.py
+++ b/loopx/capabilities/native_chat/steward_turn.py
@@ -819,7 +819,14 @@ def launch():
adapter.session._launch_guard = launch
try:
- response = adapter.start_turn(prompt, event_sink)
+ if managed_turn and not governance_work:
+ from ...control_plane.effect_runtime import effect_runtime_result
+ policy = effect_runtime_result("collaboration.session.managed_turn.sandbox_policy", {
+ "host": request["host"], "actor": actor, "authority": authority,
+ "validation": managed_turn.validation_basis["plan"]})
+ response = adapter.start_native_task_turn(prompt, event_sink, policy)
+ else:
+ response = adapter.start_turn(prompt, event_sink)
finally:
adapter.session._launch_guard = previous_guard
current() # Revocation/stop/retarget after a long model call wins.
diff --git a/loopx/chat/coordination.py b/loopx/chat/coordination.py
index 1f47003fcd..6f3399b920 100644
--- a/loopx/chat/coordination.py
+++ b/loopx/chat/coordination.py
@@ -6,6 +6,14 @@
from __future__ import annotations
+from copy import deepcopy
+import hashlib
+import os
+from pathlib import Path
+import shutil
+import stat
+import sys
+
PROJECT_COORDINATION_GUIDANCE = (
"This conversation concerns only the selected LoopX Goal. Read its current work, "
"member commitments and evidence before suggesting changes. Use loopx_context_read "
@@ -32,6 +40,211 @@
PROJECT_CONTEXT_VERSION = 2
+def check_preparation_tool():
+ """Project the existing proposal action for a newly bound managed thread."""
+ from ..chat_loopx_mode import TOOL
+ tool = deepcopy(TOOL)
+ tool["description"] = (
+ "Prepare a reviewable delivery check for this original registered Goal and Agent. "
+ "Use action=prepare_check with a stable operation_id and the existing compact "
+ "acceptance document: outcome_id and criteria [{id, validation_argv, oracle}]. "
+ "Read retained requirements with loopx_context_read first. Select an existing "
+ "independent checker from this Goal workspace using [python3, relative.py] or "
+ "[relative/executable], without options or extra arguments. The host pins its "
+ "actual source bytes and verifies python3 resolves to the host interpreter. Each oracle "
+ "is {kind: owner_pinned_oracle, source_id, input_refs, output_refs}; name the "
+ "explicit delivery files in output_refs. Do not invent a checker or replace "
+ "owner intent. The host supplies Goal, Agent, workspace and runtime identity. "
+ "Preparation saves only a goal.acceptance.check proposal. Explain its purpose "
+ "and effects for local-owner review; it neither configures acceptance nor runs "
+ "checks, claims work or launches a Turn. The owner judges whether the checker "
+ "addresses the requested outcome before applying it."
+ )
+ properties = tool["inputSchema"]["properties"]
+ tool["inputSchema"]["properties"] = {
+ key: properties[key] for key in ("action", "operation_id", "document")
+ }
+ tool["inputSchema"]["properties"]["document"]["description"] = (
+ "Existing compact acceptance document with outcome_id, criteria and optional scope. "
+ "Each criterion selects an existing requirement id, supported validation_argv, "
+ "and owner_pinned_oracle with explicit source_id, input_refs and output_refs. "
+ "Optional validation_files must match actual host source pins."
+ )
+ tool["inputSchema"]["properties"]["action"]["enum"] = ["prepare_check"]
+ tool["inputSchema"]["required"] = ["action", "operation_id", "document"]
+ return tool
+
+
+def _workspace_file(workspace: Path, ref: str, *, required: bool) -> str | None:
+ """Observe a regular relative file without following any symlink component.
+
+ Missing delivery files are legal during preparation. Descriptor-relative
+ opens keep a replaced parent from redirecting a source read outside the
+ original workspace; source digests are host observations, not verdicts.
+ """
+ if os.open not in os.supports_dir_fd or not all(hasattr(os, flag) for flag in ("O_DIRECTORY", "O_NOFOLLOW", "O_NONBLOCK")):
+ raise ValueError("this host cannot safely inspect workspace checker sources")
+ if (not isinstance(ref, str) or not ref or "\\" in ref or "\0" in ref
+ or ref.startswith("/") or any(part in {"", ".", ".."} for part in ref.split("/"))):
+ raise ValueError("checker files must remain relative to the original workspace")
+ descriptors = []
+ try:
+ parent = os.open(workspace, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
+ descriptors.append(parent)
+ parts = ref.split("/")
+ for part in parts[:-1]:
+ parent = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent)
+ descriptors.append(parent)
+ source = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent)
+ descriptors.append(source)
+ if not stat.S_ISREG(os.fstat(source).st_mode):
+ raise ValueError("checker sources and present artifacts must be regular files")
+ if not required:
+ return None
+ digest = hashlib.sha256()
+ while chunk := os.read(source, 1024 * 1024):
+ digest.update(chunk)
+ return digest.hexdigest()
+ except FileNotFoundError:
+ if not required:
+ return None
+ raise ValueError("the selected independent checker source is unavailable") from None
+ except OSError:
+ raise ValueError("checker sources and present artifacts must be readable regular files without symlinks") from None
+ finally:
+ for descriptor in reversed(descriptors):
+ os.close(descriptor)
+
+
+class _GoalSessionCheckPreparation:
+ """Per-Turn source IO over the existing typed identity and acceptance owners."""
+ def __init__(self, controller, adapter, session, turn_id, read):
+ self.controller, self.adapter, self.read = controller, adapter, read
+ self.session_id, self.turn_id = session["session_id"], turn_id
+ self.workspace = Path(adapter.session.work_dir)
+ self.runtime_root = controller.coordination_runtime_root
+ self.registry_path = controller.registry_path
+ self.original = deepcopy(session)
+ self.identity = self._current_identity()
+
+ def _current_identity(self):
+ from ..capabilities.native_chat.steward_managed_mode import registered_managed_session_identity
+ from ..control_plane.collaboration import conversation_scope
+ controller = self.controller
+ session = controller.store.load_session(self.session_id) or {}
+ turn = controller.store.load_turn(self.session_id, self.turn_id) or {}
+ fields = ("session_id", "goal_id", "goal_instance_id", "managed_agent_id",
+ "managed_workspace_path", "agent_id", "executor_endpoint_id", "adapter_kind",
+ "session_mode", "upstream_mode", "upstream_thread_id", "channel_id",
+ "project_context", "steward_context", "codex_home", "loopx_tools", "loopx_mode")
+ if (controller.closed.is_set() or controller.registry_path != self.registry_path
+ or controller.coordination_runtime_root != self.runtime_root
+ or any(session.get(key) != self.original.get(key) for key in fields)
+ or session.get("active_turn_id") != self.turn_id
+ or turn.get("session_id") != self.session_id or turn.get("turn_id") != self.turn_id
+ or turn.get("status") not in {"starting", "running"} or turn.get("origin") != "web"
+ or turn.get("loopx_execution") or turn.get("loopx_request")
+ or "collaboration_request" in turn or session.get("upstream_mode") != "chat"
+ or session.get("loopx_tools") or (session.get("loopx_mode") or {}).get("enabled")
+ or self.adapter.session.thread_id != session.get("upstream_thread_id")
+ or self.adapter.session.execution_mode or self.adapter.session.read_only_review
+ or getattr(self.adapter, "goal_driver", None) is not None
+ or Path(self.adapter.session.work_dir) != self.workspace
+ or conversation_scope(session, origin="web")["kind"] != "owner_goal"):
+ raise ValueError("the original local-owner managed Session and active read-only Turn are unavailable")
+ return registered_managed_session_identity(registry_path=self.registry_path,
+ goal_id=session.get("goal_id"), agent_id=session.get("managed_agent_id"),
+ workspace=self.workspace, session=session)
+
+ def _current(self):
+ if self._current_identity() != self.identity:
+ raise ValueError("the original managed Goal lifetime or Agent scope changed")
+
+ @staticmethod
+ def _python_interpreter():
+ executable = shutil.which("python3")
+ if executable is None or Path(executable).resolve() != Path(sys.executable).resolve():
+ raise ValueError("the supported python3 token is unavailable for this host interpreter")
+
+ def _document(self, document):
+ # Accepted document syntax, requirements, scope and oracle semantics
+ # remain with the TS owner. Only invocation/source IO is narrowed here.
+ document = deepcopy(document)
+ criteria = document.get("criteria")
+ if not isinstance(criteria, list) or not 1 <= len(criteria) <= 64:
+ raise ValueError("select bounded existing acceptance criteria and independent checker sources")
+ sources = {}
+ for criterion in criteria:
+ if not isinstance(criterion, dict):
+ raise ValueError("a check requires its existing criterion and checker source")
+ argv = criterion.get("validation_argv")
+ if (not isinstance(argv, list) or not argv or any(not isinstance(arg, str) for arg in argv)):
+ raise ValueError("select an immediate Python script or direct pinned executable")
+ if len(argv) == 2 and argv[0] in {"python", "python3", sys.executable} and argv[1].endswith(".py"):
+ source = argv[1]
+ self._python_interpreter()
+ criterion["validation_argv"] = ["python3", source]
+ elif len(argv) == 1 and "/" in argv[0]:
+ source = argv[0]
+ else:
+ raise ValueError("checker invocation supports only an immediate Python script or direct source, without options or extra arguments")
+ oracle = criterion.get("oracle")
+ if not isinstance(oracle, dict) or oracle.get("kind") != "owner_pinned_oracle":
+ raise ValueError("select an existing owner-pinned independent checker with explicit oracle outputs")
+ inputs, outputs = oracle.get("input_refs"), oracle.get("output_refs")
+ if (not isinstance(inputs, list) or not isinstance(outputs, list)
+ or len(inputs) > 20 or not 1 <= len(outputs) <= 20):
+ raise ValueError("an independent checker requires bounded explicit input and output refs")
+ if source in inputs or source in outputs:
+ raise ValueError("the independent checker source cannot be a checked input or delivery output")
+ self._current()
+ digest = _workspace_file(self.workspace, source, required=True)
+ self._current()
+ if source in sources and sources[source] != digest:
+ raise ValueError("the checker source changed during preparation")
+ pins = [{"path": source, "sha256": digest}]
+ if "validation_files" in criterion and criterion["validation_files"] != pins:
+ raise ValueError("the claimed checker source pin does not match the original workspace")
+ criterion["validation_files"] = pins
+ sources[source] = digest
+ for ref in [*inputs, *outputs]:
+ self._current()
+ _workspace_file(self.workspace, ref, required=False)
+ self._current()
+ # Reobserve the sources before publishing an immutable proposal; never
+ # refresh saved intent when a checker changed after a lost reply.
+ for source, digest in sources.items():
+ self._current()
+ if _workspace_file(self.workspace, source, required=True) != digest:
+ raise ValueError("the checker source changed during preparation")
+ self._current()
+ if any(row["validation_argv"][0] == "python3" for row in criteria):
+ self._python_interpreter()
+ return document
+
+ def __call__(self, tool, arguments):
+ from ..chat_loopx_mode import TOOL
+ if tool != TOOL["name"]:
+ return self.read(tool, arguments)
+ from ..chat_action_store import ActionConflictError
+ from ..control_plane.goals.acceptance_actions import prepare_acceptance_check
+ try:
+ self._current()
+ if (not isinstance(arguments, dict) or set(arguments) != {"action", "operation_id", "document"}
+ or arguments["action"] != "prepare_check" or not isinstance(arguments["document"], dict)
+ or not isinstance(arguments["operation_id"], str) or not arguments["operation_id"].strip()):
+ raise ValueError("prepare_check accepts only its stable operation_id and acceptance document; the host supplies actor and source identity")
+ document = self._document(arguments["document"])
+ self._current()
+ return prepare_acceptance_check(registry_path=self.registry_path,
+ runtime_root=str(self.runtime_root), goal_id=self.original["goal_id"],
+ agent_id=self.original["managed_agent_id"], document=document,
+ operation_id=arguments["operation_id"], execute=True)
+ except (ActionConflictError, ValueError) as exc:
+ return {"ok": False, "error": "collaboration_request_rejected",
+ "next_action": f"Check preparation was refused ({exc}). Read the original Goal and saved proposal; retry an operation only with unchanged intent and sources. A new intent needs a new operation id. Preparation cannot change authority or run the check."}
+
+
def apply_context_handoff(
controller, scope, session, turn, response, context, *, execution_allowed
):
@@ -212,6 +425,16 @@ def scope_valid() -> bool:
),
)
adapter.session.read_tool_handler = inspection.read
+ adapter._managed_read_turn_guard = None
+ if (session.get("managed_agent_id") and turn.get("origin") == "web"
+ and not turn.get("loopx_request") and not turn.get("loopx_execution")
+ and not session.get("loopx_tools") and not (session.get("loopx_mode") or {}).get("enabled")
+ and not adapter.session.execution_mode and not adapter.session.read_only_review
+ and getattr(adapter, "goal_driver", None) is None
+ and scope["kind"] == "owner_goal" and session.get("upstream_mode") == "chat"):
+ adapter.session.read_tool_handler = _GoalSessionCheckPreparation(
+ controller, adapter, session, turn_id, inspection.read)
+ adapter._managed_read_turn_guard = adapter.session.read_tool_handler._current
context["evidence_sources"] = inspection.sources()
context = manager_index(context, status_on_demand=status_on_demand)
from ..capabilities.native_chat.external_conversations import ChatExternalConversations
diff --git a/loopx/chat/session_open.py b/loopx/chat/session_open.py
index 49c9b6d78f..167eff8947 100644
--- a/loopx/chat/session_open.py
+++ b/loopx/chat/session_open.py
@@ -222,3 +222,19 @@ def open_chat_session(
agent_model_id=agent_model_id or None,
**({"agent_reasoning_effort": agent_reasoning_effort} if agent_reasoning_effort is not None else {}),
)
+
+
+def goal_creation_display_message(store: ChatSessionStore, *, session_id: str, client_turn_id: str, objective: str) -> str:
+ """Show confirmed intent on creation; preserve the original display on retry.
+
+ The execution request remains unchanged. An old recorded message is never
+ rewritten using the Goal's later objective or a new presentation default.
+ """
+ turn = store.turn_for_client(session_id, client_turn_id)
+ if turn is None:
+ return objective
+ messages = [row for row in store.messages(session_id, strict=True)
+ if row.get("turn_id") == turn["turn_id"] and row.get("role") == "user"]
+ if len(messages) != 1 or not isinstance(messages[0].get("text"), str):
+ raise ValueError("The original first Turn display is unavailable; restore its recorded message")
+ return messages[0]["text"]
diff --git a/loopx/chat_actions.py b/loopx/chat_actions.py
index e0f2242094..57b61e41fc 100644
--- a/loopx/chat_actions.py
+++ b/loopx/chat_actions.py
@@ -844,7 +844,7 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None:
"Goal projection did not retain the selected Agent binding"
)
from functools import partial
- from .chat.session_open import read_goal_creation_session, recover_goal_creation_session, require_regular_session_paths
+ from .chat.session_open import read_goal_creation_session, recover_goal_creation_session, require_regular_session_paths, goal_creation_display_message
read_original_session = partial(read_goal_creation_session,
self.store, self.chat_store or getattr(self.runtime_controller, "store", None),
@@ -991,6 +991,8 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None:
message=first_turn_message,
work_dir=project,
objective=objective,
+ **({"display_message": goal_creation_display_message(turn_store, session_id=session_id,
+ client_turn_id=f"goal-start-{proposal_id}", objective=objective)} if expected_managed_agent else {}),
)
require_first_turn_readback(first_turn)
turn_result = {
diff --git a/loopx/chat_agent.py b/loopx/chat_agent.py
index 951c6832b8..d48ad62807 100644
--- a/loopx/chat_agent.py
+++ b/loopx/chat_agent.py
@@ -720,6 +720,8 @@ class CodexChatAgentSession:
_launch_guard: Callable[[], AbstractContextManager[None]] | None = field(
default=None, repr=False
)
+ _native_task_policy_used: bool = field(default=False, repr=False)
+ _managed_goal_read_default: bool = field(default=False, repr=False)
@classmethod
def start(
@@ -1734,28 +1736,15 @@ def send(
on_native_item: Callable[[dict[str, Any]], None] | None = None,
turn_start_guard: Callable[[], AbstractContextManager[None]] | None = None,
check_running: Callable[[], None] | None = None,
+ _native_task: bool = False,
+ sandbox_policy: dict[str, object] | None = None,
) -> dict[str, Any]:
- text = str(user_message or "")
- if not text.strip():
- raise ValueError("user message is required")
- if self.read_only_review and not self.metadata_review and not self.answer_review:
- text = (
- "Review the existing results of the interrupted original request below. "
- "Its earlier execution may have already changed files or external systems. "
- "Use the original native history and current local artifacts to verify what actually happened. "
- "This Turn is read-only: do not re-execute the business request, write, send, delegate or start background work. "
- "Return a clear answer to the original user, distinguishing verified results from remaining gaps. "
- "If verification is incomplete, report the concrete limitation; do not claim completion. "
- "Original request: " + text
- )
- if project_collaboration:
- if (self.execution_mode or self.read_only_review or output_schema is not None
- or not self.project_context or self.project_context.get("audience") != "bound_owner"):
- raise ValueError("original project collaboration requires its existing bound project session")
- from .control_plane.effect_runtime import effect_runtime_result
- output_schema = effect_runtime_result("collaboration.project.response_schema", {})
- if output_schema is not None and not self.execution_mode and not project_collaboration:
- raise ValueError("structured Turn output requires an execution session")
+ if not _native_task and (self._native_task_policy_used or self._managed_goal_read_default) and sandbox_policy is None:
+ sandbox_policy = {"type": "readOnly", "networkAccess": False}
+ from .capabilities.native_chat.codex_adapter import prepare_native_turn_text
+ text, output_schema = prepare_native_turn_text(self, user_message, output_schema=output_schema,
+ project_collaboration=project_collaboration, native_task=_native_task,
+ sandbox_policy=sandbox_policy, turn_start_guard=turn_start_guard)
with self._request_id_lock:
request_id = self.next_request_id
self.next_request_id += 1
@@ -1763,7 +1752,7 @@ def send(
text = _turn_prompt(
text,
context_summary=self.context_summary,
- execution_mode=self.execution_mode,
+ execution_mode=self.execution_mode or _native_task,
runtime_profile=self.runtime_profile,
project_work=self.project_context is not None and self.sandbox == "workspace-write",
public_source_read_context=self._public_source_read_context,
@@ -1777,6 +1766,10 @@ def send(
started_at = time.monotonic()
start_timeout = min(self.idle_timeout_sec, self.hard_timeout_sec
if self.hard_timeout_sec is not None else self.idle_timeout_sec)
+ if _native_task:
+ # Publication may be uncertain. Every subsequent ordinary send
+ # must narrow the sticky native policy, even after an exception.
+ self._native_task_policy_used = True
turn_result = self._request(
"turn/start",
{
@@ -1788,9 +1781,10 @@ def send(
# Chat renders native summaries, but a resumed thread may have
# disabled them. Request the public summary on each Chat Turn;
# execution hosts retain their own verbosity configuration.
- **({"summary": "concise"} if not self.execution_mode else {}),
+ **({"summary": "concise"} if not (self.execution_mode or _native_task) else {}),
"approvalPolicy": "never",
**({"permissions": self.permissions_profile} if self.permissions_profile else {}),
+ **({"sandboxPolicy": sandbox_policy} if sandbox_policy is not None else {}),
**(
{"outputSchema": output_schema} if output_schema is not None else {}
),
diff --git a/loopx/chat_runtime.py b/loopx/chat_runtime.py
index 37f27d424a..5fb51a3889 100644
--- a/loopx/chat_runtime.py
+++ b/loopx/chat_runtime.py
@@ -374,6 +374,8 @@ def _start_adapter(
manager_runtime: Mapping[str, Any] | None = None,
project_coordination: bool = False,
loopx_tools: bool = False,
+ check_preparation: bool = False,
+ managed_read_default: bool = False,
executor_model: Mapping[str, str | None] | None = None,
project_context: dict[str, str] | None = None,
agent_config: dict[str, str] | None = None,
@@ -412,11 +414,9 @@ def _start_adapter(
manager_runtime=manager_runtime, executor_model=executor_model,
agent_config=agent_config, execution_mode=execution_mode,
)
- native_context = {
- "objective": self._session_objective(goal_id=goal_id, objective=objective,
- project_coordination=project_coordination and not execution_mode),
- "runtime_profile": str(manager_profile["runtime_profile"]) if manager_profile else "restricted",
- }
+ from .capabilities.native_chat.codex_adapter import native_runtime_context, start_runtime_adapter
+ native_context = native_runtime_context(self, goal_id=goal_id, objective=objective,
+ manager_profile=manager_profile, project_coordination=project_coordination, execution_mode=execution_mode)
if agent_id == "antigravity":
from .capabilities.native_chat.antigravity_adapter import AntigravityAdapter
if execution_mode or project_context is not None or read_only_review:
@@ -433,11 +433,12 @@ def _start_adapter(
hard_timeout_sec=self.hard_timeout_sec,
)
if agent_id == "codex":
- from .capabilities.native_chat.codex_adapter import start_runtime_adapter
return start_runtime_adapter(self, work_dir=work_dir, goal_id=goal_id, native_context=native_context,
manager_profile=manager_profile, model_config=model_config, history=history,
resume_thread_id=resume_thread_id, execution_mode=execution_mode, project_context=project_context,
project_coordination=project_coordination, loopx_tools=loopx_tools,
+ check_preparation=check_preparation,
+ managed_read_default=managed_read_default,
codex_home_override=codex_home_override, read_only_review=read_only_review,
metadata_review_context=metadata_review_context, answer_review_context=answer_review_context,
history_check=history_check, working_continuation=working_continuation)
@@ -694,6 +695,8 @@ def open_session(
objective=objective,
execution_mode=selected_channel.startswith("task."),
project_coordination=conversation_scope(selected_scope)["kind"] == "owner_goal",
+ check_preparation=managed_agent_id is not None,
+ managed_read_default=managed_agent_id is not None,
manager_runtime=manager_runtime,
project_context=project_context,
executor_model=alloc.manager_executor_model(manager_executor_allocation),
@@ -1041,6 +1044,7 @@ def check_route_configuration():
execution_mode=str(session.get("channel_id") or "").startswith("task."),
project_coordination=conversation_scope(session)["kind"] == "owner_goal",
loopx_tools=session.get("loopx_tools") is True,
+ managed_read_default=session.get("managed_agent_id") is not None,
executor_model=(alloc.manager_executor_model(model_allocation)
if model_allocation is not None else alloc.restored_executor_model(session)),
manager_runtime=manager_runtime,
@@ -1190,6 +1194,7 @@ def submit_turn(
loopx_execution: bool = False,
loopx_request: dict[str, object] | None = None,
_goal_commit: ManagedSessionGoalCommit | None = None,
+ display_message: str | None = None,
) -> tuple[dict[str, Any], bool]:
commit = _goal_commit or nullcontext
session = self.store.load_session(session_id)
@@ -1210,16 +1215,9 @@ def submit_turn(
if parse_native_goal_command(message) is not None:
validate_goal_chat(session, attachments)
if session.get("session_mode") == CHAT_SESSION_MODE_ATTACHED:
- if attachments:
- raise ValueError("attached host session queue does not yet accept attachments")
return enqueue_attached_agent_turn(
- store=self.store,
- registry_path=self.registry_path,
- session_id=session_id,
- client_turn_id=client_turn_id,
- message=message,
- origin="web",
- )
+ store=self.store, registry_path=self.registry_path, session_id=session_id,
+ client_turn_id=client_turn_id, message=message, origin="web", attachments=attachments)
with self._session_adapter_lock(session_id):
session = self.store.load_session(session_id)
if session is None or session.get("status") == "closed":
@@ -1257,7 +1255,7 @@ def submit_turn(
"wake": "成员结果已验收,继续推进 LoopX 模式。",
}.get(str((loopx_request or {}).get("operation")), "恢复 LoopX 模式。")
if loopx_execution
- else None
+ else display_message
),
loopx_execution=loopx_execution,
loopx_request=loopx_request,
diff --git a/loopx/chat_server.py b/loopx/chat_server.py
index 18151c789d..e20a966ece 100644
--- a/loopx/chat_server.py
+++ b/loopx/chat_server.py
@@ -953,31 +953,6 @@ def _session_snapshot(self, session_id: str) -> None:
except OSError:
self._send_error("Chat history is temporarily unavailable", status=503)
- def _managed_native_turn(self, session_id: str, *, execute: bool = False) -> None:
- from .capabilities.native_chat.steward_managed_mode import ManagedSessionTurn
- service = ManagedSessionTurn(self.server.runtime_controller)
- try:
- if execute:
- body = self._read_json()
- if set(body) - {"agent_id", "operation_id", "todo_id"}:
- raise ValueError("unsupported managed Turn arguments")
- turn, created = service.submit(session_id, **body)
- return self._send_json({"ok": True, "session_id": session_id, "turn": turn, "created": created}, status=202)
- query = parse_qs(urlparse(self.path).query, keep_blank_values=True)
- sources = query.get("calendar_task_sources", ["false"])
- if sources not in (["true"], ["false"]):
- raise ValueError("calendar_task_sources must be one true or false value")
- include_sources = sources == ["true"]
- if include_sources and (set(query) - {"calendar_task_sources", "agent_id", "operation_id"}
- or any(len(values) != 1 for values in query.values())):
- raise ValueError("select one original managed Session and Agent for Task sources")
- self._send_json(service.inspect(session_id, agent_id=query.get("agent_id", [None])[0],
- operation_id=query.get("operation_id", [None])[0], include_calendar_task_sources=include_sources))
- except KeyError:
- self._send_error("chat session was not found", status=404)
- except (TypeError, ValueError, RuntimeError) as exc:
- self._send_error(str(exc), status=409, error_code="managed_turn_unavailable")
-
def _list_sessions(self) -> None:
query = parse_qs(urlparse(self.path).query, keep_blank_values=True)
if "managed_agent_id" in query:
diff --git a/loopx/control_plane/collaboration/steward_managed_mode.ts b/loopx/control_plane/collaboration/steward_managed_mode.ts
index 947ea1c2a3..44949dcfc8 100644
--- a/loopx/control_plane/collaboration/steward_managed_mode.ts
+++ b/loopx/control_plane/collaboration/steward_managed_mode.ts
@@ -1,18 +1,19 @@
-/** Source-bound preparation of one native execution identity for a steward.
+/** Source-bound managed Session identity and native host policy.
*
- * This owner prepares/binds identity only. Goal bootstrap, Agent registration,
- * scheduling and model execution retain their existing owners. In particular,
- * a prepared identity never advertises a running monitor or an enabled host.
+ * Identity preparation grants no execution. Host policy maps only the original
+ * already-admitted Task and existing approval. Goal bootstrap, registration,
+ * scheduling and execution retain their owners; a prepared identity never
+ * advertises a running monitor or enabled host.
*/
import { createHash } from "node:crypto";
import type { JsonObject } from "../runtime_decode.ts";
-import { requireJsonObject, requireNonEmptyString } from "../runtime_decode.ts";
+import { jsonObject, requireJsonObject, requireNonEmptyString } from "../runtime_decode.ts";
import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts";
import { ENVELOPED_SHA256_PATTERN } from "../content_digest.ts";
import {boundConversationExecutorMatches, goalAgentConversationIdentity, resolveConversationScope} from "./conversation_scope.ts";
import {readTurnSelectionRejection} from "../turn_driver/selection_rejection.ts";
import {EffectiveAction} from "../quota/effective_action.generated.ts";
-import {turnPlanWorkSource} from "../quota/turn_envelope.ts";
+import {projectTurnBoundary, turnPlanWorkSource} from "../quota/turn_envelope.ts";
/** A stopped observation may get one new Chat carrier, never a new native
* observation identity. The host independently reads the old worker lock,
@@ -732,3 +733,30 @@ export function bindStewardManagedActor(params: JsonObject): JsonObject {
goal_id: current.goalId, goal_instance_id: goal.goal_instance_id, agent_id: AGENT_ID,
session_id: current.sessionId, source_ref: current.source, creation_operation_id: current.creation});
}
+
+/** Adapt a current, already admitted native Task to the host's existing
+ * sandbox vocabulary. A Task selection or check confirmation grants no writes.
+ * This bounded adapter supports an existing whole-workspace write approval;
+ * narrower approvals remain read-only until the host can enforce them.
+ */
+export function canonicalNativeTaskSandboxPolicy(params: JsonObject): JsonObject {
+ const actor = requireJsonObject(params.actor, "original native Task actor");
+ const authority = requireJsonObject(params.authority, "admitted Task authority");
+ const validation = requireJsonObject(params.validation, "current Task validation plan");
+ const identity = requireJsonObject(authority._work_identity, "checked original work identity");
+ const preparation = requireJsonObject(authority.execution_preparation, "original Task execution preparation");
+ if (!(params.host === "codex-app-server" && actor.schema_version === "loopx_managed_session_actor_v0"
+ && typeof actor.workspace_path === "string" && actor.workspace_path.length > 0
+ && identity.goal_id === actor.goal_id && identity.agent_id === actor.agent_id
+ && identity.todo_id === validation.todo_id && preparation.todo_id === validation.todo_id
+ && preparation.agent_id === actor.agent_id && preparation.state === "ready"
+ && preparation.delivery_allowed === true && authority.should_run === true
+ && authority.normal_delivery_allowed === true && validation.state === "ready")) {
+ throw new EffectRuntimeRequestError("native host policy requires the original admitted Task, validation and execution lease");
+ }
+ const approval = jsonObject(projectTurnBoundary(authority).checkpointed_boundary_authority);
+ const writable = approval?.schema_version === "checkpointed_boundary_authority_v0"
+ && Array.isArray(approval.active_write_scope) && approval.active_write_scope.includes("**");
+ return writable ? {type: "workspaceWrite", writableRoots: [actor.workspace_path], networkAccess: false,
+ excludeTmpdirEnvVar: true, excludeSlashTmp: true} : {type: "readOnly", networkAccess: false};
+}
diff --git a/loopx/control_plane/effect_runtime_handlers.ts b/loopx/control_plane/effect_runtime_handlers.ts
index c4f9f80b2e..781167fd96 100644
--- a/loopx/control_plane/effect_runtime_handlers.ts
+++ b/loopx/control_plane/effect_runtime_handlers.ts
@@ -363,6 +363,7 @@ export function createEffectRuntimeHandlers(
["goal.first_party_host_runtime.decide", lazyHandler(() => import("./goals/first_party_host_runtime.ts"), ({decideFirstPartyHostRuntime}) => decideFirstPartyHostRuntime)],
["goal.chat_session.lifecycle.decide", lazyHandler(() => import("./goals/chat_session_lifecycle.ts"), ({decideChatSessionLifecycle}) => decideChatSessionLifecycle)],
["goal.task.validation_plan", lazyHandler(() => import("./goals/task_validation_plan.ts"), ({canonicalTaskValidationPlan}) => canonicalTaskValidationPlan)],
+ ["goal.task.creation_selection", lazyHandler(() => import("./goals/task_validation_plan.ts"), ({originalCreationTaskSelection}) => originalCreationTaskSelection)],
["goal.acceptance.oracle.plan", lazyHandler(() => import("./goals/acceptance_oracle.ts"), ({planAcceptanceOracle}) => planAcceptanceOracle)],
["goal.acceptance.oracle.observe", lazyHandler(() => import("./goals/acceptance_oracle.ts"), ({observeAcceptanceOracles}) => observeAcceptanceOracles)],
["goal.acceptance.refine", lazyHandler(() => import("./goals/acceptance_authority.ts"), ({refineLocalGoalAcceptanceOutcome}) => refineLocalGoalAcceptanceOutcome)],
@@ -618,6 +619,7 @@ export function createEffectRuntimeHandlers(
["collaboration.steward.managed_mode.executor", lazyHandler(() => import("./collaboration/steward_managed_mode.ts"), ({observeStewardNativeExecutor}) => observeStewardNativeExecutor)],
["collaboration.steward.managed_turn.admit", lazyHandler(() => import("./collaboration/steward_managed_mode.ts"), ({admitStewardManagedTurn}) => admitStewardManagedTurn)],
["collaboration.session.managed_turn.admit", lazyHandler(() => import("./collaboration/steward_managed_mode.ts"), ({admitManagedSessionTurn}) => admitManagedSessionTurn)],
+ ["collaboration.session.managed_turn.sandbox_policy", lazyHandler(() => import("./collaboration/steward_managed_mode.ts"), ({canonicalNativeTaskSandboxPolicy}) => canonicalNativeTaskSandboxPolicy)],
["collaboration.session.managed_identity", lazyHandler(() => import("./collaboration/steward_managed_mode.ts"), ({admitManagedSessionIdentity}) => admitManagedSessionIdentity)],
["collaboration.steward.monitor.plan", lazyHandler(() => import("./collaboration/steward_managed_mode.ts"), ({planStewardMonitor}) => planStewardMonitor)],
["collaboration.steward.report.plan", lazyHandler(() => import("./collaboration/steward_reports.ts"), ({planStewardReport}) => planStewardReport)],
diff --git a/loopx/control_plane/goals/task_validation_plan.ts b/loopx/control_plane/goals/task_validation_plan.ts
index 895e573f68..63d89a9596 100644
--- a/loopx/control_plane/goals/task_validation_plan.ts
+++ b/loopx/control_plane/goals/task_validation_plan.ts
@@ -3,7 +3,7 @@
* pure plan; caller/model input is not authority and the plan grants no execution
* or write permission. */
import type {JsonObject} from "../effect_program.ts";
-import {requireJsonObject} from "../runtime_decode.ts";
+import {jsonObject, requireJsonObject} from "../runtime_decode.ts";
import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts";
import {canonicalAuthoritySha256} from "../coordination/authority_store_codec.ts";
import {acceptanceValidationEffects, type AcceptanceCompletionRequirements} from "./acceptance_contract.ts";
@@ -14,6 +14,25 @@ function requireThat(ok: unknown, message: string): asserts ok {
if (!ok) throw new EffectRuntimeRequestError(message);
}
+/** A display selection from retained creation work, never a newest/first Todo
+ * heuristic or an execution grant. The host must qualify the selected Todo's
+ * current validation through canonicalTaskValidationPlan before advertising it.
+ */
+export function originalCreationTaskSelection(params: JsonObject): JsonObject {
+ const basis = requireJsonObject(params.basis, "current Goal acceptance basis");
+ requireThat(basis.status === "loaded" && typeof basis.provider_revision === "string"
+ && basis.provider_revision.length > 0, "current Goal acceptance basis required");
+ const contract = requireJsonObject(basis.goal_acceptance_contract, "current Goal acceptance projection");
+ const outcomes = jsonObject(contract.outcome_requirements);
+ if (!outcomes || !Array.isArray(outcomes.outcomes)) return {todo_id: null, reason: "original_task_unavailable"};
+ const candidates: unknown[] = outcomes.outcomes;
+ const original = candidates.map(jsonObject).filter((row): row is JsonObject => row?.id === "goal-creation");
+ if (original.length !== 1 || !Array.isArray(original[0].todo_ids)
+ || original[0].todo_ids.length !== 1 || typeof original[0].todo_ids[0] !== "string"
+ || !original[0].todo_ids[0]) return {todo_id: null, reason: "original_task_unavailable"};
+ return {todo_id: original[0].todo_ids[0], reason: null};
+}
+
/** An explicit null requirement means owner-resolved out-of-scope/disabled
* checks. Missing, unbound or stale owner acceptance must never fall back to a
* Todo-only declaration. Required Todo checks remain cumulative with Goal checks. */
diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts
index b4ed32dd2d..71b56c8eab 100644
--- a/loopx/control_plane/quota/turn_envelope.ts
+++ b/loopx/control_plane/quota/turn_envelope.ts
@@ -1136,7 +1136,7 @@ function requiredReads(interaction: JsonObject, payload: JsonObject): JsonObject
return result;
}
-function boundary(payload: JsonObject): JsonObject {
+export function projectTurnBoundary(payload: JsonObject): JsonObject {
const source = object(payload.goal_boundary);
const result: JsonObject = {
rule: scalarString(source.rule, "goal_boundary.rule", "stay_in_scope_or_stop"),
@@ -1482,7 +1482,7 @@ function actionProjection(payload: JsonObject, deferSettlement = true, precision
user,
required_reads: requiredReads(interaction, payload),
replan_action_packet: replanPacket,
- boundary: boundary(payload),
+ boundary: projectTurnBoundary(payload),
execution_policy: executionPolicy(payload),
writeback: reads && deferSettlement ? deferredReplanWriteback(writeback) : writeback,
scheduler: schedulerValue,
diff --git a/tests/control_plane/test_goal_create_session.py b/tests/control_plane/test_goal_create_session.py
index c2fd0573cc..a776e38722 100644
--- a/tests/control_plane/test_goal_create_session.py
+++ b/tests/control_plane/test_goal_create_session.py
@@ -51,6 +51,26 @@ def create(host):
return proposal, ids, first
+def test_creation_display_preserves_user_intent_and_the_internal_execution_request(host):
+ proposal, ids, first = create(host)
+ store = host[2].store
+ assert store.messages(ids["session_id"])[0]["text"] == proposal["normalized_parameters"]["objective"]
+ assert first["message"].startswith("开始推进 Goal")
+
+
+def test_creation_display_recovery_retains_the_original_historical_message(host):
+ from loopx.chat.session_open import goal_creation_display_message
+ create(host)
+ store, project = host[2].store, host[4]
+ session, _ = host[2].open_session(goal_id="report", agent_id="codex", work_dir=project,
+ objective="Historical objective", mode="new", channel_id="goal.report", agent_goal_id="report")
+ turn, _ = store.create_turn(session["session_id"], client_turn_id="historical-first",
+ message="Historical internal execution request", display_message="The original confirmed request")
+ assert goal_creation_display_message(store, session_id=session["session_id"],
+ client_turn_id="historical-first", objective="Later objective") == "The original confirmed request"
+ assert store.load_turn(session["session_id"], turn["turn_id"])["message"] == "Historical internal execution request"
+
+
@pytest.mark.parametrize("provider", ["file", "sqlite"])
def test_first_goal_retains_ordinary_messages_in_the_registered_session(environment, host, provider):
configure, *_ = environment
diff --git a/tests/control_plane/test_goal_session_check_preparation.py b/tests/control_plane/test_goal_session_check_preparation.py
new file mode 100644
index 0000000000..408acaac81
--- /dev/null
+++ b/tests/control_plane/test_goal_session_check_preparation.py
@@ -0,0 +1,908 @@
+"""Original managed Chat preparation over real File/SQLite acceptance owners.
+
+The native model transport is synthetic. Preparation pins preexisting sources
+and persists a proposal without configuring acceptance or running a checker.
+"""
+
+from copy import deepcopy
+from contextlib import contextmanager, nullcontext
+import hashlib
+import json
+import queue
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+from loopx.chat.coordination import prepare_turn_context, check_preparation_tool
+from loopx.chat_agent import CodexChatAgentSession
+from loopx.chat_runtime import ChatRuntimeController, CodexAppServerAdapter
+from loopx.chat_store import ChatSessionStore
+from loopx.chat_action_store import ChatActionStore
+from loopx.control_plane.collaboration import conversation_scope
+from loopx.control_plane.goals.acceptance import refine_goal_outcome
+from test_goal_acceptance_cli import acceptance_goal as acceptance_goal
+
+
+@pytest.fixture
+def original_check(acceptance_goal, monkeypatch):
+ project, _, cli, _ = acceptance_goal
+ root, registry = project.parent / "runtime", project.parent / "registry.json"
+ refined = refine_goal_outcome(
+ registry_path=registry,
+ runtime_root=str(root),
+ goal_id="goal-acceptance",
+ agent_id="agent-a",
+ operation_id="original-owner-outcome",
+ expected_provider_revision=cli("inspect")[1]["provider_revision"],
+ execute=True,
+ refinement={
+ "outcome_id": "goal-creation",
+ "owner_agent_id": "agent-a",
+ "objective": "Produce a usable export",
+ "todo_ids": ["todo_export"],
+ "requirements": [
+ {
+ "id": "completion",
+ "description": "The exported artifact has the expected content",
+ }
+ ],
+ "source": {
+ "ref": "goal-create:fixture:completion",
+ "summary": "Owner-approved completion criteria",
+ },
+ },
+ )
+ assert refined["status"] == "applied", refined
+ checker = project / "check.py"
+ checker.write_text(
+ "from pathlib import Path\nassert Path('artifact.txt').read_text() == 'accepted'\n"
+ )
+ store = ChatSessionStore(root)
+ runtime = ChatRuntimeController(
+ store=store, codex_bin="unused", registry_path=registry
+ )
+ session = store.create_session(
+ goal_id="goal-acceptance",
+ managed_agent_id="agent-a",
+ managed_workspace_path=str(project.resolve()),
+ channel_id="agent.agent-a",
+ agent_id="codex",
+ executor_endpoint_id="codex",
+ adapter_kind="codex_app_server",
+ upstream_thread_id="original-thread",
+ upstream_mode="chat",
+ )
+ turn, _ = store.create_turn(
+ session["session_id"],
+ client_turn_id="prepare-original-check",
+ message="Prepare the independent delivery check for review.",
+ )
+ store.update_turn(session["session_id"], turn["turn_id"], status="running")
+ store.update_session(session["session_id"], active_turn_id=turn["turn_id"])
+ native = CodexChatAgentSession(
+ process=SimpleNamespace(poll=lambda: None),
+ messages=queue.Queue(),
+ thread_id="original-thread",
+ work_dir=project,
+ )
+ monkeypatch.setattr(native, "close", lambda: None)
+ adapter = CodexAppServerAdapter(native)
+ runtime.adapters[session["session_id"]] = adapter
+ session = store.load_session(session["session_id"])
+ prepared_adapter, context = prepare_turn_context(
+ runtime,
+ adapter,
+ session,
+ turn["turn_id"],
+ lambda *_: None,
+ scope=conversation_scope(session, origin="web"),
+ )
+ assert prepared_adapter is adapter and context["scope"] == "owner_goal"
+ document = {
+ "outcome_id": "goal-creation",
+ "criteria": [
+ {
+ "id": "completion",
+ "validation_argv": ["python3", "check.py"],
+ "validation_timeout_seconds": 5,
+ "oracle": {
+ "kind": "owner_pinned_oracle",
+ "source_id": "export-checker",
+ "input_refs": [],
+ "output_refs": ["artifact.txt"],
+ },
+ }
+ ],
+ }
+
+ def call(**updates):
+ return native.read_tool_handler(
+ "loopx_collaboration",
+ {
+ "action": "prepare_check",
+ "operation_id": "original-check",
+ "document": document,
+ **updates,
+ },
+ )
+
+ try:
+ yield SimpleNamespace(
+ project=project,
+ checker=checker,
+ root=root,
+ registry=registry,
+ store=store,
+ runtime=runtime,
+ session=session,
+ turn=turn,
+ native=native,
+ adapter=adapter,
+ document=document,
+ call=call,
+ cli=cli,
+ )
+ finally:
+ runtime.close()
+
+
+def test_original_read_only_turn_prepares_one_host_pinned_proposal(original_check):
+ fixture = original_check
+ before = fixture.cli("inspect")[1]
+ session_before = fixture.store.load_session(fixture.session["session_id"])
+ source_before = fixture.checker.read_bytes()
+ result = fixture.call()
+ assert result["ok"] and result["prepared"] and result["executed"] is False, (
+ result.get("next_action", result)
+ )
+ proposal = result["proposal"]
+ parameters = proposal["normalized_parameters"]
+ assert parameters["goal_id"] == fixture.session["goal_id"]
+ assert parameters["prepared_by"] == "agent-a"
+ criterion = parameters["document"]["criteria"][0]
+ assert criterion["validation_argv"] == ["python3", "check.py"]
+ assert criterion["validation_files"] == [
+ {"path": "check.py", "sha256": hashlib.sha256(source_before).hexdigest()}
+ ]
+ assert criterion["oracle"]["output_refs"] == ["artifact.txt"]
+ assert not (fixture.project / "artifact.txt").exists(), (
+ "Preparation must allow unfinished delivery"
+ )
+ assert fixture.call()["proposal"] == proposal
+ assert fixture.cli("inspect")[1] == before
+ assert fixture.store.load_session(fixture.session["session_id"]) == session_before
+ assert fixture.checker.read_bytes() == source_before
+ assert len(ChatActionStore(fixture.root / "chat/actions").list()) == 1
+
+
+@pytest.mark.parametrize(
+ "updates",
+ [
+ {"goal_id": "another-goal"},
+ {"agent_id": "other-agent"},
+ {"prepared_by": "other-agent"},
+ {"workspace": "another-workspace"},
+ {"runtime_root": "another-runtime"},
+ {"source_id": "remote"},
+ {"action": "start"},
+ {"action": "outcomes"},
+ {"operation_id": ""},
+ ],
+)
+def test_caller_cannot_replace_host_identity_or_action(original_check, updates):
+ assert original_check.call(**updates)["error"] == "collaboration_request_rejected"
+ assert ChatActionStore(original_check.root / "chat/actions").list() == []
+
+
+@pytest.mark.parametrize(
+ "change",
+ [
+ "agent",
+ "workspace",
+ "thread",
+ "channel",
+ "closed",
+ "other-turn",
+ "terminal",
+ "external",
+ "native",
+ "legacy",
+ "review",
+ "lifetime",
+ "registration",
+ "registry-workspace",
+ "goal-stopped",
+ ],
+)
+def test_preparation_rechecks_original_session_turn_and_registration(
+ original_check, change
+):
+ fixture = original_check
+ sid, tid = fixture.session["session_id"], fixture.turn["turn_id"]
+ fields = {
+ "agent": {"managed_agent_id": "other-agent"},
+ "workspace": {"managed_workspace_path": "other"},
+ "thread": {"upstream_thread_id": "replacement"},
+ "channel": {"channel_id": "goal.other"},
+ "closed": {"status": "closed"},
+ "other-turn": {"active_turn_id": "another-turn"},
+ "legacy": {"loopx_mode": {"enabled": True}},
+ }
+ if change in fields:
+ if change in {"agent", "workspace", "channel"}:
+ # These fields are immutable through the public API. Corrupt only
+ # this disposable input to qualify defensive source readback.
+ from loopx.chat_store import _atomic_write_json
+
+ path = fixture.store._session_path(sid)
+ _atomic_write_json(
+ path, {**fixture.store.load_session(sid), **fields[change]}
+ )
+ else:
+ fixture.store.update_session(sid, **fields[change])
+ elif change in {"terminal", "external", "native"}:
+ if change == "external":
+ from loopx.chat_store import _atomic_write_json
+
+ _atomic_write_json(
+ fixture.store._turn_path(sid, tid),
+ {**fixture.store.load_turn(sid, tid), "origin": "lark"},
+ )
+ else:
+ fixture.store.update_turn(
+ sid,
+ tid,
+ **(
+ {"status": "completed"}
+ if change == "terminal"
+ else {"loopx_execution": True}
+ ),
+ )
+ elif change == "review":
+ fixture.native.read_only_review = True
+ else:
+ registry = json.loads(fixture.registry.read_text())
+ goal = registry["goals"][0]
+ if change == "lifetime":
+ goal["goal_instance_id"] = "another-lifetime"
+ elif change == "registration":
+ goal["coordination"]["registered_agents"] = []
+ elif change == "registry-workspace":
+ goal["repo"] = str(fixture.project.parent)
+ else:
+ goal["status"] = "paused"
+ fixture.registry.write_text(json.dumps(registry))
+ result = fixture.call()
+ assert result["error"] == "collaboration_request_rejected", result
+ assert ChatActionStore(fixture.root / "chat/actions").list() == []
+
+
+@pytest.mark.parametrize(
+ "change",
+ [
+ "claimed-pin",
+ "inline-python",
+ "python-options",
+ "extra-argv",
+ "other-interpreter",
+ "absolute",
+ "parent",
+ "symlink",
+ "symlink-parent",
+ "missing",
+ "directory",
+ "source-output",
+ "missing-outputs",
+ "output-symlink",
+ ],
+)
+def test_preparation_rejects_unusable_or_unpinned_checker_sources(
+ original_check, change
+):
+ fixture = original_check
+ document = deepcopy(fixture.document)
+ row = document["criteria"][0]
+ if change == "claimed-pin":
+ row["validation_files"] = [{"path": "check.py", "sha256": "0" * 64}]
+ elif change == "inline-python":
+ row["validation_argv"] = ["python3", "-c", "pass"]
+ elif change == "python-options":
+ row["validation_argv"] = ["python3", "-I", "check.py"]
+ elif change == "extra-argv":
+ row["validation_argv"].append("--ignore-failure")
+ elif change == "other-interpreter":
+ row["validation_argv"] = ["arbitrary-command", "check.py"]
+ elif change == "absolute":
+ row["validation_argv"][1] = str(fixture.checker)
+ elif change == "parent":
+ row["validation_argv"][1] = "../project/check.py"
+ elif change in {"symlink", "missing", "directory"}:
+ fixture.checker.unlink()
+ if change == "symlink":
+ fixture.checker.symlink_to(fixture.project.parent / "acceptance.json")
+ elif change == "directory":
+ fixture.checker.mkdir()
+ elif change == "symlink-parent":
+ (fixture.project / "linked").symlink_to(
+ fixture.project, target_is_directory=True
+ )
+ row["validation_argv"][1] = "linked/check.py"
+ elif change == "source-output":
+ row["oracle"]["output_refs"] = ["check.py"]
+ elif change == "missing-outputs":
+ row["oracle"]["output_refs"] = []
+ else:
+ (fixture.project / "artifact.txt").symlink_to(fixture.checker)
+ result = fixture.call(document=document)
+ assert result["error"] == "collaboration_request_rejected", result
+ assert ChatActionStore(fixture.root / "chat/actions").list() == []
+
+
+def test_scope_change_during_source_read_is_refused_before_proposal(
+ original_check, monkeypatch
+):
+ import loopx.chat.coordination as coordination
+
+ observe = coordination._workspace_file
+
+ def replace_scope(*args, **kwargs):
+ result = observe(*args, **kwargs)
+ original_check.store.update_session(
+ original_check.session["session_id"], active_turn_id="later-turn"
+ )
+ return result
+
+ monkeypatch.setattr(coordination, "_workspace_file", replace_scope)
+ assert original_check.call()["error"] == "collaboration_request_rejected"
+ assert ChatActionStore(original_check.root / "chat/actions").list() == []
+
+
+def test_changed_source_retry_preserves_saved_intent_and_original_pin(original_check):
+ fixture = original_check
+ original = fixture.call()["proposal"]
+ saved_pin = original["normalized_parameters"]["document"]["criteria"][0][
+ "validation_files"
+ ]
+ source = fixture.checker.read_bytes()
+ fixture.checker.write_bytes(source + b"# A different source version\n")
+ refused = fixture.call()
+ assert refused["error"] == "collaboration_request_rejected"
+ proposals = ChatActionStore(fixture.root / "chat/actions").list()
+ assert proposals == [original]
+ assert (
+ proposals[0]["normalized_parameters"]["document"]["criteria"][0][
+ "validation_files"
+ ]
+ == saved_pin
+ )
+ fixture.checker.write_bytes(source)
+ assert fixture.call()["proposal"] == original
+
+
+@pytest.mark.parametrize("interpreter", [None, "/usr/bin/another-python"])
+def test_unavailable_host_interpreter_refuses_preparation(
+ original_check, monkeypatch, interpreter
+):
+ monkeypatch.setattr(
+ "loopx.chat.coordination.shutil.which", lambda _name: interpreter
+ )
+ result = original_check.call()
+ assert result["error"] == "collaboration_request_rejected"
+ assert "host interpreter" in result["next_action"]
+ assert ChatActionStore(original_check.root / "chat/actions").list() == []
+
+
+@pytest.mark.parametrize("direct", [False, True])
+def test_source_changed_during_read_is_refused_before_proposal(
+ original_check, monkeypatch, direct
+):
+ import loopx.chat.coordination as coordination
+
+ observe = coordination._workspace_file
+ document = deepcopy(original_check.document)
+ selected_source = original_check.checker
+ if direct:
+ selected_source = original_check.project / "checks/verify"
+ selected_source.parent.mkdir()
+ selected_source.write_bytes(original_check.checker.read_bytes())
+ selected_source.chmod(0o755)
+ document["criteria"][0]["validation_argv"] = ["checks/verify"]
+ changed = False
+
+ def change_after_read(*args, **kwargs):
+ nonlocal changed
+ result = observe(*args, **kwargs)
+ if kwargs.get("required") and not changed:
+ changed = True
+ selected_source.write_text("raise SystemExit(0)\n")
+ return result
+
+ monkeypatch.setattr(coordination, "_workspace_file", change_after_read)
+ result = original_check.call(document=document)
+ assert result["error"] == "collaboration_request_rejected"
+ assert "source changed during preparation" in result["next_action"]
+ assert ChatActionStore(original_check.root / "chat/actions").list() == []
+
+
+def test_first_of_two_checker_sources_is_reobserved_before_proposal(
+ original_check, monkeypatch
+):
+ import loopx.chat.coordination as coordination
+
+ fixture = original_check
+ refine_goal_outcome(
+ registry_path=fixture.registry,
+ runtime_root=str(fixture.root),
+ goal_id=fixture.session["goal_id"],
+ agent_id="agent-a",
+ operation_id="additional-owner-requirement",
+ expected_provider_revision=fixture.cli("inspect")[1]["provider_revision"],
+ execute=True,
+ refinement={
+ "outcome_id": "goal-creation",
+ "requirements": [
+ {
+ "id": "additional",
+ "description": "The additional independent check succeeds",
+ }
+ ],
+ "source": {
+ "ref": "message:additional-owner-direction",
+ "summary": "The owner added another requirement",
+ },
+ },
+ )
+ (fixture.project / "additional.py").write_text(
+ "from pathlib import Path\nassert Path('artifact.txt').read_text() == 'accepted'\n"
+ )
+ document = deepcopy(fixture.document)
+ additional = deepcopy(document["criteria"][0])
+ additional.update(id="additional", validation_argv=["python3", "additional.py"])
+ additional["oracle"]["source_id"] = "additional-checker"
+ document["criteria"].append(additional)
+ observe = coordination._workspace_file
+
+ def replace_first_after_second(workspace, ref, **kwargs):
+ digest = observe(workspace, ref, **kwargs)
+ if ref == "additional.py" and kwargs["required"]:
+ fixture.checker.write_text("raise SystemExit(0)\n")
+ return digest
+
+ monkeypatch.setattr(coordination, "_workspace_file", replace_first_after_second)
+ result = fixture.call(document=document)
+ assert result["error"] == "collaboration_request_rejected"
+ assert "source changed during preparation" in result["next_action"]
+ assert ChatActionStore(fixture.root / "chat/actions").list() == []
+
+
+def test_unavailable_safe_file_observation_is_explicitly_refused(
+ original_check, monkeypatch
+):
+ monkeypatch.setattr("loopx.chat.coordination.os.supports_dir_fd", set())
+ result = original_check.call()
+ assert result["error"] == "collaboration_request_rejected"
+ assert "cannot safely inspect workspace checker sources" in result["next_action"]
+ assert ChatActionStore(original_check.root / "chat/actions").list() == []
+
+
+def test_direct_existing_checker_and_matching_claimed_pin_are_supported(original_check):
+ fixture = original_check
+ checks = fixture.project / "checks"
+ checks.mkdir()
+ executable = checks / "verify"
+ executable.write_text(
+ "#!/usr/bin/env python3\nfrom pathlib import Path\nassert Path('artifact.txt').read_text() == 'accepted'\n"
+ )
+ executable.chmod(0o755)
+ document = deepcopy(fixture.document)
+ row = document["criteria"][0]
+ row["validation_argv"] = ["checks/verify"]
+ row["validation_files"] = [
+ {
+ "path": "checks/verify",
+ "sha256": hashlib.sha256(executable.read_bytes()).hexdigest(),
+ }
+ ]
+ result = fixture.call(document=document)
+ assert result["prepared"] and result["executed"] is False, result
+ assert result["proposal"]["normalized_parameters"]["document"] == document
+
+
+@pytest.mark.parametrize("token", ["python", sys.executable])
+def test_supported_python_aliases_resolve_to_public_safe_host_token(
+ original_check, token
+):
+ document = deepcopy(original_check.document)
+ document["criteria"][0]["validation_argv"][0] = token
+ result = original_check.call(document=document)
+ assert result["prepared"] and result["executed"] is False, result
+ row = result["proposal"]["normalized_parameters"]["document"]["criteria"][0]
+ assert row["validation_argv"] == ["python3", "check.py"]
+
+
+def test_outer_dispatcher_preserves_read_owner_and_rejects_actor_override_in_document(
+ original_check,
+):
+ fixture = original_check
+ handler = fixture.native.read_tool_handler
+ arguments = {"view": "goals", "source_id": "remote"}
+ assert handler("loopx_context_read", arguments) == handler.read(
+ "loopx_context_read", arguments
+ )
+ document = {**fixture.document, "goal_id": "another-goal"}
+ assert fixture.call(document=document)["error"] == "collaboration_request_rejected"
+ assert ChatActionStore(fixture.root / "chat/actions").list() == []
+
+
+@pytest.mark.parametrize(
+ "managed,resume,legacy,execution,review,manager,expected",
+ [
+ (
+ True,
+ None,
+ False,
+ False,
+ False,
+ False,
+ ["loopx_context_read", "loopx_collaboration"],
+ ),
+ (False, None, False, False, False, False, ["loopx_context_read"]),
+ (True, "existing-thread", False, False, False, False, ["loopx_context_read"]),
+ (
+ False,
+ None,
+ True,
+ False,
+ False,
+ False,
+ ["loopx_context_read", "loopx_collaboration"],
+ ),
+ (True, None, False, True, False, False, []),
+ (True, None, False, False, True, False, []),
+ (True, None, False, False, False, True, ["loopx_manager_read"]),
+ ],
+)
+def test_prepare_projection_is_only_for_new_default_managed_threads(
+ tmp_path, monkeypatch, managed, resume, legacy, execution, review, manager, expected
+):
+ from loopx.capabilities.native_chat.codex_adapter import start_runtime_adapter
+
+ captured = []
+ monkeypatch.setattr(
+ CodexAppServerAdapter, "start", lambda **kwargs: captured.append(kwargs)
+ )
+ controller = SimpleNamespace(
+ codex_bin="unused",
+ coordination_runtime_root=tmp_path,
+ codex_home=None,
+ startup_timeout_sec=2,
+ idle_timeout_sec=2,
+ hard_timeout_sec=2,
+ )
+ start_runtime_adapter(
+ controller,
+ work_dir=tmp_path,
+ goal_id="loopx-manager" if manager else "goal-fixture",
+ native_context={"objective": "Observe", "runtime_profile": "restricted"},
+ manager_profile=None,
+ model_config={},
+ history=None,
+ resume_thread_id=resume,
+ execution_mode=execution,
+ project_context=None,
+ project_coordination=not manager,
+ loopx_tools=legacy,
+ check_preparation=managed,
+ codex_home_override=None,
+ read_only_review=review,
+ metadata_review_context=None,
+ answer_review_context=None,
+ )
+ tools = captured[0]["dynamic_tools"] or []
+ assert [tool["name"] for tool in tools] == expected
+ if (
+ managed
+ and not resume
+ and not legacy
+ and not execution
+ and not review
+ and not manager
+ ):
+ assert tools[-1]["inputSchema"]["properties"]["action"]["enum"] == [
+ "prepare_check"
+ ]
+ assert set(tools[-1]["inputSchema"]["properties"]) == {
+ "action",
+ "operation_id",
+ "document",
+ }
+ if legacy:
+ assert "start" in tools[-1]["inputSchema"]["properties"]["action"]["enum"]
+
+
+def test_prepare_projection_does_not_mutate_existing_collaboration_tool():
+ from loopx.chat_loopx_mode import TOOL
+
+ before = deepcopy(TOOL)
+ check_preparation_tool()
+ assert TOOL == before
+
+
+def _capture_native_dispatch(fixture, monkeypatch):
+ """Run the real send/request event loop with a synthetic guarded wire."""
+ captured = []
+
+ def wire(payload, *, write_guard=None, deadline=None):
+ with write_guard() if write_guard is not None else nullcontext():
+ captured.append(deepcopy(payload))
+ fixture.native.messages.put(
+ {"id": payload["id"], "result": {"turn": {"id": "transport-turn"}}}
+ )
+ fixture.native.messages.put(
+ {"method": "item/agentMessage/delta", "params": {"delta": "Ready."}}
+ )
+ fixture.native.messages.put(
+ {
+ "method": "turn/completed",
+ "params": {"turn": {"status": "completed"}},
+ }
+ )
+
+ monkeypatch.setattr(fixture.native, "_write", wire)
+ return captured
+
+
+def _native_task_policy(fixture):
+ return {
+ "type": "workspaceWrite",
+ "writableRoots": [str(fixture.project.resolve())],
+ "networkAccess": False,
+ "excludeTmpdirEnvVar": True,
+ "excludeSlashTmp": True,
+ }
+
+
+@pytest.mark.parametrize("writable", [False, True])
+def test_fenced_native_task_dispatch_then_ordinary_read_reset_preserves_session_defaults(
+ original_check, monkeypatch, writable
+):
+ fixture = original_check
+ captured = _capture_native_dispatch(fixture, monkeypatch)
+ guarded = []
+
+ @contextmanager
+ def admitted_host_write():
+ # This synthetic guard checks original transport identity only. The
+ # actual Core Task/lease/authority path is qualified by the HTTP suite.
+ fixture.native.read_tool_handler._current()
+ guarded.append("entered")
+ yield
+
+ fixture.native._launch_guard = admitted_host_write
+ before = (fixture.native.execution_mode, fixture.native.sandbox)
+ policy = (
+ _native_task_policy(fixture)
+ if writable
+ else {"type": "readOnly", "networkAccess": False}
+ )
+ fixture.adapter.start_native_task_turn(
+ "Perform the confirmed Task.", lambda *_: None, policy
+ )
+ native = captured[-1]["params"]
+ assert native["sandboxPolicy"] == policy
+ assert "permissions" not in native
+ assert (
+ "You are the execution agent for a confirmed LoopX Task"
+ in native["input"][0]["text"]
+ )
+ assert "Do not edit files, mutate LoopX state" not in native["input"][0]["text"]
+ assert guarded == ["entered"]
+ fixture.adapter.start_turn("Prepare the check for review.", lambda *_: None)
+ ordinary = captured[-1]["params"]
+ assert ordinary["sandboxPolicy"] == {"type": "readOnly", "networkAccess": False}
+ assert "Do not edit files, mutate LoopX state" in ordinary["input"][0]["text"]
+ fixture.adapter.start_turn_with_attachments(
+ "Read the original attachment.", lambda *_: None, []
+ )
+ assert captured[-1]["params"]["sandboxPolicy"] == {
+ "type": "readOnly",
+ "networkAccess": False,
+ }
+ assert (fixture.native.execution_mode, fixture.native.sandbox) == before
+ fixture.native.send("Read from the original direct source.")
+ assert captured[-1]["params"]["sandboxPolicy"] == {
+ "type": "readOnly",
+ "networkAccess": False,
+ }
+ assert all(frame["params"]["threadId"] == "original-thread" for frame in captured)
+ assert fixture.native._launch_guard is admitted_host_write
+
+
+@pytest.mark.parametrize(
+ "invalid", ["no-guard", "wrong-workspace", "network", "named-profile", "review"]
+)
+def test_native_task_transport_refuses_unbound_policy_or_missing_host_fence(
+ original_check, monkeypatch, invalid
+):
+ fixture = original_check
+ captured = _capture_native_dispatch(fixture, monkeypatch)
+ policy = _native_task_policy(fixture)
+
+ @contextmanager
+ def admitted_host_write():
+ yield
+
+ fixture.native._launch_guard = admitted_host_write
+ if invalid == "no-guard":
+ fixture.native._launch_guard = None
+ elif invalid == "wrong-workspace":
+ policy["writableRoots"] = [str(fixture.project.parent.resolve())]
+ elif invalid == "network":
+ policy["networkAccess"] = True
+ elif invalid == "named-profile":
+ fixture.native.permissions_profile = "existing-owner-profile"
+ else:
+ fixture.native.read_only_review = True
+ with pytest.raises(ValueError, match="current host launch guard"):
+ fixture.adapter.start_native_task_turn(
+ "Perform the Task.", lambda *_: None, policy
+ )
+ assert captured == []
+ assert (
+ fixture.native.execution_mode is False and fixture.native.sandbox == "read-only"
+ )
+ assert fixture.native._native_task_policy_used is False
+
+
+def test_revoked_host_launch_guard_refuses_native_frame_and_ordinary_turn_cannot_widen_policy(
+ original_check, monkeypatch
+):
+ fixture = original_check
+ captured = _capture_native_dispatch(fixture, monkeypatch)
+
+ @contextmanager
+ def revoked_host_write():
+ raise ValueError("the original Task authority was revoked")
+ yield
+
+ fixture.native._launch_guard = revoked_host_write
+ with pytest.raises(ValueError, match="authority was revoked"):
+ fixture.adapter.start_native_task_turn(
+ "Perform the Task.", lambda *_: None, _native_task_policy(fixture)
+ )
+ assert captured == []
+ with pytest.raises(ValueError, match="ordinary Chat Turn"):
+ fixture.native.send(
+ "Ordinary request.", sandbox_policy=_native_task_policy(fixture)
+ )
+ assert captured == []
+
+
+def test_uncertain_native_publication_retains_ordinary_policy_reset_requirement(
+ original_check, monkeypatch
+):
+ fixture = original_check
+ captured = _capture_native_dispatch(fixture, monkeypatch)
+ request = fixture.native._request
+
+ @contextmanager
+ def admitted_host_write():
+ yield
+
+ fixture.native._launch_guard = admitted_host_write
+
+ def uncertain_publication(*args, **kwargs):
+ raise OSError("native publication is unconfirmed")
+
+ monkeypatch.setattr(fixture.native, "_request", uncertain_publication)
+ with pytest.raises(OSError, match="publication is unconfirmed"):
+ fixture.adapter.start_native_task_turn(
+ "Perform the Task.", lambda *_: None, _native_task_policy(fixture)
+ )
+ assert fixture.native._native_task_policy_used is True and captured == []
+ monkeypatch.setattr(fixture.native, "_request", request)
+ fixture.native.send("Read the original evidence after recovery.")
+ assert captured[-1]["params"]["sandboxPolicy"] == {
+ "type": "readOnly",
+ "networkAccess": False,
+ }
+ assert captured[-1]["params"]["threadId"] == "original-thread"
+ assert (
+ fixture.native.execution_mode is False and fixture.native.sandbox == "read-only"
+ )
+
+
+@pytest.mark.parametrize("cold", [False, True], ids=["new", "cold-resume"])
+def test_verified_managed_session_construction_binds_direct_read_default_without_native_history(
+ original_check, monkeypatch, cold
+):
+ from loopx.chat.coordination import PROJECT_CONTEXT_VERSION
+
+ fixture = original_check
+ starts = []
+
+ def start(**kwargs):
+ starts.append(kwargs)
+ native = CodexChatAgentSession(
+ process=SimpleNamespace(poll=lambda: None),
+ messages=queue.Queue(),
+ thread_id=kwargs.get("resume_thread_id") or "new-managed-thread",
+ work_dir=kwargs["work_dir"],
+ )
+ monkeypatch.setattr(native, "close", lambda: None)
+ return CodexAppServerAdapter(native)
+
+ monkeypatch.setattr(CodexAppServerAdapter, "start", start)
+ monkeypatch.setattr(
+ fixture.runtime,
+ "capabilities",
+ lambda: [
+ {"agent_id": "codex", "available": True, "adapter_kind": "codex_app_server"}
+ ],
+ )
+ if cold:
+ fixture.store.update_turn(
+ fixture.session["session_id"], fixture.turn["turn_id"], status="completed"
+ )
+ fixture.store.update_session(
+ fixture.session["session_id"],
+ active_turn_id=None,
+ coordination_context_version=PROJECT_CONTEXT_VERSION,
+ )
+ fixture.runtime.adapters.pop(fixture.session["session_id"])
+ session = fixture.store.load_session(fixture.session["session_id"])
+ adapter = fixture.runtime._ensure_adapter(
+ session, work_dir=fixture.project, objective="Produce a usable export"
+ )
+ assert starts[-1]["resume_thread_id"] == "original-thread"
+ assert adapter.upstream_thread_id == "original-thread"
+ assert [tool["name"] for tool in starts[-1]["dynamic_tools"]] == [
+ "loopx_context_read"
+ ]
+ else:
+ session, reused = fixture.runtime.open_session(
+ goal_id=fixture.session["goal_id"],
+ agent_id="codex",
+ managed_agent_id="agent-a",
+ work_dir=fixture.project,
+ objective="Produce a usable export",
+ mode="new",
+ )
+ assert not reused
+ adapter = fixture.runtime.adapters[session["session_id"]]
+ assert adapter.session._managed_goal_read_default is True
+ assert adapter.session._native_task_policy_used is False
+ wire = _capture_native_dispatch(
+ SimpleNamespace(native=adapter.session), monkeypatch
+ )
+ adapter.session.send("Read the original source.")
+ assert wire[-1]["params"]["sandboxPolicy"] == {
+ "type": "readOnly",
+ "networkAccess": False,
+ }
+ assert wire[-1]["params"]["threadId"] == adapter.upstream_thread_id
+ assert "managed_read_default" not in fixture.store.load_session(
+ session["session_id"]
+ )
+ assert "_managed_goal_read_default" not in fixture.store.load_session(
+ session["session_id"]
+ )
+ assert (
+ adapter.session.execution_mode is False
+ and adapter.session.sandbox == "read-only"
+ )
+
+
+def test_unbound_legacy_session_direct_send_preserves_default_native_payload(
+ original_check, monkeypatch
+):
+ fixture = original_check
+ assert fixture.native._managed_goal_read_default is False
+ assert fixture.native._native_task_policy_used is False
+ wire = _capture_native_dispatch(fixture, monkeypatch)
+ fixture.native.send("Read the source in this legacy transport.")
+ assert "sandboxPolicy" not in wire[-1]["params"]
+ assert (
+ fixture.native.execution_mode is False and fixture.native.sandbox == "read-only"
+ )
diff --git a/tests/control_plane/test_original_task_entry.py b/tests/control_plane/test_original_task_entry.py
new file mode 100644
index 0000000000..83e2105bf1
--- /dev/null
+++ b/tests/control_plane/test_original_task_entry.py
@@ -0,0 +1,230 @@
+"""Original Chat request reaches the existing repair checker and Task owner.
+
+The production HTTP/Chat/Core/File/SQLite owners execute; model interpretation
+and editing are scripted. The six preexisting repair checks remain independent.
+"""
+import hashlib
+import http.client
+import json
+import runpy
+import shutil
+import subprocess
+import sys
+import threading
+from pathlib import Path
+
+import pytest
+
+from test_new_goal_storage_defaults import environment as environment
+from loopx.chat_action_store import ChatActionStore
+from loopx.chat_actions import ChatActionService
+from loopx.chat_runtime import ChatRuntimeController
+from loopx.chat_server import ChatHTTPServer, ChatRequestHandler
+from loopx.chat_store import ChatSessionStore
+from loopx.capabilities.native_chat.project_context import ChatProjectContexts
+from loopx.control_plane.coordination.local_authority import read_canonical_todos_if_promoted
+from loopx.control_plane.goals.acceptance import inspect_goal_acceptance
+
+
+@pytest.fixture
+def cart_host(environment, monkeypatch):
+ _, bootstrap, _, project, runtime = environment
+ bootstrap("workspace")
+ exercise = Path(__file__).parents[2] / "examples/bugfix-loop"
+ for name in ("checks.py", "cart.py", "README.md"):
+ shutil.copy2(exercise / name, project / name)
+ capture, binary = runtime / "requests.jsonl", runtime / "synthetic-codex"
+ from loopx.control_plane.turn_driver import host_candidate
+ extract = host_candidate.extract_turn_authority
+ def capture_authority(*args, **kwargs):
+ authority = extract(*args, **kwargs)
+ (runtime / "native-authority.json").write_text(json.dumps(authority))
+ return authority
+ monkeypatch.setattr(host_candidate, "extract_turn_authority", capture_authority)
+ source = runpy.run_path(str(Path(__file__).parents[2] / "examples/loopx-chat-runtime-smoke.py"))["FAKE_CODEX"]
+ source = source.replace(' method = request.get("method")',
+ f' with open({str(capture)!r}, "a") as stream:\n stream.write(json.dumps(request) + "\\n")\n'
+ ' method = request.get("method")')
+ # The model proposes a same-workspace existing checker, with no absolute interpreter,
+ # source hash, Task id or Goal/Agent routing supplied as execution authority.
+ document = {"outcome_id": "goal-creation", "criteria": [{"id": "completion",
+ "validation_argv": ["python3", "checks.py"], "validation_timeout_seconds": 5,
+ "oracle": {"kind": "owner_pinned_oracle", "source_id": "bugfix-cart",
+ "input_refs": [], "output_refs": ["cart.py"]}}]}
+ source = source.replace(' elif method == "turn/start":',
+ ' elif request_id == 900 and method is None:\n'
+ ' evidence = json.loads(request["result"]["contentItems"][0]["text"])\n'
+ ' response = "" + json.dumps({"schema_version": "loopx_chat_agent_response_v0",\n'
+ ' "message": "The existing six-check repair plan is ready for owner review.", "proposals": [], "gate": None}) + ""\n'
+ ' print(json.dumps({"method": "item/agentMessage/delta", "params": {"threadId": "durable-thread", "turnId": active_turn, "delta": response}}), flush=True)\n'
+ ' print(json.dumps({"method": "turn/completed", "params": {"threadId": "durable-thread", "turn": {"id": active_turn}}}), flush=True)\n'
+ ' turn_status[active_turn] = "completed"\n'
+ ' continue\n'
+ ' elif method == "turn/start":')
+ source = source.replace(" response = 'Visible runtime response.",
+ f' if not __import__("pathlib").Path({str(project / "execute-native")!r}).exists():\n'
+ ' print(json.dumps({"id": 900, "method": "item/tool/call", "params": {\n'
+ ' "threadId": "durable-thread", "turnId": active_turn, "tool": "loopx_collaboration",\n'
+ ' "arguments": ' + repr({"action": "prepare_check", "operation_id": "original-cart-check", "document": document}) + '}}), flush=True)\n'
+ ' continue\n'
+ f' mode = __import__("pathlib").Path({str(project / "execute-native")!r}).read_text()\n'
+ ' if mode == "valid":\n'
+ f' assert request["params"].get("sandboxPolicy") == {{"type": "workspaceWrite", "writableRoots": [{str(project.resolve())!r}], "networkAccess": False, "excludeTmpdirEnvVar": True, "excludeSlashTmp": True}}\n'
+ f' path = __import__("pathlib").Path({str(project / "cart.py")!r})\n'
+ ' cart = path.read_text().replace(" if subtotal > 10_000:", " if not prices or subtotal >= 10_000:")\n'
+ ' path.write_text(cart)\n'
+ " response = 'Visible runtime response.")
+ candidate = {"result_kind": "validated_completion", "classification": "implementation",
+ "summary": "Repaired the empty-cart and free-shipping boundaries.",
+ "next_action": "Read back the original cart artifact and independent checks.",
+ "delivery_batch_scale": "implementation", "delivery_outcome": "outcome_progress",
+ "vision_unchanged_reason": "The original six-check cart repair remains the current task.",
+ "work_evidence": ["cart.py"], "validation_evidence": ["Unchanged checks.py verifies six original behaviors"]}
+ source = source.replace('"message": "Runtime response."', '"message": ' + repr(json.dumps(candidate)))
+ binary.write_text(source)
+ compile(source, str(binary), "exec")
+ binary.chmod(0o700)
+ store = ChatSessionStore(runtime / "chat")
+ registry = project / ".loopx/registry.json"
+ controller = ChatRuntimeController(store=store, codex_bin=str(binary), registry_path=registry,
+ project_contexts=ChatProjectContexts([project]))
+ actions = ChatActionStore(runtime / "chat/actions")
+ service = ChatActionService(store=actions, registry_path=registry,
+ runtime_controller=controller, chat_store=store)
+ server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler)
+ server.verbose = False
+ server.registry_path, server.runtime_root = registry, runtime
+ server.runtime_controller, server.action_store, server.action_service = controller, actions, service
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+
+ def request(path, body=None):
+ connection = http.client.HTTPConnection(*server.server_address, timeout=30)
+ try:
+ connection.request("GET" if body is None else "POST", path,
+ None if body is None else json.dumps(body), {"Content-Type": "application/json"})
+ response = connection.getresponse()
+ return response.status, json.loads(response.read())
+ finally:
+ connection.close()
+
+ try:
+ yield actions, request, controller, capture, project, runtime
+ finally:
+ server.shutdown()
+ thread.join(timeout=5)
+ server.server_close()
+ controller.close()
+
+
+def create_cart(cart_host):
+ _, request, controller, _, project, runtime = cart_host
+ status, preview = request("/api/actions/preview", {"action_kind": "goal.create",
+ "summary": "Repair the cart using its existing checks", "idempotency_key": "cart-repair-request",
+ "context": {"kind": "goal_channel", "goal_id": "workspace"}, "normalized_parameters": {
+ "goal_id": "cart-repair", "title": "Cart repair",
+ "objective": "Repair cart.py in this exercise workspace according to README.md and unchanged checks.py.",
+ "completion_criteria": "The six existing checks pass without changing checks.py.",
+ "agent_id": "codex", "workspace_ref": "current", "heartbeat": {"enabled": False},
+ "initial_todos": ["Repair cart.py to pass the six existing behavioral checks."]}})
+ assert status == 201, preview
+ proposal = preview["proposal"]
+ status, applied = request(f"/api/actions/{proposal['proposal_id']}/apply", {})
+ assert status == 202, applied
+ ids = applied["proposal"]["receipt"]["resource_ids"]
+ first = controller.wait_for_turn(session_id=ids["session_id"], turn_id=ids["turn_id"], timeout_sec=15)
+ assert first["status"] == "completed", first
+ messages = controller.store.messages(ids["session_id"])
+ assert messages[0]["text"] == proposal["normalized_parameters"]["objective"]
+ assert first["message"].startswith("开始推进 Goal"), "execution identity retains its original internal request"
+ basis = inspect_goal_acceptance(registry_path=controller.registry_path, runtime_root=str(runtime),
+ goal_id="cart-repair", agent_id="codex")
+ assert not basis.get("completion_requirements")
+ return proposal, ids, first
+
+
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+@pytest.mark.parametrize("mode", ["valid", "unconfirmed", "changed-source", "failed", "read-only"])
+def test_original_http_task_reuses_requested_checker_and_session(environment, cart_host, provider, mode):
+ configure, *_ = environment
+ configure(provider)
+ actions, request, controller, capture, project, runtime = cart_host
+ _, ids, first = create_cart(cart_host)
+ sid, todo = ids["session_id"], ids["todo_ids"][0]
+ session, history = controller.store.load_session(sid), controller.store.messages(sid)
+ checker_hash = hashlib.sha256((project / "checks.py").read_bytes()).hexdigest()
+ proposals = actions.list(goal_id="cart-repair", context_kind="goal")
+ checks = [row for row in proposals if row["action_kind"] == "goal.acceptance.check"]
+ assert len(checks) == 1, {"first": first, "proposals": proposals}
+ check = checks[0]
+ criterion = check["normalized_parameters"]["document"]["criteria"][0]
+ assert criterion["validation_argv"] == ["python3", "checks.py"]
+ assert Path(shutil.which("python3")).resolve() == Path(sys.executable).resolve()
+ assert criterion["validation_files"] == [{"path": "checks.py", "sha256": checker_hash}]
+ assert check["status"] == "preview_ready" and not first.get("loopx_execution")
+ calls_before = capture.read_bytes()
+ status, unavailable = request(f"/api/chat/sessions/{sid}/native-turn?original_task=true&agent_id=codex")
+ assert status == 200 and unavailable["task"]["state"] == "unbound", unavailable
+ if mode != "unconfirmed":
+ status, adopted = request(f"/api/actions/{check['proposal_id']}/apply", {})
+ assert status == 200 and adopted["proposal"]["receipt"]["checks_passed"] is False, adopted
+ assert capture.read_bytes() == calls_before, "check confirmation cannot launch a model/Task"
+ status, observed = request(f"/api/chat/sessions/{sid}/native-turn?original_task=true&agent_id=codex")
+ assert status == 200 and observed["task"]["state"] == "ready", observed
+ assert observed["task"]["todo_id"] == todo and not observed["task"]["canonical_done"]
+ assert "effects" not in observed["task"]
+ if mode == "changed-source":
+ (project / "checks.py").write_text("raise SystemExit(0)\n")
+ if mode in {"valid", "failed"}:
+ # An explicit, existing owner approval is separate from check adoption
+ # and native Task selection. Default new Goals do not gain write rights.
+ approved = subprocess.run([sys.executable, "-m", "loopx.entrypoint",
+ "--registry", str(controller.registry_path), "--runtime-root", str(runtime), "--format", "json",
+ "configure-goal", "--goal-id", "cart-repair", "--write-scope", "**",
+ "--boundary-authority-scope", "**", "--boundary-authority-source", "owner-approved-exercise",
+ "--boundary-authority-decision-id", "cart-workspace", "--execute"],
+ capture_output=True, text=True, timeout=20)
+ assert approved.returncode == 0, approved.stdout + approved.stderr
+ (project / "execute-native").write_text(mode)
+ status, accepted = request(f"/api/chat/sessions/{sid}/native-turn", {
+ "agent_id": "codex", "operation_id": "original-cart-execution", "todo_id": todo})
+ assert status == 202, accepted
+ turn = controller.wait_for_turn(session_id=sid, turn_id=accepted["turn"]["turn_id"], timeout_sec=20)
+ result = turn["response"]["native_loopx"]
+ assert result["status"] == {"valid": "committed", "unconfirmed": "stopped",
+ "changed-source": "stopped", "failed": "failed", "read-only": "failed"}[mode], result
+ assert result["effects"]["quota_spent"] is (mode == "valid")
+ assert result["effects"]["state_written"] is (mode == "valid")
+ authority = read_canonical_todos_if_promoted(runtime_root=runtime, goal_id="cart-repair", include_leases=True)
+ assert next(row for row in authority["todos"] if row["todo_id"] == todo)["status"] == ("done" if mode == "valid" else "open")
+ calls = [json.loads(line) for line in capture.read_bytes()[len(calls_before):].splitlines()]
+ native_calls = [row for row in calls if row.get("method") == "turn/start"]
+ assert len(native_calls) == (1 if mode in {"valid", "failed", "read-only"} else 0)
+ if native_calls:
+ assert native_calls[0]["params"]["sandboxPolicy"]["type"] == ("readOnly" if mode == "read-only" else "workspaceWrite")
+ assert controller.adapters[sid].session.sandbox == "read-only"
+ assert controller.adapters[sid].session.execution_mode is False
+ assert not any(row.get("method") == "thread/start" for row in calls)
+ assert controller.store.load_session(sid)["upstream_thread_id"] == session["upstream_thread_id"]
+ assert controller.store.messages(sid)[:len(history)] == history
+ after = capture.read_bytes()
+ status, replay = request(f"/api/chat/sessions/{sid}/native-turn", {
+ "agent_id": "codex", "operation_id": "original-cart-execution", "todo_id": todo})
+ assert status == 202 and not replay["created"] and replay["turn"]["turn_id"] == turn["turn_id"]
+ assert capture.read_bytes() == after
+ if mode == "valid":
+ (project / "execute-native").write_text("ordinary")
+ followup, created = controller.submit_turn(session_id=sid, client_turn_id="ordinary-after-task",
+ message="Explain the repaired behavior without changing the files.", work_dir=project,
+ objective="Retain the original cart repair.")
+ assert created
+ answered = controller.wait_for_turn(session_id=sid, turn_id=followup["turn_id"], timeout_sec=10)
+ assert answered["status"] == "completed" and "native_loopx" not in answered["response"]
+ later = [json.loads(line) for line in capture.read_bytes()[len(after):].splitlines()]
+ next_calls = [row for row in later if row.get("method") == "turn/start"]
+ assert len(next_calls) == 1 and next_calls[0]["params"]["sandboxPolicy"] == {
+ "type": "readOnly", "networkAccess": False}
+ assert not any(row.get("method") == "thread/start" for row in later)
+ check_run = subprocess.run([sys.executable, "checks.py"], cwd=project, capture_output=True, text=True, timeout=10)
+ assert check_run.returncode == 0 and "Ran 6 tests" in check_run.stderr
+ assert hashlib.sha256((project / "checks.py").read_bytes()).hexdigest() == checker_hash
diff --git a/tests/control_plane_ts/original_creation_task_selection.test.ts b/tests/control_plane_ts/original_creation_task_selection.test.ts
new file mode 100644
index 0000000000..7e6cba783d
--- /dev/null
+++ b/tests/control_plane_ts/original_creation_task_selection.test.ts
@@ -0,0 +1,69 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {originalCreationTaskSelection} from "../../loopx/control_plane/goals/task_validation_plan.ts";
+
+import {canonicalNativeTaskSandboxPolicy} from "../../loopx/control_plane/collaboration/steward_managed_mode.ts";
+
+const basis = (outcomes: unknown[]) => ({status: "loaded", provider_revision: "current",
+ goal_acceptance_contract: {outcome_requirements: {outcomes}}});
+
+test("original Task comes from retained creation work, independently of later outcomes", () => {
+ assert.deepEqual(originalCreationTaskSelection({basis: basis([
+ {id: "later", todo_ids: ["newest"]}, {id: "goal-creation", todo_ids: ["original"]},
+ ])}), {todo_id: "original", reason: null});
+});
+
+for (const [name, outcomes] of [
+ ["missing origin", [{id: "later", todo_ids: ["newest"]}]],
+ ["multiple initial Tasks", [{id: "goal-creation", todo_ids: ["first", "second"]}]],
+ ["removed work", [{id: "goal-creation", todo_ids: []}]],
+ ["duplicated origin", [{id: "goal-creation", todo_ids: ["one"]}, {id: "goal-creation", todo_ids: ["two"]}]],
+] as const) test(`${name} never selects the first or newest Task`, () => {
+ assert.equal(originalCreationTaskSelection({basis: basis([...outcomes])}).todo_id, null);
+});
+
+test("unavailable canonical authority is not a display selection", () => {
+ assert.throws(() => originalCreationTaskSelection({basis: {...basis([]), status: "unavailable"}}),
+ /current Goal acceptance basis/);
+});
+
+const policyInput = () => ({host: "codex-app-server", actor: {schema_version: "loopx_managed_session_actor_v0", goal_id: "goal",
+ agent_id: "agent", workspace_path: "/exercise"}, validation: {todo_id: "original", state: "ready"},
+authority: {_work_identity: {goal_id: "goal", agent_id: "agent", todo_id: "original"},
+ execution_preparation: {todo_id: "original", agent_id: "agent", state: "ready", delivery_allowed: true},
+ should_run: true, normal_delivery_allowed: true, goal_boundary: {}}});
+
+test("a native Task or its confirmed checks do not grant workspace writes", () => {
+ assert.deepEqual(canonicalNativeTaskSandboxPolicy(policyInput()), {type: "readOnly", networkAccess: false});
+});
+
+for (const scope of ["cart.py", "outputs/**"]) test(`narrow ${scope} approval is never widened to the workspace`, () => {
+ const input = policyInput();
+ input.authority.goal_boundary = {checkpointed_boundary_authority: {
+ schema_version: "checkpointed_boundary_authority_v0", active_count: 1, active_write_scope: [scope]}};
+ assert.deepEqual(canonicalNativeTaskSandboxPolicy(input), {type: "readOnly", networkAccess: false});
+});
+
+test("the original admitted Task uses the already approved workspace with network and temp writes disabled", () => {
+ const input = policyInput();
+ input.authority.goal_boundary = {checkpointed_boundary_authority: {
+ schema_version: "checkpointed_boundary_authority_v0", active_count: 1, active_write_scope: ["**"]}};
+ assert.deepEqual(canonicalNativeTaskSandboxPolicy(input), {type: "workspaceWrite", writableRoots: ["/exercise"],
+ networkAccess: false, excludeTmpdirEnvVar: true, excludeSlashTmp: true});
+});
+
+for (const count of [undefined, 0]) test(`an approval without an active count of ${count} grants no workspace writes`, () => {
+ const input = policyInput();
+ input.authority.goal_boundary = {checkpointed_boundary_authority: {
+ schema_version: "checkpointed_boundary_authority_v0", active_count: count, active_write_scope: ["**"]}};
+ assert.deepEqual(canonicalNativeTaskSandboxPolicy(input), {type: "readOnly", networkAccess: false});
+});
+
+test("Task substitution and an unavailable execution lease cannot yield host permissions", () => {
+ const substituted = policyInput();
+ substituted.authority._work_identity.todo_id = "other";
+ assert.throws(() => canonicalNativeTaskSandboxPolicy(substituted), /original admitted Task/);
+ const unavailable = policyInput();
+ unavailable.authority.execution_preparation.state = "unavailable";
+ assert.throws(() => canonicalNativeTaskSandboxPolicy(unavailable), /execution lease/);
+});