diff --git a/apps/presentation/dashboard/package.json b/apps/presentation/dashboard/package.json index 2e7d856b42..6360cf9020 100644 --- a/apps/presentation/dashboard/package.json +++ b/apps/presentation/dashboard/package.json @@ -5,6 +5,8 @@ "license": "Apache-2.0", "type": "module", "scripts": { + "smoke:goal-created-session": "tsc --noEmit --ignoreConfig --target ES2022 --module ES2022 --moduleResolution Bundler --allowImportingTsExtensions --types node --skipLibCheck --strict smoke/goal-created-session-smoke.ts src/vite-env.d.ts && vite build --ssr smoke/goal-created-session-smoke.ts --outDir node_modules/.cache/goal-created-session --emptyOutDir && node node_modules/.cache/goal-created-session/goal-created-session-smoke.js", + "smoke:goal-created-session-browser": "LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/goal-created-session-browser-smoke.mjs", "smoke:conversation-find": "LOOPX_PLAYWRIGHT_PACKAGE=\"$PWD/node_modules/playwright\" node smoke/conversation-find-browser-smoke.mjs", "smoke:queue-input-recovery": "vite build --ssr smoke/queue-input-recovery-smoke.mjs --outDir node_modules/.cache/queue-input-recovery --emptyOutDir && node node_modules/.cache/queue-input-recovery/queue-input-recovery-smoke.js", "smoke:todo-ownership": "vite build --ssr smoke/todo-ownership-smoke.mjs --outDir node_modules/.cache/todo-ownership --emptyOutDir && node node_modules/.cache/todo-ownership/todo-ownership-smoke.js", diff --git a/apps/presentation/dashboard/smoke/goal-created-session-browser-smoke.mjs b/apps/presentation/dashboard/smoke/goal-created-session-browser-smoke.mjs new file mode 100644 index 0000000000..65daaf9445 --- /dev/null +++ b/apps/presentation/dashboard/smoke/goal-created-session-browser-smoke.mjs @@ -0,0 +1,149 @@ +// Source frontend with synthetic HTTP reads; no model or active Goal state. +import assert from "node:assert/strict"; +import {mkdir} from "node:fs/promises"; +import {resolve} from "node:path"; +import {cleanupBrowserSmoke, launchBrowser, loadPlaywright, startViteDashboardServer} from "../../../../examples/dashboard-browser-smoke-support.mjs"; +import {dashboardDir, repoRoot, installApi} from "../../../../examples/personal-workspace-browser/fixture.mjs"; + +const port = Number(process.env.LOOPX_GOAL_CREATED_SESSION_PORT ?? "5349"); +const origin = `http://127.0.0.1:${port}`; +const evidence = process.env.LOOPX_GOAL_CREATED_SESSION_EVIDENCE ?? resolve(repoRoot, ".local/validation/goal-created-session"); +const server = await startViteDashboardServer({dashboardDir, port}); +let browser; +try { + browser = await launchBrowser(loadPlaywright().chromium); + await mkdir(evidence, {recursive: true}); + for (const scenario of ["managed", "legacy", "malformed"]) { + const page = await browser.newPage({viewport: {width: 1440, height: 960}}); + page.setDefaultTimeout(10000); + await page.emulateMedia({reducedMotion: "reduce"}); + await page.addInitScript(() => localStorage.setItem("loopx-pw-locale", "zh-CN")); + const proposalId = `create-${scenario}`, goalId = "progress-projection", owner = "codex", sessionId = "created-original-session"; + const proposal = {schema_version: "loopx_chat_action_proposal_v1", proposal_id: proposalId, action_kind: "goal.create", + summary: "Prepare the original Session journey", normalized_parameters: {goal_id: goalId, title: "Original Session journey / 原会话", + objective: "Retain the original work conversation", completion_criteria: ["Reopen its original history"], execution_boundary: "Synthetic readback only", agent_id: "codex"}, + context: {kind: "manager"}, expected_state_fingerprint: "original-fingerprint", permission_classification: "durable_write", + validation_evidence: ["Synthetic proposal is ready for the routing check"], available_transitions: ["apply", "cancel"], + status: "preview_ready", receipt: null, stale: null, created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z"}; + const api = await installApi(page, {fixturePort: port, initialActionProposals: [proposal]}); + api.registeredAgentsByGoal = {[goalId]: [owner]}; + const runtime = page.__loopxRuntime; + const session = {session_id: sessionId, goal_id: goalId, goal_instance_id: null, managed_agent_id: owner, + agent_id: "codex", adapter_kind: "codex_app_server", channel_id: `agent.${owner}`, session_mode: "managed_runtime", + status: "ready", active_turn_id: null, last_error_code: null, resumable: true, + created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z", last_activity_at: "2026-01-01T00:00:00Z"}; + runtime.sessions.set(sessionId, session); + const longText = "## Original first-run result / 原首轮结果\n\n" + Array.from({length: 24}, (_, i) => + `### Evidence ${i + 1} / 证据 ${i + 1}\n\nOriginal scope retained; independent acceptance remains unverified. 原始范围保留;独立验收尚未确认。`).join("\n\n"); + runtime.messages.set(sessionId, Array.from({length: 19}, (_, i) => ({message_id: `original-message-${i}`, role: i % 3 === 0 ? "user" : "agent", + turn_id: null, text: i === 18 ? longText : `Original conversation record ${i + 1} / 原会话记录 ${i + 1}:${i % 2 ? "failed check retained" : "unverified work retained"}`, + created_at: `2026-01-01T00:00:${String(i).padStart(2, "0")}Z`})).map((row, i) => i === 18 ? {...row, role: "agent"} : row)); + const writes = [], discovery = []; + let mode = "ready"; + page.on("request", request => { + if (request.method() !== "GET") writes.push({path: new URL(request.url()).pathname, body: request.postDataJSON()}); + }); + const errors = []; + page.on("pageerror", error => errors.push(error.message)); + await page.route("**/api/actions/**", async route => { + const path = new URL(route.request().url()).pathname; + if (path !== `/api/actions/${proposalId}/apply`) return route.fallback(); + const ids = {goal_id: goalId, goal_instance_id: null, agent_id: "codex", session_id: sessionId, + ...(scenario === "legacy" ? {} : {managed_agent_id: owner, channel_id: scenario === "malformed" ? `goal.${goalId}` : `agent.${owner}`})}; + const applied = {...proposal, status: "applied", available_transitions: [], receipt: {outcome: "goal_created", projection_verified: true, resource_ids: ids}, updated_at: "2026-01-01T00:00:01Z"}; + runtime.actionProposals.set(proposalId, applied); + return route.fulfill({json: {ok: true, proposal: applied}}); + }); + await page.route("**/api/chat/sessions**", async route => { + const request = route.request(), url = new URL(request.url()); + if (url.pathname === "/api/chat/sessions" && request.method() === "GET" && url.searchParams.has("managed_agent_id")) { + discovery.push([url.searchParams.get("goal_id"), url.searchParams.get("managed_agent_id")]); + const actual = runtime.sessions.get(sessionId); + const current = mode === "identity-failure" ? {...actual, channel_id: `goal.${goalId}`} : actual; + return route.fulfill({json: {ok: true, schema_version: "loopx_chat_session_list_v1", goal_id: goalId, + managed_agent_id: owner, goal_instance_id: null, sessions: [current]}}); + } + return route.fallback(); + }); + try { + await page.goto(`${origin}/?statusUrl=/status.json&view=conversation`, {waitUntil: "domcontentloaded"}); + const row = page.locator('.personal-proposal-row[data-action-kind="goal.create"]'); + await row.waitFor(); + await row.click(); + const drawer = page.locator('.personal-context-drawer[data-context-kind="proposal"]'); + await drawer.getByRole("button", {name: "创建 Goal 并开始首轮", exact: true}).click(); + const enter = drawer.getByRole("button", {name: "进入新 Goal", exact: true}); + if (scenario === "malformed") { + await drawer.getByRole("alert").filter({hasText: "无法验证新 Goal 的原 Session 地址"}).waitFor(); + assert.equal(await enter.count(), 0, "An invalid managed receipt must not expose the legacy Goal fallback"); + await page.screenshot({path: resolve(evidence, "managed-receipt-invalid-desktop.png"), animations: "disabled"}); + await page.reload({waitUntil: "domcontentloaded"}); + await row.waitFor(); await row.click(); + await drawer.getByRole("alert").filter({hasText: "无法验证新 Goal 的原 Session 地址"}).waitFor(); + assert.equal(await enter.count(), 0); + console.log("goal-created-session browser: PASS malformed receipt and reload"); + continue; + } + await enter.waitFor(); + await page.screenshot({path: resolve(evidence, `${scenario}-creation-receipt-desktop.png`), animations: "disabled"}); + await enter.click(); + await page.waitForURL(url => url.searchParams.get("goalId") === goalId); + const routed = new URL(page.url()); + if (scenario === "legacy") { + assert.equal(routed.searchParams.get("workAgent"), null); + assert.equal(routed.searchParams.get("workSession"), null); + assert.equal(routed.searchParams.get("view"), "overview"); + console.log("goal-created-session browser: PASS legacy navigation parity"); + continue; + } + assert.equal(routed.searchParams.get("workAgent"), owner); + assert.equal(routed.searchParams.get("workSession"), `managed:${sessionId}`); + assert.equal(routed.searchParams.get("view"), "conversation"); + const original = page.getByRole("heading", {name: "Original first-run result / 原首轮结果", exact: true}); + await original.waitFor(); + assert.ok(discovery.some(([goal, agent]) => goal === goalId && agent === owner)); + await page.screenshot({path: resolve(evidence, "managed-original-first-desktop.png"), animations: "disabled"}); + await original.evaluate(element => element.scrollIntoView({block: "start"})); + await page.screenshot({path: resolve(evidence, "managed-original-long-desktop.png"), animations: "disabled"}); + await page.reload({waitUntil: "domcontentloaded"}); await original.waitFor(); + assert.equal(new URL(page.url()).searchParams.get("workSession"), `managed:${sessionId}`); + const send = page.getByRole("button", {name: "发送", exact: true}), composer = page.getByLabel("向 LoopX 发送消息"); + await composer.fill("Keep this ordinary follow-up in the original Session."); + mode = "identity-failure"; + await page.reload({waitUntil: "domcontentloaded"}); + const error = page.getByRole("alert").filter({hasText: "cannot verify the registered Agent"}); + await error.waitFor(); + assert.equal(await send.isDisabled(), true); + assert.equal(await original.count(), 0, "Invalid discovery cannot show borrowed history"); + await page.screenshot({path: resolve(evidence, "managed-discovery-unavailable-desktop.png"), animations: "disabled"}); + await page.setViewportSize({width: 390, height: 844}); + await page.screenshot({path: resolve(evidence, "managed-discovery-unavailable-narrow.png"), animations: "disabled"}); + await page.setViewportSize({width: 1440, height: 960}); + mode = "ready"; + await error.getByRole("button", {name: "重新连接", exact: true}).click(); + await original.waitFor(); + await composer.fill("Keep this ordinary follow-up in the original Session."); + await send.click(); + await page.getByText("已沿用当前 Goal 与 Agent Session。接下来会先核对状态,再继续推进。", {exact: true}).waitFor(); + const turnWrites = writes.filter(row => /\/turns$/.test(row.path)); + assert.equal(turnWrites.length, 1); + assert.equal(turnWrites[0].path, `/api/chat/sessions/${sessionId}/turns`); + assert.equal(Object.hasOwn(turnWrites[0].body, "execution_control"), false, "An ordinary follow-up does not gain execution authority from the receipt"); + assert.equal(writes.some(row => row.path === "/api/chat/sessions" && row.body?.goal_id === goalId), false, + "Entering, reloading and retrying cannot create a replacement Goal Session"); + await page.setViewportSize({width: 390, height: 844}); + await original.evaluate(element => element.scrollIntoView({block: "start"})); + await page.screenshot({path: resolve(evidence, "managed-original-long-narrow.png"), animations: "disabled"}); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth + 1), false); + // Reopening the manager's receipt after reload is a read, never another apply. + await page.goto(`${origin}/?statusUrl=/status.json&view=conversation`, {waitUntil: "domcontentloaded"}); + await row.waitFor(); await row.click(); await enter.waitFor(); await enter.click(); await original.waitFor(); + assert.equal(writes.filter(row => row.path === `/api/actions/${proposalId}/apply`).length, 1); + assert.deepEqual(errors, []); + } catch (error) { + await page.screenshot({path: resolve(evidence, `${scenario}-failure.png`), animations: "disabled"}); + throw new Error(`${error.message}; url=${page.url()}; body=${(await page.locator("body").innerText()).slice(-10000)}`); + } finally {await page.unrouteAll({behavior: "ignoreErrors"}); await page.close();} + console.log(`goal-created-session browser: PASS ${scenario}`); + } +} finally {await cleanupBrowserSmoke({browser, server, dashboardDir, fixturePaths: []});} diff --git a/apps/presentation/dashboard/smoke/goal-created-session-smoke.ts b/apps/presentation/dashboard/smoke/goal-created-session-smoke.ts new file mode 100644 index 0000000000..ede6569481 --- /dev/null +++ b/apps/presentation/dashboard/smoke/goal-created-session-smoke.ts @@ -0,0 +1,79 @@ +import assert from "node:assert/strict"; +import {goalCreatedManagedSession} from "../src/features/personal-workspace/goal-created-session"; +import {conversationChannelId, conversationContextKey, createChatSession, fetchChatHistory, type TypedActionProposal} from "../src/data/chat"; + +const resources = {goal_id: "research", goal_instance_id: null, agent_id: "codex", + managed_agent_id: "codex", channel_id: "agent.codex", session_id: "original-session"}; +const proposal: TypedActionProposal = {schema_version: "loopx_chat_action_proposal_v1", proposal_id: "create-original", + action_kind: "goal.create", status: "applied", summary: "Create the original work Session", + normalized_parameters: {goal_id: "research", agent_id: "codex"}, context: {kind: "manager"}, + expected_state_fingerprint: "original-source", permission_classification: "durable_write", + validation_evidence: ["Original Session identity was read back"], available_transitions: [], stale: null, + created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:01Z", + receipt: {outcome: "goal_created", projection_verified: true, resource_ids: resources}}; +const address = goalCreatedManagedSession(proposal)!; +assert.deepEqual(address, {target: {goalId: "research", agentId: "codex", sessionId: "original-session"}}, + "The recorded registered owner and explicit null lifetime retain the original Session"); +assert.deepEqual(goalCreatedManagedSession({...proposal, receipt: {...proposal.receipt, resource_ids: {...resources, goal_instance_id: "explicit-instance"}}}), address); +assert.equal(goalCreatedManagedSession({...proposal, receipt: {resource_ids: {goal_id: "research", agent_id: "codex", session_id: "legacy"}}}), undefined, + "Legacy receipts keep their original navigation without inventing managed identity"); +for (const changed of [{goal_id: "another-goal"}, {managed_agent_id: null}, {managed_agent_id: ""}, {managed_agent_id: "another-worker"}, {session_id: ""}, + {channel_id: "goal.research"}, {goal_instance_id: undefined}, {goal_instance_id: ""}, {agent_id: "other-executor"}]) { + assert.deepEqual(goalCreatedManagedSession({...proposal, receipt: {...proposal.receipt, resource_ids: {...resources, ...changed}}}), {invalid: true}, + "A marked but unreadable address is an error, never a legacy fallback"); +} +const missingLifetime = {...resources} as Record; delete missingLifetime.goal_instance_id; +assert.deepEqual(goalCreatedManagedSession({...proposal, receipt: {...proposal.receipt, resource_ids: missingLifetime}}), {invalid: true}); +for (const changed of [{outcome: "other"}, {outcome: undefined}, {projection_verified: false}, {projection_verified: undefined}]) { + assert.deepEqual(goalCreatedManagedSession({...proposal, receipt: {...proposal.receipt, ...changed}}), {invalid: true}); +} +for (const changed of [{status: "preview_ready"}, {action_kind: "team.plan"}]) { + assert.equal(goalCreatedManagedSession({...proposal, ...changed} as TypedActionProposal), undefined); +} + +const target = address.target!, context = {kind: "managed" as const, ...target}; +assert.equal(conversationChannelId(context), "agent.codex"); +assert.equal(conversationContextKey(context), "managed/research/codex/original-session"); +const originalFetch = globalThis.fetch, requests: string[] = []; +const session = {session_id: target.sessionId, goal_id: target.goalId, goal_instance_id: resources.goal_instance_id, + managed_agent_id: target.agentId, channel_id: resources.channel_id, agent_id: "codex", adapter_kind: "codex_app_server", + session_mode: "managed_runtime", status: "ready", active_turn_id: null, resumable: true, last_error_code: null, + created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z", last_activity_at: "2026-01-01T00:00:00Z"}; +let discoveryMode = "original", snapshotMode = "original"; +try { + globalThis.fetch = async (input, init) => { + assert.equal(init?.method ?? "GET", "GET", "Reopening and retrying never create a Session or Turn"); + const url = new URL(String(input), "http://127.0.0.1"); + requests.push(url.pathname + url.search); + if (url.pathname === "/api/chat/sessions") { + assert.equal(url.searchParams.get("goal_id"), "research"); + assert.equal(url.searchParams.get("managed_agent_id"), "codex"); + const listedSession = discoveryMode === "changed" ? {...session, channel_id: "goal.research"} : session; + return Response.json({ok: true, schema_version: "loopx_chat_session_list_v1", goal_id: "research", + managed_agent_id: "codex", goal_instance_id: resources.goal_instance_id, + sessions: discoveryMode === "missing" ? [] : [listedSession]}); + } + assert.equal(url.pathname, "/api/chat/sessions/original-session"); + return Response.json({ok: true, schema_version: "loopx_chat_store_v1", + session: snapshotMode === "changed" ? {...session, goal_instance_id: "replacement-instance"} : session, + active_turn: null, messages: [{message_id: "original-answer", role: "agent", turn_id: null, + text: "Original result 原始结果", created_at: session.created_at}]}); + }; + assert.equal((await createChatSession(context, "codex")).session_id, "original-session"); + await assert.rejects(() => createChatSession(context, "codex", "new")); + const history = await fetchChatHistory({channelId: conversationContextKey(context), managed: target}); + assert.deepEqual(history.messages.map(row => [row.session_id, row.text]), [["original-session", "Original result 原始结果"]]); + assert.equal((await fetchChatHistory({channelId: conversationContextKey(context), managed: target}, history)).sessions[0].session_id, "original-session"); + discoveryMode = "missing"; + await assert.rejects(() => createChatSession(context, "codex"), /no longer available/); + discoveryMode = "changed"; + await assert.rejects(() => fetchChatHistory({channelId: conversationContextKey(context), managed: target}), /cannot verify/); + discoveryMode = "original"; snapshotMode = "changed"; + const unavailable = await fetchChatHistory({channelId: conversationContextKey(context), managed: target}); + assert.deepEqual(unavailable.messages, [], "Changed lifetime cannot expose another Goal's transcript"); + assert.deepEqual(unavailable.unavailableSessionIds, ["original-session"]); + snapshotMode = "original"; + assert.equal((await fetchChatHistory({channelId: conversationContextKey(context), managed: target}, unavailable)).messages[0].text, "Original result 原始结果"); + assert.ok(requests.every(path => path.startsWith("/api/chat/sessions"))); +} finally {globalThis.fetch = originalFetch;} +console.log("goal-created-session: original owner/history, replay, legacy parity and identity failure/recovery passed"); diff --git a/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx b/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx index 407073ec4e..60f5fe2ed1 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/context-drawer.tsx @@ -1254,7 +1254,8 @@ export function ContextDrawer({ agents, attentionHistory = [], onSelectAttention : selection.item.status === "applied" && selection.item.actionKind !== "team.plan" ?

{selection.item.actionKind === "operation.execute" ? selection.item.primaryLabel : t(taskExecution ? "feedback.taskStartRequested" : "drawer.proposalApplied")}

: null} {taskExecution ? - : selection.item.status === "applied" && selection.item.actionKind !== "operation.execute" && selection.item.goalId ? : null} + : selection.item.createdManagedSession?.invalid ?

{t("proposal.goalSessionUnavailable")}

+ : selection.item.status === "applied" && selection.item.actionKind !== "operation.execute" && selection.item.goalId ? : null} {selection.item.status === "stale" ?

{t("drawer.proposalStale")}

: null} {selection.item.status === "error" && !selection.item.reviewPlan?.retryOriginal ?
{operationUnknown ? t("proposal.operationState.submission_unknown") : selection.item.actionKind === "team.plan" || selection.item.actionKind === "goal.create" || selection.item.reviewPlan?.reason === "readback_unverified" ? t("actionReview.readback_unverified") : t("drawer.proposalApplyFailed")}{selection.item.errorMessage ? {selection.item.errorMessage} : null}{selection.item.actionKind !== "goal.create" ? {t(operationUnknown ? "actionReview.operation_reconcile_original" : selection.item.actionKind === "team.plan" ? "proposal.teamPlan.retryUnavailable" : "drawer.proposalApplyFailedHint")} : null}
: null} {selection.item.status === "rejected" ?

{t("drawer.proposalRejected")}

: null} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-agent-work-page.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-agent-work-page.tsx index 8cdeb7c3fd..8279e95b1f 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-agent-work-page.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-agent-work-page.tsx @@ -7,9 +7,10 @@ import {useWorkspaceI18n} from "./i18n"; import type {WorkspaceGoal} from "./personal-workspace-model"; /** Navigation uses the Goal directory; only the native provider can authorize a conversation. */ -export function GoalAgentWorkPage({goal, agentId, readOnly, sessionId, onSession, children, onSelect, onClose}: { +export function GoalAgentWorkPage({goal, agentId, readOnly, sessionId, onSession, onRetryManagedSession, children, onSelect, onClose}: { goal: WorkspaceGoal; agentId: string; readOnly: boolean; sessionId?: string; onSession: (sessionId: string, replace?: boolean) => void; children?: ReactNode; + onRetryManagedSession?: () => void; onSelect: (agentId: string) => void; onClose: () => void; }) { const zh = useWorkspaceI18n().locale === "zh-CN"; @@ -37,14 +38,15 @@ export function GoalAgentWorkPage({goal, agentId, readOnly, sessionId, onSession : readOnly ?

{zh ? "此来源仅提供状态快照,无法在这里读取或回复原会话。" : "This source provides a status snapshot; original conversations cannot be read or replied to here."}

: !registered ?

{zh ? "此 Agent 不在当前 Goal 的已注册列表中,请选择列表中的 Agent。" : "This Agent is not registered in the current Goal. Choose an Agent from its directory."}

: {children}} + zh={zh} sessionId={sessionId} onSession={onSession} onRetryManagedSession={onRetryManagedSession}>{children}} ; } /** Both providers stay under the registered Agent; the reader retains its original owner. */ -function AgentSessions({goalId, agentId, hosts, attached, zh, sessionId, onSession, children}: { +function AgentSessions({goalId, agentId, hosts, attached, zh, sessionId, onSession, onRetryManagedSession, children}: { goalId: string; agentId: string; hosts: string[]; attached: boolean; zh: boolean; sessionId?: string; onSession: (sessionId: string, replace?: boolean) => void; children?: ReactNode; + onRetryManagedSession?: () => void; }) { const selectionKey = `loopx-attached-selection:${goalId}:${agentId}`; const [selected, setSelected] = useState(() => { @@ -53,7 +55,10 @@ function AgentSessions({goalId, agentId, hosts, attached, zh, sessionId, onSessi }); const [directory, setDirectory] = useState<{bindings: Binding[]; managed: ChatSessionSummary[]; errors: string[]} | null>(null); const [revision, setRevision] = useState(0); - const reconnect = () => setRevision(value => value + 1); + const reconnect = () => { + setRevision(value => value + 1); + if (sessionId?.startsWith("managed:")) onRetryManagedSession?.(); + }; const previousRoute = useRef(sessionId); const selectedValue = sessionId !== undefined ? sessionId : previousRoute.current !== sessionId ? "" : selected; useEffect(() => { diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-created-session.ts b/apps/presentation/dashboard/src/features/personal-workspace/goal-created-session.ts new file mode 100644 index 0000000000..cc42d1428c --- /dev/null +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-created-session.ts @@ -0,0 +1,20 @@ +import type {ManagedConversationTarget, TypedActionProposal} from "../../data/chat"; + +/** Display address only. The existing managed Session reader verifies it again. */ +export function goalCreatedManagedSession(proposal: TypedActionProposal): {target?: ManagedConversationTarget; invalid?: true} | undefined { + if (proposal.action_kind !== "goal.create" || proposal.status !== "applied") return undefined; + const ids = proposal.receipt?.resource_ids; + if (!ids || typeof ids !== "object" || Array.isArray(ids) || !Object.hasOwn(ids, "managed_agent_id")) return undefined; + const resources = ids as Record; + const goalId = resources.goal_id, agentId = resources.managed_agent_id, sessionId = resources.session_id; + if (proposal.receipt?.outcome !== "goal_created" || proposal.receipt.projection_verified !== true || resources.agent_id !== "codex" + || typeof goalId !== "string" || !/^[A-Za-z0-9._-]{1,160}$/.test(goalId) + || goalId !== proposal.normalized_parameters.goal_id + || typeof agentId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,119}$/.test(agentId) + || agentId !== proposal.normalized_parameters.agent_id + || typeof sessionId !== "string" || !/^[A-Za-z0-9._-]{1,160}$/.test(sessionId) + || resources.channel_id !== `agent.${agentId}` + || !Object.hasOwn(resources, "goal_instance_id") || !(resources.goal_instance_id === null + || typeof resources.goal_instance_id === "string" && resources.goal_instance_id.length > 0)) return {invalid: true}; + return {target: {goalId, agentId, sessionId}}; +} diff --git a/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx b/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx index 2058fc1e13..a0901ce7c4 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/i18n.tsx @@ -400,6 +400,7 @@ const en = { "drawer.proposalDefer": "Later", "drawer.proposalDeferred": "Deferred. You can apply it later or regenerate it.", "drawer.proposalEnterGoal": "Open new Goal", + "proposal.goalSessionUnavailable": "The new Goal's original Session address could not be verified. Retry the receipt readback.", "drawer.proposalExplainer": "After confirmation, LoopX applies this change and shows the write result. Closing or canceling changes nothing.", "drawer.proposalRecheck": "Recheck against latest state", "drawer.proposalRegenerate": "Retry with latest state", @@ -2018,6 +2019,7 @@ const zhCN: Record = { "drawer.proposalDefer": "稍后", "drawer.proposalDeferred": "已暂缓,可稍后继续应用或重新生成。", "drawer.proposalEnterGoal": "进入新 Goal", + "proposal.goalSessionUnavailable": "无法验证新 Goal 的原 Session 地址,请重试读取创建回执。", "drawer.proposalExplainer": "确认后,LoopX 会执行这项变更并显示写入结果。关闭或取消不会修改任何状态。", "drawer.proposalRecheck": "按最新状态重新检查", "drawer.proposalRegenerate": "基于最新状态重试", diff --git a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs index b232a83b46..c571156d7e 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs +++ b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-contract.test.mjs @@ -210,8 +210,8 @@ assert.match(page, /\.map\(\(\[key, value\]\) => \(\{[\s\S]*key,[\s\S]*label: fi assert.match(page, /field\.key === "cadence"[\s\S]*field\.key === "stop_condition"[\s\S]*field\.key === "timezone"/, "Applied Heartbeat readback consumes stable semantic keys"); assert.doesNotMatch(page, /field\.label === "cadence"|field\.label === "stop condition"/, "Schedule semantics never depend on localized display labels"); assert.match(page, /defaultTimeline\(model, managerProjectionId, t\)/, "Default schedule projection uses the active locale authority"); -assert.match(page, /onOpenGoal: \(goalId\) => \{\s*selectGoal\(goalId\);\s*void reconcileStatus\(\[goalId\]\)/, "Applied-action Goal navigation is immediate and reconciles that Goal in the background"); -assert.match(drawer, /onClose\(\); void callbacks\.onOpenGoal\?\.\(goalId\)/, "Applied-action Goal navigation closes its result drawer before asynchronous reconciliation"); +assert.match(page, /onOpenGoal: \(goalId, managedSession\) => \{\s*selectGoal\(goalId, managedSession \? "chat" : "overview", managedSession\);\s*void reconcileStatus\(\[goalId\]\)/, "Applied-action navigation carries the original managed Session and reconciles its Goal in the background"); +assert.match(drawer, /onClose\(\); void callbacks\.onOpenGoal\?\.\(goalId, selection\.item\.createdManagedSession\?\.target\)/, "Applied-action navigation closes its drawer before opening the original Session or legacy Goal"); assert.match(tasks, /aria-busy=\{quickCompletingTodoIds\?\.has\(todo\.todoId\)/, "Quick Todo completion exposes accessible pending state while its typed preview is prepared"); assert.match(tasks, /disabled=\{quickCompletingTodoIds\?\.has\(todo\.todoId\)\}/, "Quick Todo completion rejects duplicate clicks while preview creation is pending"); assert.match(page, /callbacks\.onGoalActivationStateChange\?\.\(lifecycleChange\.goalId, lifecycleChange\.next\)/, "Goal lifecycle apply projects the requested state before the server responds"); diff --git a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts index a7b9fc82cc..8c2af83600 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts +++ b/apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-model.ts @@ -1,7 +1,7 @@ import type { GoalDraft } from "../../../../../../loopx/control_plane/collaboration/goal_draft.js"; import type { TurnStep } from "../../data/turn-steps"; import type { ChatProject, CollaborationReadback, LoopXModeSettings } from "../../data/chat-model"; -import type { BoundConversationTarget, ChatSessionSummary, BoundConversationSource, ChatReplyContext } from "../../data/chat"; +import type { BoundConversationTarget, ChatSessionSummary, BoundConversationSource, ChatReplyContext, ManagedConversationTarget } from "../../data/chat"; import type { TeamPlanAppliedOutcome } from "./team-plan-preview"; import type { ActionReviewPlan } from "../../../../../../loopx/control_plane/presentation/action_review_plan.js"; import type { GoalAcceptanceObservation } from "../../data/goal-acceptance-observation"; @@ -347,6 +347,8 @@ export type WorkspaceActionPreview = { /** Stored Todo operation for result wording; never grants execution authority. */ todoOperation?: string; reviewPlan?: ActionReviewPlan; + /** Creation receipt address; unavailable identity never falls back to a new Goal Session. */ + createdManagedSession?: {target?: ManagedConversationTarget; invalid?: true}; actionKind: | "goal.create" | "goal.update" @@ -583,7 +585,7 @@ export type PersonalWorkspaceCallbacks = { onSteerConversationTurn?: (contextId: string, turnId: string, message: string, ingressId: string) => Promise; onQueueConversationTurn?: (contextId: string, sessionId: string, message: string, ingressId: string, attachments?: WorkspaceImageAttachment[]) => Promise; onObserveConversationQueue?: (contextId: string, sessionId: string) => Promise; - onOpenGoal?: (goalId: string) => void | Promise; + onOpenGoal?: (goalId: string, managedSession?: ManagedConversationTarget) => void | Promise; onOpenGoalView?: (tab: WorkspaceGoalTab) => void; onOpenRunSession?: (run: WorkspaceRun) => void | Promise; onOpenOutput?: (output: WorkspaceOutput) => void; @@ -637,7 +639,7 @@ export type PersonalWorkspaceCallbacks = { onSelectAgentModel?: (agentId: string, modelId: string) => void | Promise; onSelectAgentReasoningEffort?: (agentId: string, effort: string) => void | Promise; onSelectChannel?: (channel: WorkspaceChannel) => void; - onSelectGoal?: (goalId: string | null, view: WorkspaceGoalTab) => void; + onSelectGoal?: (goalId: string | null, view: WorkspaceGoalTab, managedSession?: ManagedConversationTarget) => void; onSelectTodo?: (todoId: string | null) => void; onSelectView?: (view: WorkspaceGoalTab) => void; onSelectWorkAgent?: (agentId: string | null, sessionId?: string) => void; 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 cae5df70fe..4a427fe472 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 @@ -7,6 +7,7 @@ import {hasConfiguredGoalChecks} from "../../data/goal-acceptance-observation"; import {useDeliveryReview} from "./delivery-review-state"; import {useGoalWorkspaceDigest} from "./goal-masthead"; import { goalCreateRequest, goalCreationAgentId, goalDraftReady } from "./goal-create-request"; +import { goalCreatedManagedSession } from "./goal-created-session"; import { completedActionFeedback, todoCompletionPreviewFeedback, todoCompletionProofRequired } from "./todo-completion-feedback"; import { readSteeringRequest, retainSteeringRequest, retireSteeringRequest, legacySteeringRequests, restoreLegacySteeringRequest } from "./steering-recovery"; import { conversationInputKey, useConversationInputState } from "./use-conversation-input-state"; @@ -45,6 +46,7 @@ import { type LarkGoalConnection, type ManagerChannelBinding, type ManagerRuntimeSessionReadback, + type ManagedConversationTarget, type TypedActionProposal, agentBackendLabel } from "../../data/chat"; import { useTypedActionReadback, useTypedActionProposalReadback } from "../../data/use-typed-action-readback"; @@ -714,6 +716,7 @@ function workspaceProposal(proposal: TypedActionProposal, t: WorkspaceTranslate) todoOperation: proposal.action_kind === "todo.update" && typeof proposal.normalized_parameters.operation === "string" ? proposal.normalized_parameters.operation : undefined, reviewPlan, + createdManagedSession: goalCreatedManagedSession(proposal), fields: proposal.action_kind === "operation.execute" ? operationProposalFields(proposal, reviewPlan, t) : proposal.action_kind === "team.plan" @@ -1761,6 +1764,7 @@ export function PersonalWorkspacePage({ || compileActionReviewPlan(proposal).retryOriginal === true || (proposal.action_kind === "team.plan" && proposal.status === "applied") || (proposal.action_kind === "todo.create" && proposal.status === "applied") + || goalCreatedManagedSession(proposal) !== undefined // Terminal operations replace cached gated cards, including in an // already-open drawer. They never authorize local execution. || proposal.action_kind === "operation.execute") @@ -2251,8 +2255,8 @@ export function PersonalWorkspacePage({ setActiveSessionRun(run); setSelection(null); }, - onOpenGoal: (goalId) => { - selectGoal(goalId); + onOpenGoal: (goalId, managedSession) => { + selectGoal(goalId, managedSession ? "chat" : "overview", managedSession); void reconcileStatus([goalId]); }, onOpenGoalView: (tab) => { @@ -2383,13 +2387,13 @@ export function PersonalWorkspacePage({ onOpenOutput: drawerCallbacks.onOpenOutput, } : drawerCallbacks; - function selectGoal(goalId: string | null, view: WorkspaceGoalTab = "overview") { + function selectGoal(goalId: string | null, view: WorkspaceGoalTab = "overview", managedSession?: ManagedConversationTarget) { setLocalGoalId(goalId); setActiveSessionRun(null); setSelection(null); setLocalView(view); setMobileSidebarOpen(false); - callbacks.onSelectGoal?.(goalId, view); + callbacks.onSelectGoal?.(goalId, view, managedSession); } function openAttention(item: WorkspaceAttention) { @@ -3042,6 +3046,7 @@ export function PersonalWorkspacePage({ files: goalResults(selectedGoalTab === "files" && !settingsOpen), chat: agentWorkActive ? callbacks.onSelectWorkSession?.(id, replace)} + onRetryManagedSession={workspaceConversations?.managed?.retry} onSelect={id => callbacks.onSelectWorkAgent?.(id)} onClose={() => callbacks.onSelectWorkAgent?.(null)}> {workspaceConversations?.managed?.error ?

{workspaceConversations.managed.error}

: null} item.kind === "message")} onSelect={setSelection} selectedGoal={selectedGoal} diff --git a/apps/presentation/dashboard/src/views/dashboard-page.tsx b/apps/presentation/dashboard/src/views/dashboard-page.tsx index 505fcc9345..0a85804d04 100644 --- a/apps/presentation/dashboard/src/views/dashboard-page.tsx +++ b/apps/presentation/dashboard/src/views/dashboard-page.tsx @@ -58,6 +58,7 @@ import { createChatSession, type ConversationContext, type BoundConversationTarget, + type ManagedConversationTarget, updateLoopXMode, type LoopXModeSettings, fetchChatCapabilities, @@ -1324,7 +1325,7 @@ function PersonalGoalHome({ onSelectView: (view: WorkspaceGoalTab) => void; onGoalActivationStateChange: (goalId: string, activationState: "active" | "stopped") => void; onGoalDeleted: (goalId: string) => void; - onSelectGoal: (goalId: string, view?: WorkspaceGoalTab) => void; + onSelectGoal: (goalId: string, view?: WorkspaceGoalTab, managedSession?: ManagedConversationTarget) => void; onSelectWorkspace: (projectRef: string | null) => void; onOpenOriginalConversation: (target: BoundConversationTarget) => void; boundConversation: BoundConversationTarget | null; @@ -1443,8 +1444,8 @@ function PersonalGoalHome({ const originalConversation = rootGoalId && boundConversation ? { session: undefined, source: undefined, error: "Original conversation is outside this Goal navigation scope.", retry: originalReadback.retry } : originalReadback; - const managedTarget = selectedWorkAgentId != null && selectedWorkSessionId?.startsWith("managed:") && selectedGoal - ? {goalId: selectedGoal.goalId, agentId: selectedWorkAgentId, sessionId: selectedWorkSessionId.slice(8)} : null; + const managedTarget = selectedWorkAgentId != null && selectedWorkSessionId?.startsWith("managed:") && requestedGoalId + ? {goalId: requestedGoalId, agentId: selectedWorkAgentId, sessionId: selectedWorkSessionId.slice(8)} : null; const managedConversation = useManagedConversation(managedTarget, !readOnly); const fixedSession = Boolean(boundConversation || managedTarget); const conversationContext: ConversationContext = managedTarget ? {kind: "managed", ...managedTarget} : boundConversation @@ -3360,7 +3361,7 @@ function PersonalGoalHome({ onSelectAgent: (agentId) => { onClearMessageFocus?.(); return chooseAgent(agentId); }, onSelectAgentModel: chooseAgentModel, onSelectAgentReasoningEffort: chooseAgentReasoningEffort, - onSelectGoal: (goalId, view) => onSelectGoal(goalId ?? "", view), + onSelectGoal: (goalId, view, managedSession) => onSelectGoal(goalId ?? "", view, managedSession), onSelectView, onSelectWorkAgent, onSelectWorkSession, @@ -3924,7 +3925,7 @@ export function DashboardPage() { } }, [search.goalId, isLoading, progress, source]); - function selectGoal(goalId: string, view?: WorkspaceGoalTab) { + function selectGoal(goalId: string, view?: WorkspaceGoalTab, managedSession?: ManagedConversationTarget) { void navigate({ hash: search.goalId === goalId ? keepCaseChapterHash : undefined, search: (current) => { @@ -3938,7 +3939,7 @@ export function DashboardPage() { conversationBinding: undefined, conversationSession: undefined, messageSession: undefined, message: undefined, - workAgent: undefined, workSession: undefined, + workAgent: managedSession?.agentId, workSession: managedSession ? `managed:${managedSession.sessionId}` : undefined, todo: undefined, view: view === "chat" ? "conversation" : view, }); diff --git a/docs/architecture/rfcs/assets/goal-entry-original-session-desktop.webp b/docs/architecture/rfcs/assets/goal-entry-original-session-desktop.webp new file mode 100644 index 0000000000..f220c137b7 Binary files /dev/null and b/docs/architecture/rfcs/assets/goal-entry-original-session-desktop.webp differ diff --git a/docs/architecture/rfcs/assets/goal-entry-original-session-narrow.webp b/docs/architecture/rfcs/assets/goal-entry-original-session-narrow.webp new file mode 100644 index 0000000000..18de218367 Binary files /dev/null and b/docs/architecture/rfcs/assets/goal-entry-original-session-narrow.webp differ diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.md index 9f57aa581e..5d5536f400 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -4257,3 +4257,52 @@ File/SQLite negative cases guard this boundary without changing valid activation Task adoption. Full V1–V5/V10, native-model/context retention, D2/D5 closure, progressive controls, comparable complete costs, R1/M3 and C1 cutover remain unqualified; preserve original acceptance and full-goal regression gates. + +### 2026-11-15 — First Goal retains its original registered conversation + +- **Gap:** default Codex Goal creation opened an unassigned Goal conversation. + Re-entry could open another legacy conversation; a lost opening response + could select a later Session, and the receipt did not re-read stored identity. +- **Delta:** the existing TypeScript presentation owner selects the registered + Agent identity for a new default Codex Session. The Chat owner binds opening + to the original creation operation, reuses only that published Session and + rechecks the actual Goal, Agent, route, lifetime and workspace before dispatch + and receipt delivery. Unknown reservations and unidentified or ambiguous + historical originals hold recovery. Existing recorded legacy Sessions, explicit native token budgets and + other endpoints retain their paths. The frontend enters the original Agent + conversation through existing directory, Session and history readers; invalid + receipts expose recovery instead of opening another conversation. +- **Evidence:** isolated real Chat/Core/File/SQLite tests exercise original-Task + adoption with explicit owner checks, missing/failed-check refusal, retained + history, concurrent published-Session opening, lost responses, original-action + replay and changed identities. The unchanged runtime compatibility corpus + passes 106 cases on both the immutable base and candidate. The presentation + reducer passes its 27-case suite and preserves all non-routing fields in + 56 base/head vectors. Browser checks cover populated desktop/narrow views, + reload, invalid receipts and one reconnect restoring original history. +- **Maintainability:** Session readback is shared in the existing Chat Session + entry owner. The Runtime coordinator grows from 2,503 to 2,524 lines for the + exact opening seam and early identity fence; its reviewed ceiling records that bounded change rather + than duplicating readback or adding another execution pipeline. This is no + latency, default-closure or complete-cost qualification. +- **Boundary:** ordinary first and subsequent messages remain ordinary read-only + Chat. An explicitly checked original Task uses the existing Native owner; + this does not automatically provide a trusted checker or adopt every reply. + Recovery evidence covers published Sessions, not an unrecorded native + thread-start effect. A real native attempt failed: its configured model is + unsupported by the selected account. Synthetic success and account-read + readiness do not override that negative result. Full V1–V5/V10, model/context + retention, D2/D5 closure, progressive controls, comparable complete costs, + R1/M3 and C1 cutover remain unqualified. Preserve the original ten requirements + and run full original-goal regression before completion. + +The current entry design keeps the original reply and message input together. +Re-entry follows the recorded Session rather than selecting a new conversation. +These desktop and narrow references show the packaged frontend with its real +SQLite/Chat owners and synthetic replies; the unverified acceptance remains +visible. They illustrate the presentation boundary, not model or outcome +qualification. + +![Original Goal conversation on desktop](assets/goal-entry-original-session-desktop.webp) + +![Original Goal conversation at a narrow viewport](assets/goal-entry-original-session-narrow.webp) 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 7f61d428c7..0f8de6b1b8 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -3306,3 +3306,38 @@ R1/M3、C1 切换和原目标回归仍未完成资格验证。 Goal 安装可信检查器,不授权模型或 browser 命令,也不完成首个 Task 自动采用。 完整 V1–V5/V10、原生模型与 context 保留、D2/D5 闭包、渐进控制、可比完整成本、 R1/M3 和 C1 切换仍未通过资格验证;原验收与完整目标回归门继续保留。 + +### 2026-11-15 — 首个 Goal 保留原注册会话 + +- **缺口:**默认 Codex Goal 创建打开了未分配的 Goal 会话。重入可能再开旧式 + 会话;打开响应丢失后可能选中后来创建的 Session,回执也未复核实际存储身份。 +- **增量:**既有 TypeScript presentation owner 为新的默认 Codex Session 选择 + 注册 Agent 身份。Chat owner 将打开操作绑定到原创建操作,只复用已发布的原 + Session,并在派发和回执交付前核对实际 Goal、Agent、路由、生命周期及 workspace。 + 未知 reservation、无法确认或不明确的历史原会话会停止恢复。已有记录的旧式 Session、显式原生 + token budget 和其他 endpoint 保留原路径。前端通过既有目录、Session 与历史 + reader 进入原 Agent 会话;无效回执显示恢复入口,不另开会话。 +- **证据:**隔离的真实 Chat/Core/File/SQLite 测试覆盖有明确 owner 检查时采用原 + Task、检查缺失或失败时拒绝、历史保留、并发打开已发布 Session、响应丢失、原 + action 重放及身份变化。未改变的运行时兼容测试在不可变基线与候选均通过 106 + 项。presentation reducer 通过 27 项测试,56 组 base/head 向量保留所有非路由 + 字段。浏览器检查覆盖填充后的桌面/窄屏、reload、无效回执,以及一次重新连接 + 恢复原历史。 +- **可维护性:**Session 读回在既有 Chat Session 入口 owner 复用。Runtime + coordinator 因精确打开接口与早期身份门由 2,503 增至 2,524 行;reviewed ceiling 记录这一 + 有界增量,没有重复读回逻辑或新增执行管线。这不是延迟、默认闭包或完整成本资格。 +- **边界:**普通首消息及后续消息仍为普通只读 Chat。有明确检查的原 Task 使用 + 既有 Native owner;本次不自动提供可信检查器,也不自动采用每个回复。恢复证据 + 覆盖已发布 Session,不覆盖尚未记录的原生 thread-start 效果。真实原生尝试失败: + 当前配置的模型不受所选账号支持。合成成功与 account-read readiness 不能覆盖 + 该负面结果。完整 V1–V5/V10、模型/context 保留、D2/D5 闭包、渐进控制、可比 + 完整成本、R1/M3 及 C1 切换仍未通过资格验证。原十项要求保留,完成前仍需完整 + 原目标回归。 + +当前入口设计将原回复与消息输入保留在一起,重入沿记录的 Session,不选择另一条 +会话。下方桌面与窄屏参考图使用 packaged frontend、真实 SQLite/Chat owner 和 +合成回复,未验证的验收状态继续可见;它们说明展示边界,不构成模型或成果资格。 + +![桌面的原 Goal 会话](assets/goal-entry-original-session-desktop.webp) + +![窄屏的原 Goal 会话](assets/goal-entry-original-session-narrow.webp) diff --git a/examples/loopx-chat-actions-smoke.py b/examples/loopx-chat-actions-smoke.py index 63b921ef5e..f06ddc261f 100644 --- a/examples/loopx-chat-actions-smoke.py +++ b/examples/loopx-chat-actions-smoke.py @@ -105,25 +105,42 @@ def __init__(self, chat_store: ChatSessionStore) -> None: def open_session(self, **kwargs: object) -> tuple[dict[str, object], bool]: self.opened_sessions.append(dict(kwargs)) - existing = self.chat_store.latest_session( + managed_agent = kwargs.get("managed_agent_id") + channel = f"agent.{managed_agent}" if managed_agent is not None else str(kwargs["channel_id"]) + session_id = kwargs.get("session_id") + existing = self.chat_store.load_session(str(session_id)) if session_id is not None else self.chat_store.latest_session( goal_id=str(kwargs["goal_id"]), agent_id=str(kwargs["agent_id"]), - channel_id=str(kwargs["channel_id"]), + channel_id=channel, ) if existing is not None: return existing, True session = self.chat_store.create_session( goal_id=str(kwargs["goal_id"]), + goal_instance_id=kwargs.get("goal_instance_id"), + **({"session_id": str(session_id)} if session_id is not None else {}), + **({"managed_agent_id": str(managed_agent), "managed_workspace_path": str(Path(str(kwargs["work_dir"])).resolve())} + if managed_agent is not None else {}), agent_id=str(kwargs["agent_id"]), adapter_kind="fake", upstream_thread_id="thread-goal-create", - channel_id=str(kwargs["channel_id"]), + channel_id=channel, ) return session, False def submit_turn(self, **kwargs: object) -> tuple[dict[str, object], bool]: self.submissions.append(dict(kwargs)) - return ({"turn_id": "turn-correction-1", "status": "queued"}, True) + session_id = str(kwargs["session_id"]) + turn, created = self.chat_store.create_turn(session_id, + client_turn_id=str(kwargs["client_turn_id"]), message=str(kwargs["message"])) + if created: + # The synchronous fake finishes its ordinary reply through the real + # Chat completion owner; it never accepts a Goal or Task outcome. + self.chat_store.update_turn(session_id, str(turn["turn_id"]), + status="completing", started_at=turn["created_at"], completed_at=turn["created_at"], + upstream_turn_id=f"synthetic-{turn['turn_id']}", response={"message": "Synthetic ordinary reply."}) + turn = self.chat_store.finalize_managed_turn_completion(session_id, str(turn["turn_id"])) + return turn, created def capabilities(self) -> list[dict[str, object]]: return [ @@ -369,7 +386,8 @@ def assert_http_action_api(root: Path) -> None: ) assert code == 202, correction_applied assert correction_applied["proposal"]["status"] == "applied", correction_applied - assert correction_applied["turn"]["turn_id"] == "turn-correction-1", correction_applied + original_correction = chat_store.turn_for_client(session["session_id"], str(runtime_controller.submissions[1]["client_turn_id"])) + assert correction_applied["turn"]["turn_id"] == original_correction["turn_id"], correction_applied assert runtime_controller.submissions[1]["session_id"] == session["session_id"] goal_proposal = previews["goal.create"] diff --git a/loopx/canary/module_metric_baseline.json b/loopx/canary/module_metric_baseline.json index cc89abf093..3076b30f64 100644 --- a/loopx/canary/module_metric_baseline.json +++ b/loopx/canary/module_metric_baseline.json @@ -39,7 +39,7 @@ "loopx/chat_runtime.py": { "any_count": 38, "dict_any_count": 0, - "lines": 2503 + "lines": 2524 }, "loopx/chat_server.py": { "any_count": 25, diff --git a/loopx/chat/session_open.py b/loopx/chat/session_open.py index c61db67895..49c9b6d78f 100644 --- a/loopx/chat/session_open.py +++ b/loopx/chat/session_open.py @@ -20,15 +20,140 @@ from __future__ import annotations from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any, Mapping from ..chat_manager import open_manager_session +if TYPE_CHECKING: + from ..chat_action_store import ChatActionStore + from ..chat_runtime import ChatRuntimeController + from ..chat_store import ChatSessionStore + # The executor a Goal-scoped session runs on when the caller makes no explicit # pick. The steward channel does not use this: it resolves its own default. DEFAULT_GOAL_AGENT_ID = "codex" +def require_regular_session_paths(chat_store: ChatSessionStore, session_id: str) -> None: + """A redirected or incomplete reservation cannot identify an original.""" + directory, metadata = chat_store._session_dir(session_id), chat_store._session_path(session_id) + if (directory.is_symlink() or metadata.is_symlink() + or directory.exists() and not directory.is_dir() + or metadata.exists() and not metadata.is_file()): + raise ValueError("The original Session reservation is unavailable; restore its regular metadata") + + +def read_goal_creation_session( + action_store: ChatActionStore, + chat_store: ChatSessionStore | None, + *, + proposal_id: str, + session_id: str, + goal_id: str, + agent_id: str, + workspace: Path, + goal_instance_id: str | None, + expected_managed_agent: str | None = None, +) -> dict[str, Any]: + """Read the original metadata against the creation's fresh checkpoint.""" + from ..control_plane.collaboration import conversation_scope + + if chat_store is not None: + require_regular_session_paths(chat_store, session_id) + session = chat_store.load_session(session_id) if chat_store is not None else None + scope = conversation_scope(session) if session is not None else {} + if (session is None or session.get("session_id") != session_id or session.get("goal_id") != goal_id + or session.get("agent_id") != agent_id + or scope.get("goal_ids") != [goal_id] or scope.get("kind") != "owner_goal"): + raise ValueError("The original first Session is unavailable; restore it before retrying") + if expected_managed_agent is not None and session.get("managed_agent_id") != expected_managed_agent: + raise ValueError("The original registered Agent Session identity changed") + recorded_proposal = action_store.load(proposal_id) + if recorded_proposal is None: + raise ValueError("The original creation checkpoint is unavailable") + recorded = ((recorded_proposal.get("checkpoint") or {}).get("steps") or {}).get("first_session_opened") or {} + for field in ("channel_id", "managed_agent_id", "goal_instance_id"): + if field in recorded and recorded[field] != session.get(field): + raise ValueError("The original first Session route changed; restore its recorded identity") + if session.get("managed_agent_id") is not None and ( + session["managed_agent_id"] != agent_id + or session.get("goal_instance_id") != goal_instance_id + or session.get("managed_workspace_path") != str(workspace) + ): + raise ValueError("The original registered Agent Session identity changed") + return session + + +def recover_goal_creation_session( + chat_store: ChatSessionStore, + *, + client_turn_id: str, + goal_id: str, + agent_id: str, +) -> dict[str, Any] | None: + """Recover a unique published original, preferring its original client Turn.""" + from ..control_plane.collaboration import conversation_scope + + candidates = [] + for directory in chat_store.sessions_root.iterdir(): + if not directory.is_dir() and not directory.is_symlink(): + continue + require_regular_session_paths(chat_store, directory.name) + if not chat_store._session_path(directory.name).is_file(): + raise ValueError("The original Session reservation is unconfirmed; restore its metadata") + row = chat_store.load_session(directory.name) + if row is None or row.get("session_id") != directory.name: + raise ValueError("Original Session discovery is unreadable; restore it before retrying") + if (row.get("goal_id") == goal_id and row.get("agent_id") == agent_id + and conversation_scope(row).get("kind") == "owner_goal"): + candidates.append(row) + matches = [row for row in candidates if chat_store.turn_for_client(row["session_id"], client_turn_id) is not None] + if len(matches) > 1 or not matches and len(candidates) > 1: + raise ValueError("The original first Session is ambiguous; restore its recorded operation") + if matches: + return matches[0] + if candidates: + raise ValueError("The original first Session opening is unconfirmed; restore its exact checkpoint") + return None + + +def read_exact_original_session( + controller: ChatRuntimeController, + *, + session_id: str, + selected_scope: Mapping[str, object], + agent_id: str, + work_dir: Path, + requested_model: str | None = None, + requested_effort: str | None = None, +) -> dict[str, Any] | None: + """Read one exact opening under the caller's existing Session opening lock.""" + from ..capabilities.native_chat.steward_managed_mode import require_managed_agent_session + from ..chat_store import CHAT_SESSION_MODE_MANAGED, RESUMABLE_SESSION_STATES + from ..control_plane.collaboration import conversation_scope + + require_regular_session_paths(controller.store, session_id) + original = controller.store.load_session(session_id) + if original is not None: + if (original.get("session_id") != session_id + or original.get("goal_id") != selected_scope.get("goal_id") or original.get("agent_id") != agent_id + or original.get("executor_endpoint_id") != agent_id + or original.get("channel_id") != selected_scope.get("channel_id") + or original.get("managed_agent_id") != selected_scope.get("managed_agent_id") + or original.get("goal_instance_id") != selected_scope.get("goal_instance_id") + or original.get("session_mode") != CHAT_SESSION_MODE_MANAGED + or conversation_scope(original)["kind"] != "owner_goal" + or original.get("status") not in RESUMABLE_SESSION_STATES + or requested_model and original.get("agent_model_id") != requested_model + or requested_effort and original.get("agent_reasoning_effort") != requested_effort): + raise ValueError("the original Goal Session opening identity changed") + require_managed_agent_session(controller, original, work_dir) + return original + if controller.store._session_dir(session_id).exists(): + raise ValueError("the original Goal Session is unreadable; restore it before retrying") + return None + + def open_chat_session( *, controller: Any, diff --git a/loopx/chat_actions.py b/loopx/chat_actions.py index ecd46562ea..e0f2242094 100644 --- a/loopx/chat_actions.py +++ b/loopx/chat_actions.py @@ -668,7 +668,8 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None: ), None, ) - progress = effect_runtime_result("presentation.action_review_plan.compile", {"proposal": proposal}).get("creationProgress") or {} + creation_plan = effect_runtime_result("presentation.action_review_plan.compile", {"proposal": proposal}) + progress = creation_plan.get("creationProgress") or {} if (proposal.get("checkpoint") or {}).get("steps") and not progress: raise ValueError("Goal creation checkpoints do not match the original request; inspect the recorded operation") project, source_goal = self._project_for_goal_create(proposal, progress=progress) @@ -842,6 +843,14 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None: raise ValueError( "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 + + read_original_session = partial(read_goal_creation_session, + self.store, self.chat_store or getattr(self.runtime_controller, "store", None), + proposal_id=proposal_id, goal_id=goal_id, agent_id=agent_id, + workspace=project, goal_instance_id=projected.get("goal_instance_id")) + turn_result: dict[str, Any] | None = None session_id = "" first_turn_message = (f"/goal start --tokens {parameters['native_token_budget']} {objective}" @@ -850,22 +859,44 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None: f"首个 Todo:{';'.join(str(item) for item in (parameters.get('initial_todos') or [])[:3]) or '按目标边界建立首个可验证进展'}。" "然后直接推进并报告可验证结果;遇到权限边界时停止并提出明确 Gate。" )) + opening_session_id = _digest({"goal_create": proposal_id, "goal_id": goal_id})[:32] + expected_managed_agent = (creation_plan.get("creationSession") or {}).get("managedAgentId") + turn_store = self.chat_store or getattr(self.runtime_controller, "store", None) + if not progress.get("firstTurn") and not progress.get("sessionId") and turn_store is not None: + require_regular_session_paths(turn_store, opening_session_id) + original = turn_store.load_session(opening_session_id) + if original is not None: + read_original_session(session_id=opening_session_id, expected_managed_agent=expected_managed_agent) + elif turn_store._session_dir(opening_session_id).exists(): + raise ValueError("The original first Session is unreadable; restore it before retrying") + elif existing_goal is not None: + # Historical opening responses carried no operation-bound id. + # Recover only an unambiguous original; never choose latest. + original = recover_goal_creation_session(turn_store, + client_turn_id=f"goal-start-{proposal_id}", goal_id=goal_id, agent_id=agent_id) + if original is not None: + read_original_session(session_id=original["session_id"]) + progress = {**progress, "sessionId": original["session_id"]} if progress.get("firstTurn"): session_id = progress["firstTurn"]["sessionId"] turn_id = progress["firstTurn"]["turnId"] turn_store = self.chat_store or getattr(self.runtime_controller, "store", None) - session = turn_store.load_session(session_id) if turn_store is not None else None - turn = turn_store.load_turn(session_id, turn_id) if session is not None else None - if session is None or session.get("goal_id") != goal_id or session.get("agent_id") != agent_id or turn is None: + session = read_original_session(session_id=session_id) + turn = turn_store.load_turn(session_id, turn_id) if turn_store is not None else None + if turn is None: raise ValueError("The recorded first Turn is unavailable; restore its original Session instead of starting another") + if (turn.get("message") != first_turn_message + or turn.get("client_turn_id") != f"goal-start-{proposal_id}"): + raise ValueError("The original first Turn request changed; retain its recorded operation") require_first_turn_readback(turn) turn_result = {"turn_id": turn_id, "status": str(turn["status"]), "created": False} elif progress.get("sessionId"): turn_store = self.chat_store or getattr(self.runtime_controller, "store", None) if turn_store is None: raise ValueError("The original first Session is unavailable; restore it before retrying") + original_session = read_original_session(session_id=progress["sessionId"]) session, turn = self._read_task_start( - turn_store, goal_id=goal_id, agent_id=agent_id, channel_id=f"goal.{goal_id}", + turn_store, goal_id=goal_id, agent_id=agent_id, channel_id=original_session["channel_id"], client_turn_id=f"goal-start-{proposal_id}", checkpoint={"session_id": progress["sessionId"]}, ) if turn is not None: @@ -924,9 +955,7 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None: } if agent_id and self.runtime_controller is not None and first_turn_gate is None and turn_result is None: if progress.get("sessionId"): - session = self.runtime_controller.store.load_session(progress["sessionId"]) - if session is None or session.get("goal_id") != goal_id or session.get("agent_id") != agent_id: - raise ValueError("The original first Session is unavailable; restore it before retrying") + session = read_original_session(session_id=progress["sessionId"]) else: session, _resumed = self.runtime_controller.open_session( goal_id=goal_id, @@ -938,13 +967,24 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None: agent_id=agent_id, work_dir=project, objective=objective, - mode="resume_latest", + mode="new", + session_id=opening_session_id, channel_id=f"goal.{goal_id}", agent_goal_id=goal_id, + **({"managed_agent_id": creation_plan["creationSession"]["managedAgentId"]} + if creation_plan.get("creationSession") else {}), ) session_id = _opaque(session.get("session_id"), field="session_id") + if not progress.get("sessionId") and session_id != opening_session_id: + raise ValueError("The original first Session opening returned another operation") + session = read_original_session(session_id=session_id, + expected_managed_agent=expected_managed_agent if not progress.get("sessionId") else None) self.store.save_checkpoint(proposal_id, step="first_session_opened", - receipt={"outcome": "first_session_opened", "session_id": session_id}) + receipt={"outcome": "first_session_opened", "session_id": session_id, + "channel_id": session["channel_id"], + **({"managed_agent_id": session["managed_agent_id"], + "goal_instance_id": session.get("goal_instance_id")} + if session.get("managed_agent_id") is not None else {})}) first_turn, created = self.runtime_controller.submit_turn( session_id=session_id, client_turn_id=f"goal-start-{proposal_id}", @@ -973,6 +1013,8 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None: step="first_turn_gated", receipt={"outcome": "first_turn_gated", "gate": first_turn_gate}, ) + if session_id: + session = read_original_session(session_id=session_id) child_gate: dict[str, Any] | None = first_turn_gate if heartbeat.get("enabled") is True: heartbeat_parameters = { @@ -1016,6 +1058,9 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None: **({"agent_id": agent_id} if agent_id else {}), **({"todo_ids": todo_ids} if todo_ids else {}), **({"session_id": session_id} if session_id else {}), + **({"managed_agent_id": session["managed_agent_id"], "channel_id": session["channel_id"], + "goal_instance_id": session.get("goal_instance_id")} + if session_id and session.get("managed_agent_id") is not None else {}), **({"turn_id": turn_result["turn_id"]} if turn_result else {}), }, **({"child_gate": child_gate} if child_gate else {}), diff --git a/loopx/chat_runtime.py b/loopx/chat_runtime.py index c018072005..37f27d424a 100644 --- a/loopx/chat_runtime.py +++ b/loopx/chat_runtime.py @@ -24,6 +24,7 @@ steward_machine_defaults, ) from .chat.coordination import PROJECT_COORDINATION_GUIDANCE, PROJECT_CONTEXT_VERSION, apply_context_handoff +from .chat.session_open import read_exact_original_session from .capabilities.native_chat import codex_context, project_context as project_context_policy from .capabilities.native_chat.codex_adapter import ( CodexAppServerAdapter, NativeHistoryRestoration, NativeWorkingContinuation, start_attachment_turn, @@ -59,6 +60,7 @@ from .file_lock import ( LOCK_HOLDER_DEAD, LOCK_HOLDER_LIVE, LOCK_HOLDER_RELEASED, _lock_id, lock_holder_host_label, lock_holder_liveness, process_is_alive, try_exclusive_file_lock, + exclusive_cross_runtime_file_lock, ) from .kiro_cli_goal_mode import ( KIRO_CLI_BIN, @@ -521,6 +523,7 @@ def open_session( agent_goal_id: str | None = None, goal_instance_id: str | None = None, managed_agent_id: str | None = None, + session_id: str | None = None, manager_executor_allocation: Mapping[str, Any] | None = None, project_ref: str | None = None, conversation_binding_id: str | None = None, @@ -541,6 +544,8 @@ def open_session( error_code="unsupported_configuration", gate=None) if mode not in {"resume_latest", "new"}: raise ValueError("mode must be resume_latest or new") + if session_id is not None and mode != "new": + raise ValueError("an exact Session opening requires mode=new") selected_channel = channel_id or f"goal.{goal_id}" project_context = None steward_context = None @@ -593,9 +598,24 @@ def open_session( goal_id = MANAGER_AGENT_GOAL_ID route_goal_id = "*" if is_manager_channel(selected_channel) else goal_id route_key = (route_goal_id, agent_id, selected_channel) + if session_id is not None: + if not isinstance(session_id, str) or session_id != session_id.strip() or session_id in {".", ".."}: + raise ValueError("session_id must retain its exact non-empty opaque identity") + session_id = _opaque_id(session_id, field="session_id") + if (project_context is not None or steward_context is not None or is_manager_channel(selected_channel) + or goal_id is None or agent_goal_id is not None and agent_goal_id != goal_id + or conversation_scope(selected_scope)["kind"] != "owner_goal"): + raise ValueError("an exact Session opening requires its original local Goal route") with self.lock: route_lock = self.session_open_locks.setdefault(route_key, threading.Lock()) - with route_lock: + with route_lock, (exclusive_cross_runtime_file_lock( + self.store.root / "session-open-locks" / session_id, operation="open_original_goal_session") + if session_id is not None else nullcontext()): + if session_id is not None: + original = read_exact_original_session(self, session_id=session_id, selected_scope=selected_scope, + agent_id=agent_id, work_dir=work_dir, requested_model=agent_model_id, requested_effort=agent_reasoning_effort) + if original is not None: + return original, True latest = None if not is_manager_channel(selected_channel) and project_context is None: exact_attached, strict_profile = select_current_attached_session( @@ -618,7 +638,7 @@ def open_session( error_code="source_session_managed_chat_unsupported", gate=None, ) - if mode == "resume_latest": + if mode == "resume_latest" and session_id is None: latest = self.store.latest_session( goal_id=None if is_manager_channel(selected_channel) else goal_id, agent_id=agent_id, @@ -686,6 +706,7 @@ def open_session( require_managed_agent_session(self, selected_scope, work_dir) observed_settings = self._observed_model_settings(adapter, agent_reasoning_effort, agent_model_id) persisted = self.store.create_session( + **({"session_id": session_id} if session_id is not None else {}), goal_id=goal_id, goal_instance_id=goal_instance_id, **({"managed_agent_id": managed_agent_id, "managed_workspace_path": str(work_dir.resolve())} if managed_agent_id is not None else {}), diff --git a/loopx/control_plane/presentation/action_review_plan.ts b/loopx/control_plane/presentation/action_review_plan.ts index ec6059c58c..7dad7a4548 100644 --- a/loopx/control_plane/presentation/action_review_plan.ts +++ b/loopx/control_plane/presentation/action_review_plan.ts @@ -96,6 +96,9 @@ export type ActionReviewPlan = ActionReviewIdentity & ActionReviewState & { /** Recorded creation effects, not evidence of a completed Goal or model Turn. */ creationProgress?: GoalCreationProgress; creationOutcome?: GoalCreationOutcome; + /** New Session routing only. Recorded Sessions recover through creationProgress; + * this identity decision does not certify Task acceptance or execution. */ + creationSession?: {managedAgentId: string}; /** Accepted dispatch bound to its original Turn. It does not establish a result. */ taskExecution?: { goalId: string; todoId: string; sessionId: string; turnId: string }; }; @@ -541,12 +544,25 @@ export function compileActionReviewPlan(proposalValue: unknown, nowMs?: number): const operationFrame = compileOperationReviewFrame(proposal, nowMs); const reviewCardFrame = compileReviewCardFrame(proposal); const decisionFrame = compileDecisionReviewFrame(proposal); + const parameters = objectValue(proposal.normalized_parameters); const creationProgress = goalCreationProgress(proposal); // Older already-dispatched creations retain their original semantics. A // failed write retries its original CAS even after a response was lost. const creationOutcome = creationProgress?.todoIds && (!creationProgress.sessionId && !creationProgress.firstTurn || creationProgress.completionBasis) - ? goalCreationOutcome(identity.proposalId, objectValue(proposal.normalized_parameters) ?? {}, creationProgress.todoIds) : undefined; + ? goalCreationOutcome(identity.proposalId, parameters ?? {}, creationProgress.todoIds) : undefined; + const creationSteps = objectValue(objectValue(proposal.checkpoint)?.steps); + // A persisted Session/Turn, including a malformed checkpoint, always owns + // recovery. Never infer a new managed identity from its old creation fields. + const creationSession = proposal.action_kind === "goal.create" && parameters?.agent_id === "codex" + && parameters.native_token_budget == null && proposal.status !== "applied" + && !creationProgress?.sessionId && !creationProgress?.firstTurn + && !Object.hasOwn(proposal, "first_turn_readback") + && (proposal.checkpoint == null || creationSteps !== null + && (Object.keys(creationSteps).length === 0 || creationProgress !== undefined)) + && !Object.hasOwn(creationSteps ?? {}, "first_session_opened") + && !Object.hasOwn(creationSteps ?? {}, "first_turn_started") + ? {managedAgentId: "codex"} : undefined; const finish = (state: ActionReviewState): ActionReviewPlan => ({ ...identity, ...state, @@ -555,6 +571,7 @@ export function compileActionReviewPlan(proposalValue: unknown, nowMs?: number): ...(decisionFrame ? { decisionFrame } : {}), ...(creationProgress ? { creationProgress } : {}), ...(creationOutcome ? { creationOutcome } : {}), + ...(creationSession ? { creationSession } : {}), }); const held = ( interaction: "gated" | "refresh" | "repair" | "pending" | "completed" | "inactive", @@ -589,7 +606,6 @@ export function compileActionReviewPlan(proposalValue: unknown, nowMs?: number): return taskExecution ? {...completed, taskExecution} : completed; } const basis = objectValue(proposal.canonical_update_basis); - const parameters = objectValue(proposal.normalized_parameters); // Recovery keeps the frozen workspace and committed effects. The server // revalidates their identity and reuses native Todo/Turn idempotency owners. if (proposal.action_kind === "goal.create" && ["failed", "applying"].includes(String(proposal.status)) diff --git a/tests/control_plane/test_goal_create_completion.py b/tests/control_plane/test_goal_create_completion.py index 0b0642a022..d105a7dbe8 100644 --- a/tests/control_plane/test_goal_create_completion.py +++ b/tests/control_plane/test_goal_create_completion.py @@ -254,6 +254,12 @@ def assert_retained_then_submit(*args, **kwargs): status, recovered = request(f"/api/actions/{proposal['proposal_id']}/apply", {}) assert status == 202, recovered ids = recovered["proposal"]["receipt"]["resource_ids"] + original_session = chat.load_session(ids["session_id"]) + assert original_session["managed_agent_id"] == "codex" + assert original_session["channel_id"] == "agent.codex" + assert ids["managed_agent_id"] == original_session["managed_agent_id"] + assert ids["channel_id"] == original_session["channel_id"] + assert ids["goal_instance_id"] == original_session.get("goal_instance_id") if confirmed is not None: assert ids["session_id"] == sid and ids["turn_id"] == confirmed["turn_id"] assert admission_calls == [], "confirmed first work is readback, not a new admission" diff --git a/tests/control_plane/test_goal_create_session.py b/tests/control_plane/test_goal_create_session.py new file mode 100644 index 0000000000..c2fd0573cc --- /dev/null +++ b/tests/control_plane/test_goal_create_session.py @@ -0,0 +1,364 @@ +"""Goal creation reaches its original Agent conversation and Task owners. + +The Chat/Core/providers are real; the app-server/model is synthetic. Explicit +owner checks below qualify the integration, not automatic checker production. +""" +import hashlib +import json +import runpy +import sys +from pathlib import Path + +import pytest + +from test_new_goal_storage_defaults import environment as environment, app as app +from test_goal_create_completion import preview_goal, inspect +from loopx.chat_runtime import ChatRuntimeController +from loopx.chat_store import ChatSessionStore +from loopx.capabilities.native_chat.project_context import ChatProjectContexts +from loopx.capabilities.native_chat.steward_managed_mode import ManagedSessionTurn +from loopx.control_plane.coordination.local_authority import read_canonical_todos_if_promoted + + +@pytest.fixture +def host(environment, app): + _, _, _, project, runtime = environment + actions, request, service = app + capture, binary = runtime / "requests.jsonl", runtime / "synthetic-codex" + source = runpy.run_path(str(Path(__file__).parents[2] / "examples/loopx-chat-runtime-smoke.py"))["FAKE_CODEX"] + binary.write_text(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")')) + binary.chmod(0o700) + chat = ChatSessionStore(runtime / "chat") + controller = ChatRuntimeController(store=chat, codex_bin=str(binary), registry_path=service.registry_path, + project_contexts=ChatProjectContexts([project])) + service.chat_store, service.runtime_controller = chat, controller + try: + yield actions, request, controller, capture, project, runtime + finally: + controller.close() + + +def create(host): + _, request, controller, *_ = host + proposal = preview_goal(request) + status, result = request(f"/api/actions/{proposal['proposal_id']}/apply", {}) + assert status == 202, result + ids = result["proposal"]["receipt"]["resource_ids"] + first = controller.wait_for_turn(session_id=ids["session_id"], turn_id=ids["turn_id"], timeout_sec=10) + assert first["status"] == "completed", first + return proposal, ids, first + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_first_goal_retains_ordinary_messages_in_the_registered_session(environment, host, provider): + configure, *_ = environment + configure(provider) + _, request, controller, capture, project, runtime = host + proposal, ids, first = create(host) + chat, sid = controller.store, ids["session_id"] + original = chat.load_session(sid) + assert original["channel_id"] == "agent.codex" and original["managed_agent_id"] == "codex" + assert original["managed_workspace_path"] == str(project) + assert first.get("loopx_execution") is not True and "native_loopx" not in first["response"] + assert controller.adapters[sid].session.sandbox == "read-only" + history = chat.messages(sid) + followup, created = controller.submit_turn(session_id=sid, client_turn_id="original-followup", + message="Retain the introduction while preparing the appendix.", work_dir=project, objective="Deliver the report.") + assert created + completed = controller.wait_for_turn(session_id=sid, turn_id=followup["turn_id"], timeout_sec=10) + assert completed["status"] == "completed" and "native_loopx" not in completed["response"] + assert chat.messages(sid)[:len(history)] == history + assert chat.load_session(sid)["upstream_thread_id"] == original["upstream_thread_id"] + calls = [json.loads(line) for line in capture.read_text().splitlines()] + assert sum(row["method"] == "thread/start" for row in calls) == 1 + assert sum(row["method"] == "turn/start" for row in calls) == 2 + before_replay = capture.read_bytes() + status, replay = request(f"/api/actions/{proposal['proposal_id']}/apply", {}) + assert status == 202 and replay["proposal"]["receipt"]["resource_ids"] == ids + assert capture.read_bytes() == before_replay and len(chat.list_sessions(goal_id="report")) == 1 + authority = read_canonical_todos_if_promoted(runtime_root=runtime, goal_id="report", include_leases=True) + assert [(todo["todo_id"], todo["status"]) for todo in authority["todos"]] == [(ids["todo_ids"][0], "open")] + assert inspect(project, runtime)["goal_acceptance_contract"]["outcome_requirements"]["outcomes"][0]["requirements"][0]["status"] == "unverified" + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("window", ["simple", "competing", "historical", "historical_competing", "historical_missing_metadata"]) +def test_lost_session_open_response_reuses_the_original_registered_route(environment, host, monkeypatch, provider, window): + configure, *_ = environment + configure(provider) + actions, request, controller, capture, *_ = host + proposal = preview_goal(request) + open_session = controller.open_session + opening = {} + def lost_response(**kwargs): + if window.startswith("historical"): + kwargs.pop("managed_agent_id", None) + kwargs.pop("session_id", None) + session, _ = open_session(**kwargs) + opening.update(session=session, arguments=kwargs) + raise TimeoutError("Session opening response lost before the checkpoint") + monkeypatch.setattr(controller, "open_session", lost_response) + path = f"/api/actions/{proposal['proposal_id']}/apply" + assert request(path, {})[0] == 424 + sid = controller.store.list_sessions(goal_id="report")[0]["session_id"] + assert "first_session_opened" not in actions.load(proposal["proposal_id"])["checkpoint"]["steps"] + monkeypatch.setattr(controller, "open_session", open_session) + if window == "historical_missing_metadata": + path_to_metadata = controller.store._session_path(sid) + path_to_metadata.rename(path_to_metadata.with_suffix(".saved")) + if window.endswith("competing"): + arguments = {**opening["arguments"], "mode": "new"} + arguments.pop("session_id", None) + other, _ = open_session(**arguments) + assert other["session_id"] != sid + status, recovered = request(path, {}) + if window.startswith("historical"): + assert status == 400 and ("ambiguous" if window == "historical_competing" else "unconfirmed") in recovered["error"], recovered + assert controller.store.turn_for_client(sid, f"goal-start-{proposal['proposal_id']}") is None + return + assert status == 202, recovered + ids = recovered["proposal"]["receipt"]["resource_ids"] + assert ids["session_id"] == sid + assert ("managed_agent_id" in ids) is not window.startswith("historical") + assert controller.wait_for_turn(session_id=sid, turn_id=ids["turn_id"], timeout_sec=10)["status"] == "completed" + assert len(controller.store.list_sessions(goal_id="report")) == (2 if window == "competing" else 1) + calls = [json.loads(line) for line in capture.read_text().splitlines()] + assert sum(row["method"] == "thread/start" for row in calls) == (2 if window == "competing" else 1) + assert sum(row["method"] == "turn/start" for row in calls) == 1 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_new_open_checks_the_persisted_session_before_certifying_its_route(environment, host, monkeypatch, provider): + configure, *_ = environment + configure(provider) + actions, request, controller, capture, *_ = host + proposal = preview_goal(request) + open_session = controller.open_session + original = {} + def changed_before_response(**kwargs): + session, resumed = open_session(**kwargs) + original.update(session) + stored = {**session, "channel_id": "goal.report", "managed_agent_id": None} + stored.pop("managed_workspace_path", None) + controller.store._session_path(session["session_id"]).write_text(json.dumps(stored)) + return session, resumed + monkeypatch.setattr(controller, "open_session", changed_before_response) + status, failed = request(f"/api/actions/{proposal['proposal_id']}/apply", {}) + assert status == 400 and "Session identity changed" in failed["error"], failed + assert "first_session_opened" not in actions.load(proposal["proposal_id"])["checkpoint"]["steps"] + assert controller.store.turn_for_client(original["session_id"], f"goal-start-{proposal['proposal_id']}") is None + calls = [json.loads(line) for line in capture.read_text().splitlines()] + assert not [row for row in calls if row["method"] == "turn/start"] + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_explicit_native_budget_retains_the_legacy_goal_channel(environment, host, monkeypatch, provider): + configure, *_ = environment + configure(provider) + actions, request, controller, capture, *_ = host + proposal = preview_goal(request, native_token_budget=100) + save = actions.save_checkpoint + def interrupt(*args, **kwargs): + result = save(*args, **kwargs) + if kwargs.get("step") == "first_session_opened": + raise OSError("Stop the synthetic host before its explicit /goal request") + return result + monkeypatch.setattr(actions, "save_checkpoint", interrupt) + status, result = request(f"/api/actions/{proposal['proposal_id']}/apply", {}) + assert status == 424, result + sid = actions.load(proposal["proposal_id"])["checkpoint"]["steps"]["first_session_opened"]["session_id"] + session = controller.store.load_session(sid) + assert session["channel_id"] == "goal.report" and session.get("managed_agent_id") is None + assert controller.store.turn_for_client(sid, f"goal-start-{proposal['proposal_id']}") is None + assert not [json.loads(line) for line in capture.read_text().splitlines() if json.loads(line)["method"] == "turn/start"] + + +def test_concurrent_session_opening_reuses_one_published_identity_and_no_new_adapter_on_replay(host): + from concurrent.futures import ThreadPoolExecutor + + _, _, controller, capture, project, _ = host + create(host) + secondary = ChatRuntimeController(store=controller.store, codex_bin=controller.codex_bin, + registry_path=controller.registry_path, project_contexts=ChatProjectContexts([project])) + arguments = dict(goal_id="report", agent_id="codex", managed_agent_id="codex", + work_dir=project, objective="Deliver the report.", mode="new", session_id="concurrent-original") + before = capture.read_bytes() + try: + with ThreadPoolExecutor(max_workers=2) as workers: + opened = list(workers.map(lambda runtime: runtime.open_session(**arguments), [controller, secondary])) + assert [row[0]["session_id"] for row in opened] == ["concurrent-original", "concurrent-original"] + assert sorted(row[1] for row in opened) == [False, True] + assert opened[0][0] == opened[1][0] + calls = [json.loads(line) for line in capture.read_bytes()[len(before):].splitlines()] + assert sum(row["method"] == "thread/start" for row in calls) == 1 + before_replay = capture.read_bytes() + original = controller.store.load_session("concurrent-original") + result, resumed = secondary.open_session(**arguments) + assert resumed and result == original and capture.read_bytes() == before_replay + finally: + secondary.close() + + +@pytest.mark.parametrize("reservation", ["directory", "dangling-link", "metadata-link"]) +def test_unknown_physical_session_reservation_never_starts_another_native_thread(host, reservation): + _, _, controller, capture, project, _ = host + create(host) + directory = controller.store._session_dir("unknown-opening") + if reservation == "directory": + directory.mkdir() + elif reservation == "dangling-link": + directory.symlink_to(directory.parent / "missing-target", target_is_directory=True) + else: + directory.mkdir() + controller.store._session_path("unknown-opening").symlink_to(directory.parent / "missing-metadata.json") + before = capture.read_bytes() + with pytest.raises(ValueError, match="unreadable|unavailable"): + controller.open_session(goal_id="report", agent_id="codex", managed_agent_id="codex", + work_dir=project, objective="Deliver the report.", mode="new", session_id="unknown-opening") + assert capture.read_bytes() == before + + +def test_exact_session_opening_cannot_select_the_resume_latest_branch(host): + _, _, controller, capture, project, _ = host + create(host) + before = capture.read_bytes() + with pytest.raises(ValueError, match="mode=new"): + controller.open_session(goal_id="report", agent_id="codex", managed_agent_id="codex", + work_dir=project, objective="Deliver the report.", mode="resume_latest", session_id="another-opening") + assert capture.read_bytes() == before + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("legacy", [False, True], ids=["registered", "historical-legacy"]) +def test_interrupted_first_session_recovers_its_recorded_route(environment, host, monkeypatch, provider, legacy): + configure, *_ = environment + configure(provider) + actions, request, controller, capture, *_ = host + proposal = preview_goal(request) + save, open_session = actions.save_checkpoint, controller.open_session + if legacy: + def old_open(**kwargs): + # Stop today's producer before opening, then restore a checkpoint + # genuinely written by the historical unbound Session producer. + raise OSError("Restore the original historical Session checkpoint") + monkeypatch.setattr(controller, "open_session", old_open) + def interrupt(*args, **kwargs): + result = save(*args, **kwargs) + if kwargs.get("step") == "first_session_opened": + raise OSError("Interrupted before dispatch") + return result + monkeypatch.setattr(actions, "save_checkpoint", interrupt) + path = f"/api/actions/{proposal['proposal_id']}/apply" + assert request(path, {})[0] == 424 + if legacy: + project = host[4] + session, _ = open_session(goal_id="report", agent_id="codex", work_dir=project, + objective="Deliver the report.", mode="new", channel_id="goal.report", agent_goal_id="report") + save(proposal["proposal_id"], step="first_session_opened", + receipt={"outcome": "first_session_opened", "session_id": session["session_id"]}) + recorded = actions.load(proposal["proposal_id"])["checkpoint"]["steps"]["first_session_opened"] + sid = recorded["session_id"] + original = controller.store.load_session(sid) + assert original["channel_id"] == ("goal.report" if legacy else "agent.codex") + monkeypatch.setattr(actions, "save_checkpoint", save) + monkeypatch.setattr(controller, "open_session", open_session) + status, resumed = request(path, {}) + assert status == 202, resumed + ids = resumed["proposal"]["receipt"]["resource_ids"] + assert ids["session_id"] == sid + turn = controller.wait_for_turn(session_id=sid, turn_id=ids["turn_id"], timeout_sec=10) + assert turn["status"] == "completed" + assert ("managed_agent_id" in ids) is not legacy + assert controller.store.load_session(sid)["channel_id"] == original["channel_id"] + calls = [json.loads(line) for line in capture.read_text().splitlines()] + assert sum(row["method"] == "thread/start" for row in calls) == 1 + assert sum(row["method"] == "turn/start" for row in calls) == 1 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("field,value", [("channel_id", "goal.report"), ("managed_agent_id", "other-owner"), + ("goal_instance_id", "replaced-lifetime"), ("managed_workspace_path", "/unavailable-workspace")]) +def test_recovery_refuses_a_changed_original_session_route(environment, host, monkeypatch, provider, field, value): + configure, *_ = environment + configure(provider) + actions, request, controller, capture, *_ = host + proposal = preview_goal(request) + save = actions.save_checkpoint + def interrupt(*args, **kwargs): + result = save(*args, **kwargs) + if kwargs.get("step") == "first_session_opened": + raise OSError("Interrupted before dispatch") + return result + monkeypatch.setattr(actions, "save_checkpoint", interrupt) + path = f"/api/actions/{proposal['proposal_id']}/apply" + assert request(path, {})[0] == 424 + monkeypatch.setattr(actions, "save_checkpoint", save) + sid = actions.load(proposal["proposal_id"])["checkpoint"]["steps"]["first_session_opened"]["session_id"] + session = controller.store.load_session(sid) + controller.store._session_path(sid).write_text(json.dumps({**session, field: value})) + before = capture.read_bytes() + status, failed = request(path, {}) + assert status == 400, failed + assert "Session" in failed["error"] + assert capture.read_bytes() == before and len(controller.store.list_sessions(goal_id="report")) == 1 + assert controller.store.turn_for_client(sid, f"goal-start-{proposal['proposal_id']}") is None + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("checks", ["valid", "missing", "failed"]) +def test_created_session_adopts_original_task_only_with_independent_owner_check(environment, host, provider, checks): + from loopx.control_plane.goals.acceptance import configure_goal_acceptance + + configure, *_ = environment + configure(provider) + _, _, controller, capture, project, runtime = host + _, ids, _ = create(host) + sid, todo = ids["session_id"], ids["todo_ids"][0] + original = controller.store.load_session(sid) + history = controller.store.messages(sid) + artifact, checker = project / "report.txt", project / "check-report.py" + expected = "Introduction\nAppendix\n" + checker.write_text("from pathlib import Path\nassert Path('report.txt').read_text() == 'Introduction\\nAppendix\\n'\n") + if checks != "missing": + basis = inspect(project, runtime) + configure_goal_acceptance(registry_path=controller.registry_path, runtime_root=str(runtime), goal_id="report", + expected_provider_revision=basis["provider_revision"], execute=True, + document={"scope": {"kind": "selected_work", "todo_ids": [todo]}, "objective": "Deliver both report sections", + "non_goals": [], "criteria": [{"id": "complete-report", "description": "Both approved sections are present", + "validation_argv": [sys.executable, "check-report.py"], "validation_timeout_seconds": 5, + "validation_files": [{"path": "check-report.py", "sha256": hashlib.sha256(checker.read_bytes()).hexdigest()}]}], + "bindings": [{"todo_id": todo, "criterion_ids": ["complete-report"]}]}) + candidate = {"result_kind": "validated_completion", "classification": "implementation", + "summary": "The report includes both sections.", "next_action": "Read back the original report.", + "delivery_batch_scale": "implementation", "delivery_outcome": "outcome_progress", + "vision_unchanged_reason": "The original approved report remains the current task.", + "work_evidence": ["report.txt"], "validation_evidence": ["The independent checker reads both original sections"]} + binary = Path(controller.codex_bin) + source = binary.read_text().replace('"message": "Runtime response."', '"message": ' + repr(json.dumps(candidate))) + artifact_content = expected if checks != "failed" else "Introduction\n" + source = source.replace(' turn_count += 1', + f' open({str(artifact)!r}, "w").write({artifact_content!r})\n turn_count += 1') + binary.write_text(source) + controller.adapters.pop(sid).close_session() + before = capture.read_bytes() + native = ManagedSessionTurn(controller) + accepted, created = native.submit(sid, agent_id="codex", operation_id="original-task", todo_id=todo) + assert created + completed = controller.wait_for_turn(session_id=sid, turn_id=accepted["turn_id"], timeout_sec=15) + result = completed["response"]["native_loopx"] + assert result["status"] == {"valid": "committed", "missing": "stopped", "failed": "failed"}[checks], result + assert result["effects"]["quota_spent"] is (checks == "valid") + assert result["effects"]["state_written"] is (checks == "valid") + authority = read_canonical_todos_if_promoted(runtime_root=runtime, goal_id="report", include_leases=True) + assert next(row for row in authority["todos"] if row["todo_id"] == todo)["status"] == ("done" if checks == "valid" else "open") + calls = [json.loads(line) for line in capture.read_bytes()[len(before):].splitlines()] + assert sum(row["method"] == "turn/start" for row in calls) == (0 if checks == "missing" else 1) + assert not [row for row in calls if row["method"] == "thread/start"] + assert controller.store.messages(sid)[:len(history)] == history + assert controller.store.load_session(sid)["upstream_thread_id"] == original["upstream_thread_id"] + assert len(controller.store.list_sessions(goal_id="report")) == 1 + after = capture.read_bytes() + replay, created = native.submit(sid, agent_id="codex", operation_id="original-task", todo_id=todo) + assert not created and replay["turn_id"] == accepted["turn_id"] and capture.read_bytes() == after diff --git a/tests/control_plane_ts/action_review_plan_session.test.ts b/tests/control_plane_ts/action_review_plan_session.test.ts new file mode 100644 index 0000000000..6691ce9110 --- /dev/null +++ b/tests/control_plane_ts/action_review_plan_session.test.ts @@ -0,0 +1,99 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import {compileActionReviewPlan} from "../../loopx/control_plane/presentation/action_review_plan.ts"; + +const proposal = {proposal_id: "new-goal", expected_state_fingerprint: "reviewed-source", + action_kind: "goal.create", permission_classification: "durable_write", status: "preview_ready", + normalized_parameters: {goal_id: "new-goal", title: "New Goal", agent_id: "codex", + initial_todos: ["Deliver the original requested work"]}}; +const steps = {workspace_validated: {outcome: "workspace_validated", workspace_digest: "a".repeat(64)}, + goal_bootstrapped: {outcome: "goal_bootstrapped", goal_id: "new-goal"}, + agent_bound: {outcome: "agent_bound", goal_id: "new-goal", agent_id: "codex"}, + todos_created: {outcome: "todos_created", todo_ids: ["todo-original"]}}; + +test("a new default Codex Goal chooses managed Agent routing before its first Session", () => { + for (const checkpoint of [undefined, null, {steps: {}}, {steps}]) { + const plan = compileActionReviewPlan({...proposal, checkpoint}); + assert.deepEqual(plan.creationSession, {managedAgentId: "codex"}); + assert.equal(plan.canApply, true); + assert.equal(plan.creationProgress?.sessionId, undefined); + assert.equal(plan.creationProgress?.firstTurn, undefined); + } + assert.deepEqual(compileActionReviewPlan({...proposal, normalized_parameters: { + ...proposal.normalized_parameters, native_token_budget: null}}).creationSession, {managedAgentId: "codex"}); +}); + +test("explicit budgets and other endpoints preserve the legacy first Session route", () => { + // Invalid explicit budget shapes are rejected upstream; a pure projection + // must not turn them into a managed default through truthiness. + for (const native_token_budget of [1, 10000, 0, false, "", "10000", {}, []]) { + assert.equal(Object.hasOwn(compileActionReviewPlan({...proposal, normalized_parameters: { + ...proposal.normalized_parameters, native_token_budget}}), "creationSession"), false); + } + for (const agent_id of ["antigravity", "claude-code", "other-codex", "codex@worker", " codex ", "", null, undefined]) { + assert.equal(Object.hasOwn(compileActionReviewPlan({...proposal, normalized_parameters: { + ...proposal.normalized_parameters, agent_id}}), "creationSession"), false); + } + assert.equal(compileActionReviewPlan({...proposal, action_kind: "todo.create"}).creationSession, undefined); +}); + +test("bootstrap retry chooses a new route only while no Session has been recorded", () => { + for (const status of ["failed", "applying"]) { + const plan = compileActionReviewPlan({...proposal, status, checkpoint: {steps}}); + assert.equal(plan.retryOriginal, true); + assert.deepEqual(plan.creationSession, {managedAgentId: "codex"}); + assert.deepEqual(plan.creationProgress?.todoIds, ["todo-original"]); + } +}); + +test("recorded legacy Session and first Turn retain their original recovery identity", () => { + const first_session_opened = {outcome: "first_session_opened", session_id: "original-session"}; + const first_turn_started = {outcome: "first_turn_started", session_id: "original-session", turn_id: "original-turn"}; + for (const recorded of [{first_session_opened}, {first_turn_started}, {first_session_opened, first_turn_started}]) { + const plan = compileActionReviewPlan({...proposal, status: "failed", checkpoint: {steps: {...steps, ...recorded}}}); + assert.equal(plan.retryOriginal, true); + assert.equal(Object.hasOwn(plan, "creationSession"), false); + if ("first_session_opened" in recorded) assert.equal(plan.creationProgress?.sessionId, "original-session"); + if ("first_turn_started" in recorded) + assert.deepEqual(plan.creationProgress?.firstTurn, {sessionId: "original-session", turnId: "original-turn"}); + } +}); + +test("malformed recorded checkpoints cannot be treated as a new default Session", () => { + for (const value of [undefined, null, false, [], {}, {session_id: "original-session"}]) { + for (const field of ["first_session_opened", "first_turn_started"]) { + const plan = compileActionReviewPlan({...proposal, status: "failed", checkpoint: {steps: {...steps, [field]: value}}}); + assert.equal(Object.hasOwn(plan, "creationSession"), false); + } + } + for (const checkpoint of [[], false, {}, {steps: null}, {steps: []}, + {steps: {...steps, goal_bootstrapped: {...steps.goal_bootstrapped, goal_id: "other"}}}, + {steps: {...steps, first_session_opened: {outcome: "first_session_opened", session_id: "original-session"}, + first_turn_started: {outcome: "first_turn_started", session_id: "other-session", turn_id: "turn"}}}]) { + assert.equal(compileActionReviewPlan({...proposal, status: "failed", checkpoint}).creationSession, undefined); + } +}); + +test("terminal or persisted first-Turn readback does not advertise another Session", () => { + assert.equal(compileActionReviewPlan({...proposal, status: "applied", receipt: {projection_verified: true}}).creationSession, undefined); + for (const first_turn_readback of [null, {}, {status: "queued"}, + {status: "failed", completed_at: "2026-01-01T00:00:01Z", started_at: null, upstream_turn_id: null}]) { + assert.equal(compileActionReviewPlan({...proposal, first_turn_readback}).creationSession, undefined); + } +}); + +test("managed routing leaves requirement retention and action authority independent", () => { + const input = {...proposal, normalized_parameters: {...proposal.normalized_parameters, + completion_criteria: "Keep the original acceptance boundary"}, checkpoint: {steps}}; + const plan = compileActionReviewPlan(input); + assert.deepEqual(plan.creationSession, {managedAgentId: "codex"}); + assert.deepEqual(plan.creationOutcome?.refinement.requirements, + [{id: "completion", description: "Keep the original acceptance boundary"}]); + assert.equal(Object.hasOwn(plan, "taskExecution"), false); + assert.equal(Object.hasOwn(plan, "taskAccepted"), false); + for (const status of ["gated", "stale", "rejected"]) { + const held = compileActionReviewPlan({...input, status}); + assert.equal(held.canApply, false); + assert.equal(held.retryOriginal, undefined); + } +});