Skip to content

Automate browser based workflows with AI

Recover split LLM responses that strand extra JSON fragments (SKY-12928) (#8253)

Aaron Pereze3030f0a2aff
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx
index fe32009c3..65145c0e4 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx
@@ -486,7 +486,7 @@ describe("WorkflowCopilotChat — g2 review gate (flag-on, SKY-12136)", () => {
);
expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();
expect(screen.getByText("Proposed changes")).toBeTruthy();
- expect(screen.getByText("Tested")).toBeTruthy();
+ expect(screen.queryByText("Tested")).toBeNull();
});
it("clears the proposal and shows a discarded receipt on a late Reject", async () => {
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index fc13205b2..3854a4576 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -123,6 +123,7 @@ import { TooltipProvider } from "@/components/ui/tooltip";
// Cap on retained per-turn snap-back snapshots. A typical session has a
// handful of turns; this ceiling guards a runaway long-running chat.
const MAX_TURN_SNAPSHOTS = 20;
+const TEST_END_TO_END_PROMPT = "Test this workflow end to end.";
// Cadence for re-fetching a live test run's recorded actions. Mirrors the
// backend block-status poll (5s) closely enough to surface rows soon after
@@ -1891,6 +1892,9 @@ export function WorkflowCopilotChat({
// Set by a block's "Generate" arm step so the next send scopes regeneration to that block.
const blockBuildTargetLabelRef = useRef<string | null>(null);
+ // Set by the review gate's "Test end-to-end" action so the next send posts that product
+ // action instead of an ordinary authoring turn.
+ const endToEndActionRef = useRef(false);
// True only while a block-build turn is actually in flight (not a turn it queued behind).
const blockGenInFlightRef = useRef(false);
@@ -1905,8 +1909,11 @@ export function WorkflowCopilotChat({
}
updateQueuedPrompt(null);
- // Drop the queued block-build target so it doesn't leak into the next message.
+ // Drop the queued block-build target and end-to-end action so neither leaks into the next
+ // message. Deferring paths (queue_working / queue_live_browser) keep the action armed on
+ // purpose; only abandoning the message disarms it.
blockBuildTargetLabelRef.current = null;
+ endToEndActionRef.current = false;
setMessages((prev) => prev.filter((message) => message.id !== queued.id));
// Text already in the composer is the newer intent — the user was part way
// through replacing the queued message — so it wins over what comes back.
@@ -2029,6 +2036,7 @@ export function WorkflowCopilotChat({
return;
}
if (!workflowPermanentId) {
+ endToEndActionRef.current = false;
toast({
title: "Missing agent",
description: "Agent permanent ID is required to chat.",
@@ -2050,8 +2058,11 @@ export function WorkflowCopilotChat({
if (!queued) {
return;
}
- // New text: the block-build scope belonged to the message being replaced.
+ // New text: the block-build scope and the end-to-end action belonged to the message being
+ // replaced. Carrying the action over would run the whole workflow for real on text the user
+ // wrote to say something else.
blockBuildTargetLabelRef.current = null;
+ endToEndActionRef.current = false;
updateQueuedPrompt({
...queued,
content: candidate,
@@ -2173,6 +2184,7 @@ export function WorkflowCopilotChat({
let audioArtifactId: string | null = null;
if (!workflowId) {
+ endToEndActionRef.current = false;
toast({
title: "Missing agent",
description: "Agent ID is required to chat.",
@@ -2444,6 +2456,10 @@ export function WorkflowCopilotChat({
}
};
+ // Read before the awaits below, and unconditionally: this send owns the action, so a
+ // throw on the way out must not leave it armed for whatever the user types next.
+ const endToEndAction = endToEndActionRef.current;
+ endToEndActionRef.current = false;
const client = await getSseClient(credentialGetter);
const targetBlockLabel = blockBuildTargetLabelRef.current;
blockBuildTargetLabelRef.current = null;
@@ -2472,6 +2488,7 @@ export function WorkflowCopilotChat({
cancel_token: cancelToken,
idempotency_key: options.idempotencyKey ?? null,
target_block_label: targetBlockLabel,
+ product_action: endToEndAction ? "test_end_to_end" : null,
keep_pending_proposal:
copilotUxV1Enabled && Boolean(pendingProposalTurnId),
// Only opt in behind the flag; flag-off omits the field entirely so
@@ -2690,6 +2707,11 @@ export function WorkflowCopilotChat({
handleSendRef.current = handleSend;
}, [handleSend]);
+ const handleTestEndToEnd = useCallback(() => {
+ endToEndActionRef.current = true;
+ void handleSend(TEST_END_TO_END_PROMPT);
+ }, [handleSend]);
+
const handleConnectedAccountChoice = useCallback(
(turnId: string, connectionId: string) => {
if (connectedAccountChoiceLatch.current !== null) {
@@ -3143,6 +3165,7 @@ export function WorkflowCopilotChat({
? findLastIndexOfTurn(messages, pendingProposalTurnId)
: -1;
const gateIndex = gateOwnerIndex >= 0 ? gateOwnerIndex : lastTurnIndex;
+ const gateOwnerNarrative = messages[gateIndex]?.narrative;
// Mid-turn Accept would be clobbered by the in-flight turn's terminal
// restore, so gate actions wait for idle.
const gateActionable =
@@ -3469,6 +3492,7 @@ export function WorkflowCopilotChat({
proposedWorkflow &&
handleReviewWorkflow(proposedWorkflow)
}
+ onTestEndToEnd={handleTestEndToEnd}
gateId={turnId ? `copilot-gate-${turnId}` : undefined}
flash={turnId !== null && turnId === gateFlashTurnId}
/>
@@ -3672,7 +3696,7 @@ export function WorkflowCopilotChat({
<ReviewGateCard
pending
verdict={getReviewGateVerdict(
- undefined,
+ gateOwnerNarrative,
proposedWorkflow,
)}
settled={null}
@@ -3690,6 +3714,7 @@ export function WorkflowCopilotChat({
proposedWorkflow &&
handleReviewWorkflow(proposedWorkflow)
}
+ onTestEndToEnd={handleTestEndToEnd}
/>
) : !copilotUxV1Enabled && showProposedPanel ? (
<>
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.test.tsx
index 656cc0f44..618dff394 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.test.tsx
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
-import { cleanup, render, screen } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import {
@@ -9,8 +9,27 @@ import {
type TurnNarrativeState,
} from "../narrativeState";
import { WorkflowApiResponse } from "@/routes/workflows/types/workflowTypes";
+import { derivePhases } from "../copilotPhases";
import { ReviewGateCard, getReviewGateVerdict } from "./ReviewGateCard";
+const failedBlock = {
+ workflowRunBlockId: "wrb_failed",
+ label: "add_to_cart",
+ blockType: "task",
+ state: "failed" as const,
+ lastSeenIteration: 0,
+ activity: [],
+ startedAt: null,
+ endedAt: null,
+};
+
+const completedBlock = {
+ ...failedBlock,
+ workflowRunBlockId: "wrb_done",
+ label: "open_page",
+ state: "completed" as const,
+};
+
afterEach(() => {
cleanup();
});
@@ -70,11 +89,11 @@ describe("getReviewGateVerdict", () => {
).toBe("untested");
});
- it("falls back to tested for a legacy proposal without the unvalidated marker", () => {
+ it("has no verdict for a legacy proposal carrying no evidence either way", () => {
const legacyProposal = {} as unknown as WorkflowApiResponse;
expect(
getReviewGateVerdict(turn({ proposalDisposition: null }), legacyProposal),
- ).toBe("tested");
+ ).toBe(null);
});
it("returns null with no disposition and no proposal", () => {
@@ -82,6 +101,151 @@ describe("getReviewGateVerdict", () => {
getReviewGateVerdict(turn({ proposalDisposition: null }), null),
).toBe(null);
});
+
+ it("returns null for a turn-less call, so a pending gate cannot invent a verdict", () => {
+ const proposal = {} as unknown as WorkflowApiResponse;
+ expect(getReviewGateVerdict(undefined, proposal)).toBe(null);
+ });
+
+ it("never reports tested while the turn's own rail computes a failed test phase", () => {
+ const failedTurn = turn({
+ proposalDisposition: "review_tested",
+ blocks: [failedBlock],
+ });
+
+ expect(
+ derivePhases(failedTurn).find((row) => row.id === "test")?.status,
+ ).toBe("fail");
+ expect(getReviewGateVerdict(failedTurn, null)).not.toBe("tested");
+ });
+});
+
+describe("ReviewGateCard — untested proposals stay actionable", () => {
+ const noop = () => {};
+
+ it("keeps Accept and Always accept enabled with an untested verdict", () => {
+ render(
+ <ReviewGateCard
+ turn={turn({ proposalDisposition: "review_untested" })}
+ pending
+ verdict="untested"
+ actionsEnabled
+ onAccept={noop}
+ onAlwaysAccept={noop}
+ onReject={noop}
+ onReview={noop}
+ />,
+ );
+
+ const accept = screen.getByRole("button", { name: /^Accept$/ });
+ const alwaysAccept = screen.getByRole("button", { name: /Always accept/ });
+ expect(accept.hasAttribute("disabled")).toBe(false);
+ expect(alwaysAccept.hasAttribute("disabled")).toBe(false);
+ });
+});
+
+describe("ReviewGateCard — Test end-to-end recourse", () => {
+ const noop = () => {};
+
+ it("keeps Accept working on an untested proposal that never ran end-to-end", () => {
+ let accepted = 0;
+ render(
+ <ReviewGateCard
+ turn={turn({ proposalDisposition: "review_untested" })}
+ pending
+ verdict="untested"
+ actionsEnabled
+ onAccept={() => {
+ accepted += 1;
+ }}
+ onAlwaysAccept={noop}
+ onReject={noop}
+ onReview={noop}
+ onTestEndToEnd={noop}
+ />,
+ );
+
+ const accept = screen.getByRole("button", { name: /^Accept$/ });
+ expect(accept.hasAttribute("disabled")).toBe(false);
+ fireEvent.click(accept);
+ expect(accepted).toBe(1);
+ });
+
+ it("does not claim every step was tested when one of them never ran", () => {
+ render(
+ <ReviewGateCard
+ turn={turn({
+ proposalDisposition: "review_untested",
+ blocks: [
+ completedBlock,
+ { ...failedBlock, state: "drafted" as const },
+ ],
+ })}
+ pending
+ verdict="untested"
+ actionsEnabled
+ onAccept={noop}
+ onAlwaysAccept={noop}
+ onReject={noop}
+ onReview={noop}
+ onTestEndToEnd={noop}
+ />,
+ );
+
+ expect(screen.queryByText(/Each step was tested on its own/)).toBeNull();
+ });
+
+ it("says only that the run acts for real when no step has been tested yet", () => {
+ render(
+ <ReviewGateCard
+ turn={turn({ proposalDisposition: "review_untested", blocks: [] })}
+ pending
+ verdict="untested"
+ actionsEnabled
+ onAccept={noop}
+ onAlwaysAccept={noop}
+ onReject={noop}
+ onReview={noop}
+ onTestEndToEnd={noop}
+ />,
+ );
+
+ expect(
+ screen.getByRole("button", { name: /Test end-to-end/ }),
+ ).not.toBeNull();
+ expect(screen.queryByText(/Each step was tested on its own/)).toBeNull();
+ expect(
+ screen.getByText(/performs real actions on the site/).textContent,
+ ).toContain("place orders");
+ });
+
+ it("states that steps were tested alone, not together, and that the run acts on the site", () => {
+ render(
+ <ReviewGateCard
+ turn={turn({
+ proposalDisposition: "review_untested",
+ blocks: [completedBlock],
+ })}
+ pending
+ verdict="untested"
+ actionsEnabled
+ onAccept={noop}
+ onAlwaysAccept={noop}
+ onReject={noop}
+ onReview={noop}
+ onTestEndToEnd={noop}
+ />,
+ );
+
+ expect(
+ screen.getByRole("button", { name: /Test end-to-end/ }),
+ ).not.toBeNull();
+ const explainer = screen.getByText(/Each step was tested on its own/);
+ expect(explainer.textContent).toContain("have not been run together");
+ expect(explainer.textContent).toContain(
+ "performs real actions on the site",
+ );
+ });
});
describe("ReviewGateCard — block label humanization", () => {
diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx
index d949dea00..595d92223 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx
@@ -3,6 +3,7 @@ import { MagicWandIcon } from "@radix-ui/react-icons";
import { WorkflowApiResponse } from "@/routes/workflows/types/workflowTypes";
import { humanizeBlockLabel } from "../blockLabel";
+import { everyTestBlockExecuted, hasFailedTestBlock } from "../copilotPhases";
import { TurnNarrativeState } from "../narrativeState";
import { getDiffCardTitle } from "./diffCardTitle";
@@ -21,6 +22,9 @@ export function getReviewGateVerdict(
turn: TurnNarrativeState | undefined,
proposedWorkflow: WorkflowApiResponse | null,
): ReviewGateVerdict {
+ if (turn && hasFailedTestBlock(turn)) {
+ return "untested";
+ }
if (
turn?.proposalDisposition === "review_tested" ||
turn?.proposalDisposition === "auto_applicable"
@@ -30,11 +34,8 @@ export function getReviewGateVerdict(
if (turn?.proposalDisposition) {
return "untested";
}
- if (!proposedWorkflow) {
- return null;
- }
- const legacy = proposedWorkflow as LegacyProposedWorkflow;
- return legacy._copilot_unvalidated ? "untested" : "tested";
+ const legacy = proposedWorkflow as LegacyProposedWorkflow | null;
+ return legacy?._copilot_unvalidated ? "untested" : null;
}
const VERDICT_PILL_CLASSES: Record<"tested" | "untested", string> = {
@@ -43,6 +44,14 @@ const VERDICT_PILL_CLASSES: Record<"tested" | "untested", string> = {
untested: "border-sky-500/30 bg-sky-500/15 text-sky-700 dark:text-sky-300",
};
+const END_TO_END_REAL_ACTIONS =
+ "Testing end-to-end performs real actions on the site, so it can submit forms, " +
+ "place orders, or send messages for real.";
+
+const END_TO_END_EXPLAINER =
+ "Each step was tested on its own — the steps have not been run together yet. " +
+ END_TO_END_REAL_ACTIONS;
+
const VERDICT_PILL_LABELS: Record<"tested" | "untested", string> = {
tested: "Tested",
untested: "Untested",
@@ -58,6 +67,7 @@ interface ReviewGateCardProps {
onAlwaysAccept: () => void;
onReject: () => void;
onReview: () => void;
+ onTestEndToEnd?: () => void;
gateId?: string;
// Transient highlight when the pending-proposal chip scrolls to this gate.
flash?: boolean;
@@ -102,6 +112,7 @@ export function ReviewGateCard({
onAlwaysAccept,
onReject,
onReview,
+ onTestEndToEnd,
gateId,
flash = false,
}: ReviewGateCardProps) {
@@ -223,6 +234,25 @@ export function ReviewGateCard({
>
Reject
</button>
+ {onTestEndToEnd ? (
+ <button
+ type="button"
+ onClick={onTestEndToEnd}
+ className="rounded-md border border-border px-3 py-1.5 text-xs text-foreground hover:bg-slate-elevation4 dark:text-slate-200"
+ >
+ Test end-to-end
+ </button>
+ ) : null}
+ {onTestEndToEnd ? (
+ <p className="basis-full text-[11px] leading-snug text-muted-foreground">
+ {verdict === "untested" &&
+ turn &&
+ everyTestBlockExecuted(turn) &&
+ !hasFailedTestBlock(turn)
+ ? END_TO_END_EXPLAINER
+ : END_TO_END_REAL_ACTIONS}
+ </p>
+ ) : null}
</div>
) : null}
{settled ? (
diff --git a/skyvern-frontend/src/routes/workflows/copilot/copilotPhases.ts b/skyvern-frontend/src/routes/workflows/copilot/copilotPhases.ts
index f0048b93b..f4464dd69 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/copilotPhases.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/copilotPhases.ts
@@ -189,6 +189,19 @@ function spanIso(blocks: BlockState[]): {
return { start, end };
}
+export function hasFailedTestBlock(turn: TurnNarrativeState): boolean {
+ return latestBlocksByLabel(turn.blocks)
+ .filter((b) => b.state !== "drafted")
+ .some((b) => b.state === "failed");
+}
+
+export function everyTestBlockExecuted(turn: TurnNarrativeState): boolean {
+ // Gates a claim about every step, so one executed block is not enough and an empty list is
+ // not vacuously true: the turn must carry blocks and none of them may still be drafted.
+ const blocks = latestBlocksByLabel(turn.blocks);
+ return blocks.length > 0 && blocks.every((b) => b.state !== "drafted");
+}
+
export function derivePhases(turn: TurnNarrativeState): PhaseRowModel[] {
const {
explore,
@@ -240,7 +253,7 @@ export function derivePhases(turn: TurnNarrativeState): PhaseRowModel[] {
// A cancelled turn also lands on terminal "error" — that error is the stop
// itself, so it must not paint the rail red.
const isError = turn.terminal === "error" && !isCancelled;
- const anyFailed = latestBlocks.some((b) => b.state === "failed");
+ const anyFailed = hasFailedTestBlock(turn);
const anyStopped = latestBlocks.some((b) => b.state === "stopped");
const anyNotDemonstrated = latestBlocks.some(
(b) => b.outcome === "not_demonstrated" && !isInterimOutcome(b.outcomeRole),
diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
index 6d6bdcde2..3d048656b 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
@@ -52,6 +52,7 @@ export interface WorkflowCopilotChatRequest {
idempotency_key?: string | null;
target_block_label?: string | null;
keep_pending_proposal?: boolean;
+ product_action?: "test_end_to_end" | null;
// Opt-in: only clients that can render the credential_required frame set
// this, so the backend never pauses a turn a client would silently drop.
supports_credential_pause?: boolean;
diff --git a/skyvern/forge/sdk/api/llm/utils.py b/skyvern/forge/sdk/api/llm/utils.py
index 5192139df..f864be30e 100644
--- a/skyvern/forge/sdk/api/llm/utils.py
+++ b/skyvern/forge/sdk/api/llm/utils.py
@@ -175,15 +175,17 @@ def _reassemble_list_response(response: list[Any], allow_action_list_wrap: bool)
dicts = [item for item in response if isinstance(item, dict)]
lists = [item for item in response if isinstance(item, list)]
- # Reasoning object + nested action array. This shape is unambiguous (a nested
- # action array beside a non-action dict), so it never collides with
- # single-object prompts and is recovered regardless of caller.
- if len(dicts) == 1 and len(lists) == 1:
- preamble = dicts[0]
- nested = lists[0]
- is_action_list = bool(nested) and all(isinstance(item, dict) and "action_type" in item for item in nested)
- if is_action_list and "actions" not in preamble and "action_type" not in preamble:
- return {**preamble, "actions": nested}
+ # Reasoning object + nested action array. This shape is unambiguous (exactly one
+ # nested action array beside dicts that carry no decision of their own), so it
+ # never collides with single-object prompts and is recovered regardless of
+ # caller. An unescaped quote inside the reasoning text ends that string early
+ # and strands the remainder as extra fragments, so surplus non-action fragments
+ # are tolerated as long as only one action array survives.
+ action_lists = [
+ item for item in lists if item and all(isinstance(entry, dict) and "action_type" in entry for entry in item)
+ ]
+ if dicts and len(action_lists) == 1 and all("actions" not in d and "action_type" not in d for d in dicts):
+ return {**dicts[0], "actions": action_lists[0]}
# Bare list of action dicts. Collides with single-object callers whose object
# carries action_type, so only wrap when the caller consumes an actions array.
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index 177f0bddb..f388637d8 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -168,6 +168,7 @@ from skyvern.forge.sdk.copilot.terminal_envelope import (
from skyvern.forge.sdk.copilot.todo_list import todo_list_prompt
from skyvern.forge.sdk.copilot.tools.credentials import _server_verified_google_account_choices
from skyvern.forge.sdk.copilot.tools.guardrails import _record_output_policy_guardrail_outcome
+from skyvern.forge.sdk.copilot.tools.run_execution import run_workflow_end_to_end
from skyvern.forge.sdk.copilot.tools.scouting import hydrate_prior_carried_trajectory
from skyvern.forge.sdk.copilot.tracing_setup import _copilot_model_name, ensure_tracing_initialized, is_tracing_enabled
from skyvern.forge.sdk.copilot.turn_context import TurnContextAssembler, TurnContextInputs, TurnContextPacket
@@ -1881,6 +1882,51 @@ def _build_exit_result(
)
+def _end_to_end_run_reply(result: dict[str, Any], block_count: int) -> str:
+ data = result.get("data")
+ detail = (data.get("failure_reason") if isinstance(data, dict) else None) or result.get("error")
+ detail_text = detail.strip() if isinstance(detail, str) and detail.strip() else None
+ # block_count is the planned label list, so a failure that never reached a run must not be
+ # reported as though those steps were tested.
+ run_started = isinstance(data, dict) and bool(data.get("workflow_run_id"))
+ if block_count == 0 or (not result.get("ok") and not run_started):
+ return detail_text or "I could not start an end-to-end test run."
+ steps = "step" if block_count == 1 else "steps"
+ opening = f"Tested all {block_count} {steps} together in a browser session opened just for this run."
+ if result.get("ok"):
+ return f"{opening} Every step completed."
+ if isinstance(data, dict) and (data.get("control_signal") or {}).get("kind") == "watchdog_paused":
+ return f"{opening} The run is paused and waiting on you — the run details are above."
+ if detail_text:
+ return f"{opening} It did not get through: {detail_text}"
+ return f"{opening} It did not get through — the run details are above."
+
+
+async def _run_end_to_end_test_turn(
+ ctx: CopilotContext,
+ *,
+ workflow_yaml: str,
+ global_llm_context: str | None,
+) -> AgentResult:
+ result = await run_workflow_end_to_end(ctx, workflow_yaml)
+ block_count = len(ctx.last_executed_block_labels or [])
+ LOG.info(
+ "copilot_test_end_to_end_turn_finished",
+ workflow_permanent_id=ctx.workflow_permanent_id,
+ turn_id=ctx.turn_id,
+ executed_block_labels=ctx.last_executed_block_labels,
+ run_ok=bool(result.get("ok")),
+ composition_verified_labels=ctx.composition_verified_labels,
+ terminal_ready=ctx.last_full_workflow_test_ok,
+ )
+ return _build_exit_result(
+ ctx,
+ _end_to_end_run_reply(result, block_count),
+ global_llm_context,
+ proposal_disposition="review_tested" if ctx.last_full_workflow_test_ok else "review_untested",
+ )
+
+
async def _build_goal_satisfied_exit_result(
ctx: CopilotContext,
global_llm_context: str | None,
@@ -4370,6 +4416,13 @@ async def _run_copilot_turn_impl(
validated_browser_session_id = await _resolve_live_browser_session_id(chat_request, organization_id)
ctx.browser_session_id = validated_browser_session_id
+ if chat_request.product_action == "test_end_to_end":
+ return await _run_end_to_end_test_turn(
+ ctx,
+ workflow_yaml=chat_request.workflow_yaml or "",
+ global_llm_context=global_llm_context,
+ )
+
model_name, run_config, llm_key, supports_vision = resolve_model_config(
llm_api_handler,
copilot_config=copilot_config,
diff --git a/skyvern/forge/sdk/copilot/frontier_provenance_dump.py b/skyvern/forge/sdk/copilot/frontier_provenance_dump.py
new file mode 100644
index 000000000..d61453d28
--- /dev/null
+++ b/skyvern/forge/sdk/copilot/frontier_provenance_dump.py
@@ -0,0 +1,90 @@
+"""Serializable capture of the frontier planner, edit invalidation, and the terminal-ready latch.
+
+Enabled by ``COPILOT_DUMP_FRONTIER_PROVENANCE=<directory>``; see
+``dev_scripts/replay_frontier_provenance.py`` for the replayer that consumes these packets.
+
+Local development only. Packets carry unredacted workflow definitions and extracted block
+outputs, so setting this anywhere real writes customer data to disk.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+import uuid
+from pathlib import Path
+from typing import Any
+
+import structlog
+from pydantic import BaseModel
+
+from skyvern.forge.sdk.copilot.runtime import AgentContext
+
+LOG = structlog.get_logger()
+
+
+def frontier_dump_root() -> Path | None:
+ root = os.getenv("COPILOT_DUMP_FRONTIER_PROVENANCE")
+ return Path(root).expanduser() if root else None
+
+
+def trust_snapshot(ctx: AgentContext) -> dict[str, Any]:
+ # Callers build this outside write_packet's guard, so it swallows its own failures: an
+ # observability emit must never replace the result the planner decided.
+ try:
+ return _trust_snapshot(ctx)
+ except Exception:
+ LOG.debug("Frontier provenance trust snapshot failed", exc_info=True)
+ return {"trust_snapshot_failed": True}
+
+
+def _trust_snapshot(ctx: AgentContext) -> dict[str, Any]:
+ evidence = ctx.workflow_verification_evidence
+ return {
+ "verified_prefix_labels": list(ctx.verified_prefix_labels or []),
+ "composition_verified_labels": list(ctx.composition_verified_labels or []),
+ "verified_block_outputs": _json_safe(ctx.verified_block_outputs),
+ "verified_prefix_block_end_urls": dict(ctx.verified_prefix_block_end_urls or {}),
+ "verified_prefix_block_end_session_id": ctx.verified_prefix_block_end_session_id,
+ "verified_prefix_terminal_label": ctx.verified_prefix_terminal_label,
+ "frontier_resume_session_id": ctx.frontier_resume_session_id,
+ "frontier_start_provenance": ctx.frontier_start_provenance,
+ "last_full_workflow_test_ok": ctx.last_full_workflow_test_ok,
+ "last_requested_block_labels": list(ctx.last_requested_block_labels or []),
+ "last_executed_block_labels": list(ctx.last_executed_block_labels or []),
+ "last_frontier_start_label": ctx.last_frontier_start_label,
+ "turn_origin": str(ctx.turn_origin),
+ "block_verified": list(evidence.block_verified or []),
+ "full_workflow_verified": evidence.full_workflow_verified,
+ }
+
+
+def definition_payload(definition: object | None) -> dict[str, Any] | None:
+ if not isinstance(definition, BaseModel):
+ return None
+ try:
+ return definition.model_dump(mode="json")
+ except Exception:
+ LOG.debug("Frontier provenance definition dump failed", exc_info=True)
+ return {"definition_payload_failed": True}
+
+
+def write_packet(kind: str, payload: dict[str, Any]) -> None:
+ root = frontier_dump_root()
+ if root is None:
+ return
+ try:
+ directory = root / kind
+ directory.mkdir(parents=True, exist_ok=True)
+ path = directory / f"{time.time_ns()}-{uuid.uuid4().hex[:8]}.json"
+ path.write_text(json.dumps({"kind": kind, **payload}, indent=2, default=str))
+ except Exception:
+ LOG.debug("Frontier provenance dump failed", kind=kind, exc_info=True)
+
+
+def _json_safe(value: dict[str, Any] | None) -> dict[str, Any]:
+ try:
+ return json.loads(json.dumps(value or {}, default=str))
+ except Exception:
+ return {}
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index 2b6cbe71d..12b73d0fc 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -8,7 +8,7 @@ from collections.abc import AsyncIterator, Awaitable, Callable
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from enum import StrEnum
-from typing import TYPE_CHECKING, Any, NotRequired, TypeAlias, TypedDict, cast
+from typing import TYPE_CHECKING, Any, Literal, NotRequired, TypeAlias, TypedDict, cast
import structlog
@@ -64,6 +64,10 @@ if TYPE_CHECKING:
LOG = structlog.get_logger()
+# Where a planned frontier run starts its browser from; only a non-``unanchored`` start proves the
+# run began in a composition state the workflow itself established.
+FrontierStartProvenance = Literal["initial", "replayed", "resumed", "unanchored"]
+
_SESSION_CLEANUP_TIMEOUT_SECONDS = 5.0
# Sized to cover the manager's COMMON recovery so this deadline stops cancelling it midway and
# reporting a session unverified that was about to be handed back: a 2s cached-handle probe, a
@@ -349,6 +353,12 @@ class AgentContext:
# Set by the planner when it proved a resume against the browser above; the next run is
# threaded into that browser instead of the chat's. Consumed and cleared by that run.
frontier_resume_session_id: str | None = None
+ # Where the planned run starts from, stamped once per plan and consumed by that run. Only a
+ # non-``unanchored`` start can credit its labels as composition-verified.
+ frontier_start_provenance: FrontierStartProvenance | None = None
+ # Labels whose last successful run started from a provable composition state. Distinct from
+ # verified_prefix_labels, which drives frontier advancement and must stay per-label.
+ composition_verified_labels: list[str] = field(default_factory=list)
last_full_workflow_test_ok: bool = False
last_unverified_block_labels: list[str] = field(default_factory=list)
workflow_verification_evidence: WorkflowVerificationEvidence = field(default_factory=WorkflowVerificationEvidence)
diff --git a/skyvern/forge/sdk/copilot/tools/__init__.py b/skyvern/forge/sdk/copilot/tools/__init__.py
index 0f9b747ee..d888554f1 100644
--- a/skyvern/forge/sdk/copilot/tools/__init__.py
+++ b/skyvern/forge/sdk/copilot/tools/__init__.py
@@ -766,9 +766,10 @@ async def run_blocks_tool(
prior_definition = await _get_prior_workflow_definition(copilot_ctx)
# No definition change on this path, so the frontier never reaches the edit-in-place branch
# and a live page read would be spent on nothing.
- labels_to_execute, block_outputs_to_seed, frontier_start_label = _plan_frontier(
+ labels_to_execute, block_outputs_to_seed, frontier_start_label, start_provenance = _plan_frontier(
copilot_ctx, block_labels, prior_definition, prior_definition
)
+ copilot_ctx.frontier_start_provenance = start_provenance
with copilot_span(
"run_blocks",
data=_run_blocks_span_data(
@@ -1019,13 +1020,14 @@ async def _run_updated_workflow_blocks(
if copilot_ctx.last_workflow is not None:
new_definition = getattr(copilot_ctx.last_workflow, "workflow_definition", None)
- labels_to_execute, block_outputs_to_seed, frontier_start_label = _plan_frontier(
+ labels_to_execute, block_outputs_to_seed, frontier_start_label, start_provenance = _plan_frontier(
copilot_ctx,
block_labels,
prior_definition,
new_definition,
await _frontier_runtime_page_url(copilot_ctx),
)
+ copilot_ctx.frontier_start_provenance = start_provenance
with copilot_span(
"run_blocks",
data=_run_blocks_span_data(
diff --git a/skyvern/forge/sdk/copilot/tools/_shared.py b/skyvern/forge/sdk/copilot/tools/_shared.py
index 005e9a343..176dfb9d8 100644
--- a/skyvern/forge/sdk/copilot/tools/_shared.py
+++ b/skyvern/forge/sdk/copilot/tools/_shared.py
@@ -401,6 +401,12 @@ def _unverified_current_workflow_labels(ctx: object) -> list[str]:
return [label for label in labels if label not in verified]
+def _composition_unverified_current_workflow_labels(ctx: object) -> list[str]:
+ labels = _current_workflow_block_labels(ctx)
+ verified = set(getattr(ctx, "composition_verified_labels", []) or [])
+ return [label for label in labels if label not in verified]
+
+
def _iter_yaml_blocks(blocks: Any) -> list[dict[str, Any]]:
found: list[dict[str, Any]] = []
if not isinstance(blocks, list):
diff --git a/skyvern/forge/sdk/copilot/tools/frontier.py b/skyvern/forge/sdk/copilot/tools/frontier.py
index bc7d76b31..4cddcde80 100644
--- a/skyvern/forge/sdk/copilot/tools/frontier.py
+++ b/skyvern/forge/sdk/copilot/tools/frontier.py
@@ -26,9 +26,16 @@ from skyvern.forge.sdk.copilot.failure_tracking import (
_canonical_block_config,
block_shape_hashes_by_label,
)
+from skyvern.forge.sdk.copilot.frontier_provenance_dump import (
+ definition_payload,
+ frontier_dump_root,
+ trust_snapshot,
+ write_packet,
+)
from skyvern.forge.sdk.copilot.output_utils import INTERNAL_VALIDATION_FAILURE_PREFIX
from skyvern.forge.sdk.copilot.runtime import (
AgentContext,
+ FrontierStartProvenance,
resolve_browser_state_for_context,
)
from skyvern.forge.sdk.copilot.turn_origin import TurnOrigin
@@ -52,6 +59,8 @@ from ._shared import (
LOG = structlog.get_logger()
+FrontierPlan = tuple[list[str], dict[str, Any], str | None, FrontierStartProvenance]
+
_BLOCK_TYPES_STATE_ESTABLISHER = frozenset({"navigation", "login", "goto_url"})
# Bounds the walk into nested blocks; workflows nest a few levels, not hundreds.
@@ -319,6 +328,7 @@ def _clear_runtime_anchor_evidence(copilot_ctx: Any) -> None:
def _reset_all_verified_trust(copilot_ctx: Any) -> None:
evidence = copilot_ctx.workflow_verification_evidence
copilot_ctx.verified_prefix_labels = []
+ copilot_ctx.composition_verified_labels = []
copilot_ctx.verified_block_outputs = {}
copilot_ctx.verified_prefix_block_end_urls = {}
copilot_ctx.verified_prefix_block_end_session_id = None
@@ -419,6 +429,27 @@ def _invalidate_verified_state_on_edit(
copilot_ctx: Any,
prior_definition: object | None,
new_definition: object | None,
+) -> None:
+ if frontier_dump_root() is None:
+ _apply_verified_state_invalidation(copilot_ctx, prior_definition, new_definition)
+ return
+ before = trust_snapshot(copilot_ctx)
+ _apply_verified_state_invalidation(copilot_ctx, prior_definition, new_definition)
+ write_packet(
+ "invalidation",
+ {
+ "prior_definition": definition_payload(prior_definition),
+ "new_definition": definition_payload(new_definition),
+ "trust_before": before,
+ "trust_after": trust_snapshot(copilot_ctx),
+ },
+ )
+
+
+def _apply_verified_state_invalidation(
+ copilot_ctx: Any,
+ prior_definition: object | None,
+ new_definition: object | None,
) -> None:
evidence = copilot_ctx.workflow_verification_evidence
if new_definition is None:
@@ -453,6 +484,11 @@ def _invalidate_verified_state_on_edit(
copilot_ctx.verified_prefix_labels = [
label for label in copilot_ctx.verified_prefix_labels if label not in invalidated
]
+ # Composition credit is an ordered prefix, so an invalidated block ends it there: the
+ # labels after it were only composed by way of the block that just changed.
+ credited = list(copilot_ctx.composition_verified_labels or [])
+ end = next((index for index, label in enumerate(credited) if label in invalidated), len(credited))
+ copilot_ctx.composition_verified_labels = credited[:end]
for label in invalidated:
copilot_ctx.verified_block_outputs.pop(label, None)
copilot_ctx.verified_prefix_block_end_urls.pop(label, None)
@@ -620,6 +656,8 @@ def _block_can_start_browser_run(block: object) -> bool:
def _nearest_upstream_runnable_anchor(
workflow_labels: list[str], target_label: str, new_definition: object | None
) -> str | None:
+ """The workflow head is a last resort, so a return is not proof the anchor can start a browser
+ run; a caller needing that proof reads the plan's start provenance instead."""
by_label = _blocks_by_label(new_definition)
try:
idx = workflow_labels.index(target_label)
@@ -857,16 +895,85 @@ def _workflow_requires_canonical_persist(prior: Workflow | None, new: Workflow)
return prior_fingerprints != new_fingerprints
+def _plan_start_provenance(
+ labels_to_execute: list[str],
+ frontier_start_label: str | None,
+ new_definition: object | None,
+) -> FrontierStartProvenance:
+ """Composition provenance of a plan, from what its start can prove about the page it opens on."""
+ if not labels_to_execute or frontier_start_label != labels_to_execute[0]:
+ return "unanchored"
+ workflow_labels = _workflow_definition_block_labels(new_definition)
+ start = labels_to_execute[0]
+ start_block = _blocks_by_label(new_definition).get(start)
+ start_establishes_state = start_block is not None and _block_can_start_browser_run(start_block)
+ if workflow_labels and start == workflow_labels[0]:
+ # Position alone proves nothing: a first block that establishes no state runs against
+ # whatever page authoring left open, which is the discontinuity this value exists to catch.
+ # A run given its own browser stamps "initial" directly and never reaches here.
+ return "initial" if start_establishes_state else "unanchored"
+ if start not in workflow_labels or labels_to_execute[-1] not in workflow_labels:
+ return "unanchored"
+ # A plan whose start is also its end replays nothing: the block runs against whatever page the
+ # browser already holds, which is the state this provenance exists to distinguish.
+ if workflow_labels.index(start) >= workflow_labels.index(labels_to_execute[-1]):
+ return "unanchored"
+ return "replayed" if start_establishes_state else "unanchored"
+
+
+def _anchored_plan(
+ plan: tuple[list[str], dict[str, Any], str | None],
+ new_definition: object | None,
+) -> FrontierPlan:
+ labels_to_execute, block_outputs_to_seed, frontier_start_label = plan
+ return (
+ labels_to_execute,
+ block_outputs_to_seed,
+ frontier_start_label,
+ _plan_start_provenance(labels_to_execute, frontier_start_label, new_definition),
+ )
+
+
def _plan_frontier(
ctx: AgentContext,
requested_labels: list[str],
old_definition: object | None,
new_definition: object | None,
runtime_page_url: str | None = None,
-) -> tuple[list[str], dict[str, Any], str | None]:
+) -> FrontierPlan:
+ if frontier_dump_root() is None:
+ return _plan_frontier_uncaptured(ctx, requested_labels, old_definition, new_definition, runtime_page_url)
+ before = trust_snapshot(ctx)
+ plan = _plan_frontier_uncaptured(ctx, requested_labels, old_definition, new_definition, runtime_page_url)
+ labels_to_execute, _seed, frontier_start_label, start_provenance = plan
+ write_packet(
+ "frontier",
+ {
+ "requested_labels": list(requested_labels),
+ "old_definition": definition_payload(old_definition),
+ "new_definition": definition_payload(new_definition),
+ "runtime_page_url": runtime_page_url,
+ "trust_before": before,
+ "plan": {
+ "labels_to_execute": list(labels_to_execute),
+ "frontier_start_label": frontier_start_label,
+ "frontier_start_provenance": start_provenance,
+ },
+ },
+ )
+ return plan
+
+
+def _plan_frontier_uncaptured(
+ ctx: AgentContext,
+ requested_labels: list[str],
+ old_definition: object | None,
+ new_definition: object | None,
+ runtime_page_url: str | None = None,
+) -> FrontierPlan:
"""Plan the frontier execution.
- Returns ``(labels_to_execute, block_outputs_to_seed, frontier_start_label)``.
+ Returns ``(labels_to_execute, block_outputs_to_seed, frontier_start_label, start_provenance)``.
Falls back to the full requested list on any ambiguity. When there is no
workflow change (plain run path) the frontier is the first requested label,
@@ -874,9 +981,10 @@ def _plan_frontier(
browser-state outputs needed to start a downstream frontier.
"""
if not requested_labels:
- return requested_labels, {}, None
+ return requested_labels, {}, None, "unanchored"
if new_definition is None:
- return requested_labels, {}, requested_labels[0]
+ # Nothing to prove a start against, so the run cannot claim a composition state.
+ return requested_labels, {}, requested_labels[0], "unanchored"
verified_outputs: dict[str, Any] = dict(ctx.verified_block_outputs or {})
verified_prefix: list[str] = list(ctx.verified_prefix_labels or [])
@@ -886,21 +994,27 @@ def _plan_frontier(
# No old definition (cold start or parse failure) OR no diff signal → plain path.
if old_definition is None:
frontier = failed_frontier_label or requested_labels[0]
- return _seed_for_frontier(requested_labels, frontier, verified_outputs, new_definition)
+ return _anchored_plan(
+ _seed_for_frontier(requested_labels, frontier, verified_outputs, new_definition),
+ new_definition,
+ )
try:
invalidated = _find_invalidated_labels(old_definition, new_definition, requested_labels)
except Exception:
LOG.debug("Frontier diff failed, falling back to full run", exc_info=True)
- return requested_labels, {}, requested_labels[0]
+ return _anchored_plan((requested_labels, {}, requested_labels[0]), new_definition)
earliest = _earliest_invalidated(requested_labels, invalidated)
if earliest is None:
if failed_frontier_label is not None:
- return _seed_for_frontier(
- requested_labels,
- failed_frontier_label,
- verified_outputs,
+ return _anchored_plan(
+ _seed_for_frontier(
+ requested_labels,
+ failed_frontier_label,
+ verified_outputs,
+ new_definition,
+ ),
new_definition,
)
# No invalidation at all — unchanged request. Continue from the
@@ -909,7 +1023,10 @@ def _plan_frontier(
# verified frontiers.
next_frontier = _first_unverified_requested_label(requested_labels, verified_prefix_set)
if next_frontier is not None:
- return _seed_for_frontier(requested_labels, next_frontier, verified_outputs, new_definition)
+ return _anchored_plan(
+ _seed_for_frontier(requested_labels, next_frontier, verified_outputs, new_definition),
+ new_definition,
+ )
# If the model accidentally asks to rerun an already-verified prefix,
# keep the browser moving forward instead of spending another tool call
@@ -918,14 +1035,20 @@ def _plan_frontier(
next_workflow_frontier = _first_unverified_requested_label(workflow_labels, verified_prefix_set)
if next_workflow_frontier is not None:
frontier_idx = workflow_labels.index(next_workflow_frontier)
- return _seed_for_frontier(
- workflow_labels[: frontier_idx + 1],
- next_workflow_frontier,
- verified_outputs,
+ return _anchored_plan(
+ _seed_for_frontier(
+ workflow_labels[: frontier_idx + 1],
+ next_workflow_frontier,
+ verified_outputs,
+ new_definition,
+ ),
new_definition,
)
- return _seed_for_frontier(requested_labels, requested_labels[0], verified_outputs, new_definition)
+ return _anchored_plan(
+ _seed_for_frontier(requested_labels, requested_labels[0], verified_outputs, new_definition),
+ new_definition,
+ )
earliest_idx = requested_labels.index(earliest)
failed_frontier_idx = (
@@ -936,10 +1059,13 @@ def _plan_frontier(
and failed_frontier_idx is not None
and (failed_frontier_idx < earliest_idx or failed_frontier_label != _recorded_failed_attempted_label(ctx))
):
- return _seed_for_frontier(
- requested_labels,
- failed_frontier_label,
- verified_outputs,
+ return _anchored_plan(
+ _seed_for_frontier(
+ requested_labels,
+ failed_frontier_label,
+ verified_outputs,
+ new_definition,
+ ),
new_definition,
)
@@ -949,7 +1075,7 @@ def _plan_frontier(
prefix_in_requested = [label for label in requested_labels if label != earliest]
prefix_in_requested = prefix_in_requested[: requested_labels.index(earliest)]
if not all(label in verified_prefix_set for label in prefix_in_requested):
- return requested_labels, {}, requested_labels[0]
+ return _anchored_plan((requested_labels, {}, requested_labels[0]), new_definition)
old_by_label = _blocks_by_label(old_definition)
is_append_only = earliest not in old_by_label
@@ -963,17 +1089,21 @@ def _plan_frontier(
if not all(label in verified_prefix_set for label in workflow_prefix):
anchor = _nearest_upstream_runnable_anchor(workflow_labels, earliest, new_definition)
if anchor is not None:
- return _seed_for_frontier(
- workflow_labels[workflow_labels.index(anchor) : workflow_labels.index(earliest) + 1],
- anchor,
- verified_outputs,
+ return _anchored_plan(
+ _seed_for_frontier(
+ workflow_labels[workflow_labels.index(anchor) : workflow_labels.index(earliest) + 1],
+ anchor,
+ verified_outputs,
+ new_definition,
+ ),
new_definition,
)
# The prefix ran somewhere; an appended block has to run there too, or it acts on a page
# that browser never reached. Naming it is safe only on the same evidence a resume needs.
seeded = _seed_for_frontier(requested_labels, earliest, verified_outputs, new_definition)
- _name_resume_session_for_plan(ctx, seeded, earliest, new_definition, runtime_page_url)
- return seeded
+ if _name_resume_session_for_plan(ctx, seeded, earliest, new_definition, runtime_page_url):
+ return (*seeded, "resumed")
+ return _anchored_plan(seeded, new_definition)
# Edit-in-place. The edited block can only be rerun alone when the live session is provably
# still on the page its predecessor ended on; otherwise walk back to the nearest upstream
@@ -987,11 +1117,14 @@ def _plan_frontier(
requested_labels=requested_labels,
resume_session_id=ctx.frontier_resume_session_id,
)
- return seeded
+ return (*seeded, "resumed")
anchor = _nearest_upstream_state_establisher(requested_labels, earliest, new_definition)
if anchor is None:
- return requested_labels, {}, requested_labels[0]
- return _seed_for_frontier(requested_labels, anchor, verified_outputs, new_definition)
+ return _anchored_plan((requested_labels, {}, requested_labels[0]), new_definition)
+ return _anchored_plan(
+ _seed_for_frontier(requested_labels, anchor, verified_outputs, new_definition),
+ new_definition,
+ )
def _first_unverified_requested_label(requested_labels: list[str], verified_prefix_set: set[str]) -> str | None:
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index 91edd4ef9..29abc158d 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -66,6 +66,7 @@ from skyvern.forge.sdk.copilot.failure_tracking import (
_blocks_by_label,
block_shape_hashes_by_label,
)
+from skyvern.forge.sdk.copilot.frontier_provenance_dump import frontier_dump_root, trust_snapshot, write_packet
from skyvern.forge.sdk.copilot.narration import NarratorState
from skyvern.forge.sdk.copilot.narration import handler_available as narration_handler_available
from skyvern.forge.sdk.copilot.narration import narrator_poll_tick
@@ -91,6 +92,7 @@ from skyvern.forge.sdk.copilot.run_outcome import (
)
from skyvern.forge.sdk.copilot.runtime import (
AgentContext,
+ FrontierStartProvenance,
PreRunPageReference,
RegisteredArtifactEntry,
RegisteredArtifactEvidence,
@@ -135,11 +137,14 @@ from ._shared import (
_FAILED_BLOCK_STATUSES,
RUN_BLOCKS_SAFETY_CEILING_SECONDS,
_completed_run_block_labels,
+ _composition_unverified_current_workflow_labels,
+ _current_workflow_block_labels,
_failed_run_block_labels,
_fallback_page_info,
_is_meaningful_extracted_data,
_unverified_current_workflow_labels,
_valid_runtime_anchor_url,
+ _workflow_definition_block_labels,
_workflow_verification_evidence,
)
from .banned_blocks import _copilot_block_authoring_policy
@@ -174,6 +179,7 @@ from .frontier import (
_workflow_with_runtime_frontier_starter_url_seed,
)
from .guardrails import (
+ _authority_tool_error,
_parameter_binding_invariant_error,
_placeholder_for_parameter_type,
)
@@ -1654,6 +1660,112 @@ def _resolve_run_data_and_unbound_keys(
return data, unbound
+def terminal_ready_for_latch(
+ *,
+ current_workflow_labels: list[str],
+ has_executed_blocks: bool,
+ unverified: list[str],
+ composition_unverified: list[str],
+ artifact_reason: object | None,
+ structured_blocker: object | None,
+ empty_data_blocks: object,
+) -> bool:
+ """The single definition of "tested". Offline replay calls this, so the rule cannot drift from its grader."""
+ return (
+ # "Every label is credited" says nothing when there are no labels, so an unresolvable
+ # workflow must not satisfy it by emptiness.
+ bool(current_workflow_labels)
+ and has_executed_blocks
+ and not unverified
+ and not composition_unverified
+ and artifact_reason is None
+ and structured_blocker is None
+ and not empty_data_blocks
+ )
+
+
+def _credit_composition_verified_labels(
+ ctx: AgentContext,
+ labels_to_execute: list[str],
+ start_provenance: FrontierStartProvenance,
+) -> None:
+ """Passing is not anchoring: credit only a run that started from a provable composition state
+ and executed exactly the workflow labels following the credit already earned."""
+ if start_provenance == "unanchored":
+ return
+ workflow_labels = _current_workflow_block_labels(ctx)
+ if not workflow_labels:
+ return
+ credited = list(ctx.composition_verified_labels or [])
+ # Credit is an ordered contiguous prefix, so a workflow that no longer opens with it has to
+ # re-earn the whole chain rather than keep set membership that says nothing about order.
+ if credited != workflow_labels[: len(credited)]:
+ ctx.composition_verified_labels = []
+ return
+ if not labels_to_execute:
+ return
+ # Starting before the credited boundary is more evidence, not less: a walk-back replay or a
+ # full re-run proves the chain from further back, so credit it rather than demanding the plan
+ # begin exactly where the previous credit stopped.
+ try:
+ start_index = workflow_labels.index(labels_to_execute[0])
+ except ValueError:
+ return
+ if start_index > len(credited):
+ return
+ end = start_index + len(labels_to_execute)
+ if labels_to_execute != workflow_labels[start_index:end]:
+ return
+ ctx.composition_verified_labels = workflow_labels[: max(end, len(credited))]
+
+
+async def run_workflow_end_to_end(ctx: CopilotContext, workflow_yaml: str) -> dict[str, Any]:
+ """Run every block of a candidate workflow in one browser minted for this run. Frontier
+ selection is bypassed and the provenance stamped so a clean result earns composition credit
+ for the whole chain rather than for one label."""
+ authority_error = _authority_tool_error(ctx, "run_blocks_and_collect_debug")
+ if authority_error:
+ return {"ok": False, "error": authority_error}
+
+ workflow = await _process_workflow_yaml(
+ workflow_id=ctx.workflow_id,
+ workflow_permanent_id=ctx.workflow_permanent_id,
+ organization_id=ctx.organization_id,
+ workflow_yaml=workflow_yaml,
+ settings_fallback_yaml=ctx.persisted_workflow_yaml,
+ )
+ # Checked before anything is staged: a blockless candidate would otherwise replace the good
+ # in-memory workflow on its way to returning an error.
+ labels = _workflow_definition_block_labels(workflow.workflow_definition)
+ if not labels:
+ return {"ok": False, "error": "This workflow has no blocks to run."}
+
+ ctx.staged_workflow = workflow
+ ctx.staged_workflow_yaml = workflow_yaml
+ ctx.workflow_yaml = workflow_yaml
+ ctx.last_workflow = workflow
+ ctx.last_workflow_yaml = workflow_yaml
+
+ # This run starts the chain over in its own browser, so its result supersedes credit earned
+ # by earlier partial runs rather than appending to it. A resume id left by an earlier plan
+ # would outrank force_fresh_session and run this in a carried browser, which is the one way
+ # "initial" could be stamped on a start it cannot prove.
+ ctx.frontier_resume_session_id = None
+ ctx.composition_verified_labels = []
+ ctx.frontier_start_provenance = "initial"
+ result = await _run_blocks_and_collect_debug(
+ {"block_labels": labels, "parameters": {}},
+ ctx,
+ labels_to_execute=labels,
+ frontier_start_label=labels[0],
+ force_fresh_session=True,
+ definition_unpersisted=True,
+ outside_turn_deadline=True,
+ )
+ await _verify_and_record_run_blocks_result(ctx, result, time.monotonic())
+ return result
+
+
async def _run_blocks_and_collect_debug(
params: dict[str, Any],
ctx: CopilotContext,
@@ -1661,11 +1773,16 @@ async def _run_blocks_and_collect_debug(
labels_to_execute: list[str] | None = None,
block_outputs_to_seed: dict[str, Any] | None = None,
frontier_start_label: str | None = None,
+ force_fresh_session: bool = False,
+ definition_unpersisted: bool = False,
+ outside_turn_deadline: bool = False,
) -> dict[str, Any]:
# Read the planner's session choice before any exit path, so a run that bails cannot leave it
# set for a later run whose frontier was never proven against that browser.
resume_session_id = ctx.frontier_resume_session_id
ctx.frontier_resume_session_id = None
+ start_provenance: FrontierStartProvenance = ctx.frontier_start_provenance or "unanchored"
+ ctx.frontier_start_provenance = None
block_labels = params["block_labels"]
if not block_labels:
@@ -1707,6 +1824,9 @@ async def _run_blocks_and_collect_debug(
if prior_draft_workflow is not None:
workflow = prior_draft_workflow
resolved_from_prior_draft = True
+ # An in-memory definition the canonical rows never saw: nothing for the parameter-binding
+ # invariant to compare against, and the run needs a persisted snapshot of its own to bind.
+ executes_unpersisted_definition = resolved_from_prior_draft or definition_unpersisted
if not workflow:
return {"ok": False, "error": f"Workflow not found: {ctx.workflow_permanent_id}"}
@@ -1819,10 +1939,11 @@ async def _run_blocks_and_collect_debug(
# Short-circuit before a wasted workflow execution when the definition
# JSON has drifted from the persisted parameter rows that runtime reads.
- # Skipped for the prior-draft fallback: its in-memory params differ from the rolled-back canonical rows by design.
+ # Skipped when the definition was never persisted: its in-memory params differ from the
+ # canonical rows by design, and the run binds against its own snapshot version instead.
invariant_error = (
None
- if resolved_from_prior_draft
+ if executes_unpersisted_definition
else _parameter_binding_invariant_error(workflow, persisted_workflow_params, persisted_output_params)
)
if invariant_error is not None:
@@ -1852,8 +1973,8 @@ async def _run_blocks_and_collect_debug(
# A resume proven against another browser has to run in that browser; minting or falling back
# to the chat's would drop the very state the resume was authorised against.
- use_fresh_session = resume_session_id is None and _should_use_fresh_session_for_login_first_replay(
- ctx, labels_that_may_execute, workflow
+ use_fresh_session = resume_session_id is None and (
+ force_fresh_session or _should_use_fresh_session_for_login_first_replay(ctx, labels_that_may_execute, workflow)
)
# Reported as run evidence, so it stays literal: a browser minted for this run. A carried
# browser is not one, and reporting it as such would misattribute a challenge that stalled.
@@ -1930,17 +2051,17 @@ async def _run_blocks_and_collect_debug(
}
)
- # Snapshot version persisted for a worker-dispatched run or an inline run sourced from an
- # unsaved prior draft. The run is created against its exact workflow_id so prepare_workflow
+ # Snapshot version persisted for a worker-dispatched run or an inline run of a definition that
+ # was never persisted. The run is created against its exact workflow_id so prepare_workflow
# reads parameter rows from the same definition execute_workflow receives. Without the inline
- # prior-draft snapshot, newly drafted parameters exist only in memory and are omitted from the
+ # snapshot, newly drafted parameters exist only in memory and are omitted from the
# WorkflowRunParameter rows, causing block execution to fail before it reaches the browser.
# The snapshot is soft-deleted once the run resolves so it never lingers as the latest version.
dispatch_draft_workflow_id: str | None = None
# The persisted dispatch version (its own regenerated parameter ids) used for post-run output
# mapping on the dispatch path; runtime_workflow / ctx.staged_workflow is left unmutated.
dispatch_workflow: Workflow | None = None
- if dispatch_to_worker or resolved_from_prior_draft:
+ if dispatch_to_worker or executes_unpersisted_definition:
# Persist the wrapped runtime workflow as a real new version (with its own parameter /
# output-parameter rows) through the normal create machinery. The run is then created
# against this version so the worker resolves it by run.workflow_id and registers block
@@ -1956,7 +2077,7 @@ async def _run_blocks_and_collect_debug(
"Failed to persist copilot run snapshot; blocking execution",
workflow_permanent_id=ctx.workflow_permanent_id,
dispatch_to_worker=dispatch_to_worker,
- resolved_from_prior_draft=resolved_from_prior_draft,
+ executes_unpersisted_definition=executes_unpersisted_definition,
exc_info=True,
)
if dispatch_to_worker:
@@ -2153,9 +2274,10 @@ async def _run_blocks_and_collect_debug(
# Active block runs use the tighter per-tool budget so a single in-flight
# call cannot consume the whole copilot session. Quiet-block runs keep the
# long safety ceiling because HumanInteractionBlock can legitimately pause
- # indefinitely.
+ # indefinitely, and so does a run the user triggered outside the turn: it
+ # replays every block, which the per-tool budget is far too small to cover.
budget_exit_reason: WatchdogExitReason
- if stagnation_enabled:
+ if stagnation_enabled and not outside_turn_deadline:
budget_seconds = _active_block_run_budget_seconds(ctx)
budget_exit_reason = "per_tool_budget"
else:
@@ -2557,6 +2679,7 @@ async def _run_blocks_and_collect_debug(
existing_prefix.append(label)
existing_set.add(label)
ctx.verified_prefix_labels = existing_prefix
+ _credit_composition_verified_labels(ctx, labels_to_execute, start_provenance)
# Rebuilt from this run's rows alone: the position was forgotten at dispatch, and the
# browser these pages describe is the one this run used.
ctx.verified_prefix_block_end_urls = dict(block_end_urls)
@@ -3177,6 +3300,7 @@ def _record_run_blocks_result(
output_report=output_report,
)
unverified = _unverified_current_workflow_labels(copilot_ctx)
+ composition_unverified = _composition_unverified_current_workflow_labels(copilot_ctx)
result_blocks = data.get("blocks") if isinstance(data, dict) else None
executed_labels = data.get("executed_block_labels") if isinstance(data, dict) else None
has_executed_blocks = bool(
@@ -3188,14 +3312,31 @@ def _record_run_blocks_result(
copilot_ctx.last_failed_workflow_yaml = None
copilot_ctx.last_test_failure_reason = None
copilot_ctx.last_test_suspicious_success = False
- terminal_ready = (
- has_executed_blocks
- and not unverified
- and artifact_reason is None
- and structured_blocker is None
- and not empty_data_blocks
+ terminal_ready = terminal_ready_for_latch(
+ current_workflow_labels=_current_workflow_block_labels(copilot_ctx),
+ has_executed_blocks=has_executed_blocks,
+ unverified=unverified,
+ composition_unverified=composition_unverified,
+ artifact_reason=artifact_reason,
+ structured_blocker=structured_blocker,
+ empty_data_blocks=empty_data_blocks,
)
copilot_ctx.verified_terminal_proposal_ready = terminal_ready
+ if frontier_dump_root() is not None:
+ write_packet(
+ "latch",
+ {
+ "trust": trust_snapshot(copilot_ctx),
+ "current_workflow_labels": _current_workflow_block_labels(copilot_ctx),
+ "unverified": unverified,
+ "composition_unverified": composition_unverified,
+ "has_executed_blocks": has_executed_blocks,
+ "artifact_reason": artifact_reason,
+ "structured_blocker": structured_blocker,
+ "empty_data_blocks": empty_data_blocks,
+ "terminal_ready": terminal_ready,
+ },
+ )
copilot_ctx.last_full_workflow_test_ok = terminal_ready
if copilot_ctx.last_full_workflow_test_ok:
copilot_ctx.last_unverified_block_labels = []
diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.py
index d7857f141..41b30ab02 100644
--- a/skyvern/forge/sdk/routes/workflow_copilot.py
+++ b/skyvern/forge/sdk/routes/workflow_copilot.py
@@ -165,6 +165,7 @@ def bind_copilot_session_id(chat_id: str | None) -> Iterator[None]:
COPILOT_CODE_MODE_OPT_OUT_EVENT = "copilot_code_mode_opt_out"
COPILOT_RECOVERABLE_FAILURE_TERMINAL_REASON = "copilot_recoverable_failure"
USER_CANCELLED_TERMINAL_REASON = "user_cancelled"
+TEST_END_TO_END_TURN_MESSAGE = "Test this workflow end to end."
def _effective_copilot_composer_mode(
@@ -2070,6 +2071,24 @@ async def _new_copilot_chat_post(
if blockless_fallback is not None:
chat_request.workflow_yaml = blockless_fallback
+ if chat_request.product_action == "test_end_to_end":
+ # The button posts a structured action, so the message is the server's own
+ # receipt line rather than client prose the turn would have to interpret.
+ chat_request.message = TEST_END_TO_END_TURN_MESSAGE
+ pending_proposal_yaml = _prior_copilot_workflow_yaml(
+ proposed_workflow=chat.proposed_workflow,
+ persisted_workflow_yaml=None,
+ )
+ # The action runs a definition end to end with real side effects, so it may only ever
+ # run the server's own pending proposal. Falling through would execute whatever YAML
+ # the caller sent, unreviewed.
+ if pending_proposal_yaml is None:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="No pending proposal to test end to end.",
+ )
+ chat_request.workflow_yaml = pending_proposal_yaml
+
block_infos, debug_html = await _get_new_copilot_block_infos(
organization.organization_id, chat_request.workflow_run_id
)
diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.py
index 34e0082f9..e2518bfbc 100644
--- a/skyvern/forge/sdk/schemas/workflow_copilot.py
+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py
@@ -165,6 +165,14 @@ class WorkflowCopilotChatRequest(BaseModel):
"a new proposal, so the client can keep rendering an actionable review gate."
),
)
+ product_action: Literal["test_end_to_end"] | None = Field(
+ None,
+ description=(
+ "Structured product action for this turn, dispatched by the server instead of the agent. "
+ "'test_end_to_end' runs every block of the pending proposal in a browser session minted "
+ "for that run."
+ ),
+ )
class WorkflowCopilotCancelRequest(BaseModel):
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 9a9213885..7791bfd09 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -1734,7 +1734,7 @@ workflow_definition:
monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *args, **kwargs: None)
monkeypatch.setattr(tools_module, "_get_prior_workflow_definition", AsyncMock(return_value=None))
monkeypatch.setattr(tools_module, "_update_workflow", fake_update_workflow)
- monkeypatch.setattr(tools_module, "_plan_frontier", lambda *args: (["submit"], {}, "submit"))
+ monkeypatch.setattr(tools_module, "_plan_frontier", lambda *args: (["submit"], {}, "submit", "initial"))
monkeypatch.setattr(tools_module, "_run_blocks_and_collect_debug", fake_run_blocks)
monkeypatch.setattr(tools_module, "_record_diagnosis_repair_contract", lambda *args, **kwargs: None)
monkeypatch.setattr(tools_module, "enqueue_screenshot_from_result", lambda *args, **kwargs: None)
@@ -1824,7 +1824,7 @@ workflow_definition:
monkeypatch.setattr(tools_module, "_get_prior_workflow_definition", AsyncMock(return_value={"blocks": []}))
monkeypatch.setattr(tools_module, "_update_workflow", fake_update_workflow)
monkeypatch.setattr(tools_module, "_frontier_runtime_page_url", AsyncMock(return_value=None))
- monkeypatch.setattr(tools_module, "_plan_frontier", lambda *args: (["read_total"], {}, "read_total"))
+ monkeypatch.setattr(tools_module, "_plan_frontier", lambda *args: (["read_total"], {}, "read_total", "initial"))
monkeypatch.setattr(tools_module, "_run_blocks_and_collect_debug", fake_run_blocks)
monkeypatch.setattr(tools_module, "_verify_and_record_run_blocks_result", AsyncMock())
monkeypatch.setattr(tools_module, "_record_workflow_update_result", lambda *args, **kwargs: None)
@@ -3225,6 +3225,7 @@ class TestCredentialRefusalReachesAgent:
workflow_copilot_chat_id="chat-1",
workflow_yaml="",
browser_session_id=None,
+ product_action=None,
),
chat_history=[],
global_llm_context=None,
@@ -4446,6 +4447,7 @@ class TestCopilotConfig:
workflow_copilot_chat_id="chat-1",
workflow_yaml="",
browser_session_id=None,
+ product_action=None,
),
chat_history=[],
global_llm_context=None,
diff --git a/tests/unit/test_copilot_completion_verification.py b/tests/unit/test_copilot_completion_verification.py
index 061ebcea9..dda6ae970 100644
--- a/tests/unit/test_copilot_completion_verification.py
+++ b/tests/unit/test_copilot_completion_verification.py
@@ -3123,6 +3123,7 @@ def _ctx_with_blocks(*block_types: str) -> CopilotContext:
blocks = [SimpleNamespace(block_type=bt, label=f"b{i}") for i, bt in enumerate(block_types)]
ctx.last_workflow = SimpleNamespace(workflow_definition=SimpleNamespace(blocks=blocks))
ctx.verified_prefix_labels = [b.label for b in blocks]
+ ctx.composition_verified_labels = [b.label for b in blocks]
return ctx
@@ -9902,6 +9903,7 @@ def test_snapshot_includes_verified_context_labels_without_prior_outputs() -> No
)
)
ctx.verified_prefix_labels = list(labels)
+ ctx.composition_verified_labels = list(labels)
ctx.verified_block_outputs["expand_noor_assi_result"] = {"stale": "prior run output"}
run = {
@@ -10000,6 +10002,7 @@ async def test_completion_verification_receives_verified_context_labels(monkeypa
)
)
ctx.verified_prefix_labels = list(labels)
+ ctx.composition_verified_labels = list(labels)
result = {
"ok": True,
"data": {
diff --git a/tests/unit/test_copilot_enforcement_pruning.py b/tests/unit/test_copilot_enforcement_pruning.py
index 0fc49a3e8..d72d7e280 100644
--- a/tests/unit/test_copilot_enforcement_pruning.py
+++ b/tests/unit/test_copilot_enforcement_pruning.py
@@ -454,6 +454,7 @@ def test_record_run_blocks_result_promotes_when_verified_prefix_covers_workflow(
)
ctx.last_workflow_yaml = "workflow: yaml"
ctx.verified_prefix_labels = ["open", "extract"]
+ ctx.composition_verified_labels = ["open", "extract"]
ctx.last_unverified_block_labels = ["stale_extract"]
result = {
diff --git a/tests/unit/test_copilot_frontier.py b/tests/unit/test_copilot_frontier.py
index dc65220a2..a2277c458 100644
--- a/tests/unit/test_copilot_frontier.py
+++ b/tests/unit/test_copilot_frontier.py
@@ -9,12 +9,14 @@ import pytest
from jinja2.sandbox import SandboxedEnvironment
from skyvern.forge.sdk.copilot import tools
+from skyvern.forge.sdk.copilot.agent import _verified_workflow_or_none
from skyvern.forge.sdk.copilot.build_test_outcome import RecordedBuildTestOutcome
from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.copilot.output_utils import (
sanitize_tool_result_for_llm,
summarize_tool_result,
)
+from skyvern.forge.sdk.copilot.request_policy import RequestPolicy
from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome
from skyvern.forge.sdk.copilot.tools import (
_find_invalidated_labels,
@@ -24,6 +26,13 @@ from skyvern.forge.sdk.copilot.tools import (
_referenced_output_labels,
)
from skyvern.forge.sdk.copilot.tools import frontier as frontier_module
+from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module
+from skyvern.forge.sdk.copilot.tools.run_execution import (
+ _credit_composition_verified_labels,
+ _record_run_blocks_result,
+ run_workflow_end_to_end,
+ terminal_ready_for_latch,
+)
from skyvern.forge.sdk.workflow.models.parameter import RESERVED_PARAMETER_KEYS
@@ -187,7 +196,7 @@ def test_plan_frontier_append_after_success_runs_only_appended() -> None:
ctx.verified_prefix_labels = ["a", "b"]
ctx.verified_block_outputs = {"a": "nav_ok", "b": {"title": "hi"}}
- labels, _seed, frontier = _plan_frontier(ctx, ["a", "b", "c"], old, new)
+ labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["a", "b", "c"], old, new)
assert labels == ["c"]
assert frontier == "c"
@@ -210,7 +219,7 @@ def test_plan_frontier_append_walks_back_when_workflow_prefix_is_not_verified()
ctx.verified_prefix_labels = ["open"]
ctx.verified_block_outputs = {"open": "opened"}
- labels, seed, frontier = _plan_frontier(ctx, ["submit_search"], old, new)
+ labels, seed, frontier, _provenance = _plan_frontier(ctx, ["submit_search"], old, new)
assert labels == ["open", "set_search", "submit_search"]
assert seed == {}
@@ -229,7 +238,7 @@ def test_plan_frontier_unchanged_workflow_continues_from_first_unverified_label(
ctx = _make_ctx()
ctx.verified_prefix_labels = ["open", "set_search"]
- labels, seed, frontier = _plan_frontier(
+ labels, seed, frontier, _provenance = _plan_frontier(
ctx,
["open", "set_search", "submit_search", "extract"],
definition,
@@ -253,7 +262,7 @@ def test_plan_frontier_verified_only_request_advances_to_next_unverified_workflo
ctx = _make_ctx()
ctx.verified_prefix_labels = ["open", "set_search"]
- labels, seed, frontier = _plan_frontier(
+ labels, seed, frontier, _provenance = _plan_frontier(
ctx,
["open", "set_search"],
definition,
@@ -281,7 +290,7 @@ def test_plan_frontier_suffix_only_request_seeds_prior_browser_state_outputs() -
"search": {"current_url": "https://example.com/search/results"},
}
- labels, seed, frontier = _plan_frontier(ctx, ["expand"], definition, definition)
+ labels, seed, frontier, _provenance = _plan_frontier(ctx, ["expand"], definition, definition)
assert labels == ["expand"]
assert seed == {
@@ -586,7 +595,7 @@ def test_plan_frontier_edit_walks_back_to_upstream_navigation_anchor() -> None:
ctx.verified_prefix_labels = ["nav", "click"]
ctx.verified_block_outputs = {"nav": "ok"}
- labels, _seed, frontier = _plan_frontier(ctx, ["nav", "click"], old, new)
+ labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["nav", "click"], old, new)
assert labels == ["nav", "click"]
assert frontier == "nav"
@@ -601,7 +610,7 @@ def test_plan_frontier_edit_read_only_block_still_walks_back_to_anchor() -> None
ctx.verified_prefix_labels = ["nav", "extract"]
ctx.verified_block_outputs = {"nav": "ok", "extract": "old_out"}
- labels, _seed, frontier = _plan_frontier(ctx, ["nav", "extract"], old, new)
+ labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["nav", "extract"], old, new)
assert labels == ["nav", "extract"]
assert frontier == "nav"
@@ -636,7 +645,7 @@ def test_plan_frontier_edit_resumes_at_edited_block_when_live_page_matches_recor
}
ctx.verified_prefix_terminal_label = "inspect_summary"
- labels, _seed, frontier = _plan_frontier(
+ labels, _seed, frontier, _provenance = _plan_frontier(
ctx,
_LOGIN_THEN_INSPECT_LABELS,
old,
@@ -669,7 +678,7 @@ def test_plan_frontier_edit_walks_back_when_a_loop_hides_a_credential_fill() ->
ctx.verified_prefix_block_end_urls = {"open_site": "https://app.example.com/signin"}
ctx.verified_prefix_terminal_label = "retry_login"
- _labels, _seed, frontier = _plan_frontier(
+ _labels, _seed, frontier, _provenance = _plan_frontier(
ctx,
["open_site", "retry_login"],
old,
@@ -691,7 +700,7 @@ def test_plan_frontier_resume_names_the_browser_that_must_run_it() -> None:
ctx.verified_prefix_terminal_label = "inspect_summary"
ctx.verified_prefix_block_end_session_id = "pbs_login_run"
- _labels, _seed, frontier = _plan_frontier(
+ _labels, _seed, frontier, _provenance = _plan_frontier(
ctx,
_LOGIN_THEN_INSPECT_LABELS,
old,
@@ -722,7 +731,7 @@ def test_plan_frontier_append_names_the_browser_that_ran_the_prefix() -> None:
ctx.verified_prefix_block_end_session_id = "pbs_login_run"
ctx.verified_prefix_terminal_label = "login_to_site"
- _labels, _seed, frontier = _plan_frontier(
+ _labels, _seed, frontier, _provenance = _plan_frontier(
ctx,
["open_site", "login_to_site", "read_total"],
old,
@@ -755,7 +764,7 @@ def test_plan_frontier_does_not_name_a_browser_when_the_seeder_vetoes_the_fronti
ctx.verified_prefix_block_end_session_id = "pbs_login_run"
ctx.verified_prefix_terminal_label = "read_total"
- labels, _seed, frontier = _plan_frontier(
+ labels, _seed, frontier, _provenance = _plan_frontier(
ctx,
labels_in_order,
_definition("result = 1"),
@@ -777,7 +786,7 @@ def test_plan_frontier_edit_walks_back_when_live_page_left_the_recorded_anchor()
ctx.verified_block_outputs = {"open_site": "ok", "login_to_site": "ok"}
ctx.verified_prefix_block_end_urls = {"login_to_site": "https://app.example.com/dashboard"}
- labels, _seed, frontier = _plan_frontier(
+ labels, _seed, frontier, _provenance = _plan_frontier(
ctx,
_LOGIN_THEN_INSPECT_LABELS,
old,
@@ -794,7 +803,7 @@ def test_plan_frontier_edit_walks_back_when_no_anchor_was_recorded() -> None:
ctx.verified_prefix_labels = list(_LOGIN_THEN_INSPECT_LABELS)
ctx.verified_block_outputs = {"open_site": "ok", "login_to_site": "ok"}
- _labels, _seed, frontier = _plan_frontier(
+ _labels, _seed, frontier, _provenance = _plan_frontier(
ctx,
_LOGIN_THEN_INSPECT_LABELS,
old,
@@ -826,7 +835,7 @@ def test_plan_frontier_edit_walks_back_when_only_the_spa_route_fragment_matches(
ctx.verified_block_outputs = {"open_site": "ok", "login_to_site": "ok"}
ctx.verified_prefix_block_end_urls = {"login_to_site": "https://app.example.com/#/dashboard"}
- _labels, _seed, frontier = _plan_frontier(
+ _labels, _seed, frontier, _provenance = _plan_frontier(
ctx,
_LOGIN_THEN_INSPECT_LABELS,
old,
@@ -856,7 +865,7 @@ def test_plan_frontier_edit_walks_back_when_the_browser_ran_past_the_edited_bloc
ctx.verified_prefix_block_end_urls = dict.fromkeys(labels_in_order, "https://app.example.com/")
ctx.verified_prefix_terminal_label = "checkout"
- labels, _seed, frontier = _plan_frontier(
+ labels, _seed, frontier, _provenance = _plan_frontier(
ctx,
labels_in_order,
_definition("await page.click('#add')"),
@@ -887,7 +896,7 @@ def test_plan_frontier_edit_walks_back_when_the_frontier_would_refill_credential
ctx.verified_block_outputs = {"open_site": "ok"}
ctx.verified_prefix_block_end_urls = {"open_site": "https://app.example.com/signin"}
- _labels, _seed, frontier = _plan_frontier(
+ _labels, _seed, frontier, _provenance = _plan_frontier(
ctx,
["open_site", "login_code"],
old,
@@ -976,7 +985,7 @@ def test_plan_frontier_edit_with_no_upstream_anchor_falls_back_to_full_list() ->
new = _FakeDefinition([_FakeBlock("click", "action", {"selector": "#b"}), _FakeBlock("download", "download_to_s3")])
ctx = _make_ctx()
ctx.verified_prefix_labels = ["click", "download"]
- labels, seed, frontier = _plan_frontier(ctx, ["click", "download"], old, new)
+ labels, seed, frontier, _provenance = _plan_frontier(ctx, ["click", "download"], old, new)
assert labels == ["click", "download"]
assert frontier == "click"
assert seed == {}
@@ -987,7 +996,7 @@ def test_plan_frontier_without_verified_prefix_falls_back_to_full() -> None:
new = _FakeDefinition([_FakeBlock("a", "navigation"), _FakeBlock("b", "extraction", {"prompt": "changed"})])
ctx = _make_ctx()
# No verified_prefix_labels — previous run must have failed.
- labels, _seed, frontier = _plan_frontier(ctx, ["a", "b"], old, new)
+ labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["a", "b"], old, new)
assert labels == ["a", "b"]
assert frontier == "a"
@@ -995,7 +1004,7 @@ def test_plan_frontier_without_verified_prefix_falls_back_to_full() -> None:
def test_plan_frontier_cold_start_no_old_definition_uses_first_requested() -> None:
new = _FakeDefinition([_FakeBlock("a", "navigation")])
ctx = _make_ctx()
- labels, _seed, frontier = _plan_frontier(ctx, ["a"], None, new)
+ labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["a"], None, new)
assert labels == ["a"]
assert frontier == "a"
@@ -1010,7 +1019,7 @@ def test_plan_frontier_ambiguous_diff_falls_back_on_exception(monkeypatch: pytes
new = _FakeDefinition([_FakeBlock("a", "navigation")])
ctx = _make_ctx()
ctx.verified_prefix_labels = ["a"]
- labels, seed, frontier = _plan_frontier(ctx, ["a"], old, new)
+ labels, seed, frontier, _provenance = _plan_frontier(ctx, ["a"], old, new)
assert labels == ["a"]
assert frontier == "a"
assert seed == {}
@@ -1079,7 +1088,7 @@ def test_plan_frontier_append_with_block_form_jinja_ref_falls_back_to_full_run()
"extract_article_info": {"extracted_information": {"abstract": "Prior output"}},
}
- labels, seed, frontier = _plan_frontier(
+ labels, seed, frontier, _provenance = _plan_frontier(
ctx,
["open_page", "extract_article_info", "summarize_article"],
old,
@@ -1121,7 +1130,7 @@ def test_plan_frontier_append_seeds_output_parameter_jinja_ref() -> None:
"extract_article_info": {"extracted_information": {"abstract": "Prior output"}},
}
- labels, seed, frontier = _plan_frontier(
+ labels, seed, frontier, _provenance = _plan_frontier(
ctx,
["open_page", "extract_article_info", "summarize_article"],
old,
@@ -1253,7 +1262,7 @@ def test_plan_frontier_unknown_jinja_root_falls_back_to_full_requested_list() ->
ctx.verified_prefix_labels = ["open_page"]
ctx.verified_block_outputs = {"open_page": "nav_ok"}
- labels, seed, frontier = _plan_frontier(ctx, ["open_page", "summarize_article"], old, new)
+ labels, seed, frontier, _provenance = _plan_frontier(ctx, ["open_page", "summarize_article"], old, new)
assert labels == ["open_page", "summarize_article"]
assert seed == {}
@@ -1293,7 +1302,7 @@ def test_plan_frontier_falls_back_when_unknown_root_coexists_with_seedable_ref()
"extract_article_info": {"extracted_information": {"abstract": "Prior output"}},
}
- labels, seed, frontier = _plan_frontier(
+ labels, seed, frontier, _provenance = _plan_frontier(
ctx,
["open_page", "extract_article_info", "summarize_article"],
old,
@@ -1476,7 +1485,7 @@ def test_plan_frontier_append_only_with_workflow_param_does_not_fall_back() -> N
ctx.verified_prefix_labels = ["open_page"]
ctx.verified_block_outputs = {"open_page": "nav_ok"}
- labels, seed, frontier = _plan_frontier(ctx, ["open_page", "search"], old, new)
+ labels, seed, frontier, _provenance = _plan_frontier(ctx, ["open_page", "search"], old, new)
assert labels == ["search"]
assert seed == {"open_page": "nav_ok"}
@@ -1678,7 +1687,7 @@ def test_plan_frontier_uses_recorded_failed_block_position_for_same_request_orde
workflow_definition=definition,
)
- labels, seed, frontier = _plan_frontier(
+ labels, seed, frontier, _provenance = _plan_frontier(
ctx,
["open", "search", "extract"],
definition,
@@ -1708,7 +1717,7 @@ def test_plan_frontier_maps_recorded_failed_block_by_structure_across_label_chur
workflow_definition=old,
)
- labels, seed, frontier = _plan_frontier(
+ labels, seed, frontier, _provenance = _plan_frontier(
ctx,
["open_new", "search_new", "extract_new"],
old,
@@ -1738,7 +1747,7 @@ def test_plan_frontier_fails_closed_when_recorded_failed_order_differs() -> None
workflow_definition=old,
)
- labels, seed, frontier = _plan_frontier(
+ labels, seed, frontier, _provenance = _plan_frontier(
ctx,
["open_new", "extract_new", "search_new"],
old,
@@ -1768,7 +1777,7 @@ def test_plan_frontier_fails_closed_when_recorded_failed_shapes_are_ambiguous()
workflow_definition=old,
)
- labels, seed, frontier = _plan_frontier(
+ labels, seed, frontier, _provenance = _plan_frontier(
ctx,
["second_new", "first_new", "extract_new"],
old,
@@ -1800,7 +1809,7 @@ def test_plan_frontier_does_not_index_suffix_failed_run_into_full_request() -> N
workflow_definition=old,
)
- labels, seed, frontier = _plan_frontier(
+ labels, seed, frontier, _provenance = _plan_frontier(
ctx,
["open_new", "search_new", "extract_new"],
old,
@@ -1949,7 +1958,7 @@ def test_edit_invalidates_verified_goal_block_on_split_path() -> None:
# Split path: run_blocks passes old==new; the pruned prefix makes the edited
# block the frontier again instead of reusing it as verified.
- labels, _seed, frontier = _plan_frontier(ctx, ["open", "search", "extract"], new, new)
+ labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["open", "search", "extract"], new, new)
assert frontier == "extract"
assert "extract" in labels
@@ -2226,8 +2235,8 @@ def test_fused_and_split_leave_identical_verified_state() -> None:
# Neither the split seam (new, new) nor the fused seam (prior, new) reuses the
# edited block as verified.
- split_labels, _s, _sf = _plan_frontier(split_ctx, ["open", "search", "extract"], new, new)
- fused_labels, _f, _ff = _plan_frontier(fused_ctx, ["open", "search", "extract"], prior, new)
+ split_labels, _s, _sf, _sp = _plan_frontier(split_ctx, ["open", "search", "extract"], new, new)
+ fused_labels, _f, _ff, _fp = _plan_frontier(fused_ctx, ["open", "search", "extract"], prior, new)
assert "extract" in split_labels
assert "extract" in fused_labels
@@ -2329,7 +2338,7 @@ def test_appended_block_output_parameter_keeps_upstream_verified_prefix() -> Non
assert ctx.workflow_verification_evidence.full_workflow_verified is False
assert ctx.last_full_workflow_test_ok is False
- labels, _seed, frontier = _plan_frontier(ctx, ["sign_in", "read_summary"], prior, new)
+ labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["sign_in", "read_summary"], prior, new)
assert labels == ["read_summary"]
assert frontier == "read_summary"
@@ -2518,5 +2527,387 @@ def test_reorder_resets_verified_trust() -> None:
assert ctx.last_full_workflow_test_ok is False
+def test_unanchored_append_is_never_credited_as_composition_verified() -> None:
+ prior = _wf_def(("open", "goto_url", {"url": "https://example.com"}))
+ appended = _wf_def(
+ ("open", "goto_url", {"url": "https://example.com"}),
+ ("add_to_cart", "navigation", {"prompt": "add the item to the cart"}),
+ )
+ ctx = _make_ctx()
+ _seed_verified(ctx, ["open"], current_url="https://example.com/list", full=False)
+ ctx.composition_verified_labels = ["open"]
+
+ labels, _seed, frontier, provenance = _plan_frontier(ctx, ["open", "add_to_cart"], prior, appended)
+
+ assert frontier == "add_to_cart"
+ assert provenance == "unanchored"
+
+ _credit_composition_verified_labels(ctx, labels, provenance)
+
+ assert "add_to_cart" not in ctx.composition_verified_labels
+
+
+def test_a_lone_mid_workflow_block_that_opens_a_page_is_not_a_replay() -> None:
+ prior = _wf_def(("open", "goto_url", {"url": "https://example.com"}))
+ appended = _wf_def(
+ ("open", "goto_url", {"url": "https://example.com"}),
+ ("open_cart", "goto_url", {"url": "https://example.com/cart"}),
+ )
+ ctx = _make_ctx()
+ _seed_verified(ctx, ["open"], current_url="https://example.com/list", full=False)
+ ctx.composition_verified_labels = ["open"]
+ ctx.last_workflow = _FakeWorkflow(appended)
+ ctx.last_workflow_yaml = "workflow: yaml"
+
+ labels, _seed, frontier, provenance = _plan_frontier(ctx, ["open", "open_cart"], prior, appended)
+
+ assert frontier == "open_cart"
+ assert provenance == "unanchored"
+
+ _credit_composition_verified_labels(ctx, labels, provenance)
+
+ assert ctx.composition_verified_labels == ["open"]
+
+
+def test_a_workflow_with_no_resolvable_labels_is_not_vacuously_tested() -> None:
+ assert (
+ terminal_ready_for_latch(
+ current_workflow_labels=[],
+ has_executed_blocks=True,
+ unverified=[],
+ composition_unverified=[],
+ artifact_reason=None,
+ structured_blocker=None,
+ empty_data_blocks=None,
+ )
+ is False
+ )
+ assert (
+ terminal_ready_for_latch(
+ current_workflow_labels=["open"],
+ has_executed_blocks=True,
+ unverified=[],
+ composition_unverified=[],
+ artifact_reason=None,
+ structured_blocker=None,
+ empty_data_blocks=None,
+ )
+ is True
+ )
+
+
+def test_a_run_starting_before_the_credited_boundary_still_earns_credit() -> None:
+ definition = _wf_def(
+ ("open", "goto_url", {"url": "https://example.com"}),
+ ("pick_size", "navigation", {"prompt": "pick a size"}),
+ ("add_to_cart", "navigation", {"prompt": "add the item"}),
+ )
+ ctx = _make_ctx()
+ ctx.last_workflow = _FakeWorkflow(definition)
+ ctx.last_workflow_yaml = "workflow: yaml"
+ ctx.composition_verified_labels = ["open"]
+
+ _credit_composition_verified_labels(ctx, ["open", "pick_size", "add_to_cart"], "initial")
+
+ assert ctx.composition_verified_labels == ["open", "pick_size", "add_to_cart"]
+
+
+def test_a_walk_back_replay_credits_through_its_own_end() -> None:
+ definition = _wf_def(
+ ("open", "goto_url", {"url": "https://example.com"}),
+ ("pick_size", "navigation", {"prompt": "pick a size"}),
+ ("add_to_cart", "navigation", {"prompt": "add the item"}),
+ )
+ ctx = _make_ctx()
+ ctx.last_workflow = _FakeWorkflow(definition)
+ ctx.last_workflow_yaml = "workflow: yaml"
+ ctx.composition_verified_labels = ["open", "pick_size"]
+
+ _credit_composition_verified_labels(ctx, ["pick_size", "add_to_cart"], "replayed")
+
+ assert ctx.composition_verified_labels == ["open", "pick_size", "add_to_cart"]
+
+
+def test_a_non_contiguous_run_credits_no_composition_labels() -> None:
+ definition = _wf_def(
+ ("open", "goto_url", {"url": "https://example.com"}),
+ ("pick_size", "navigation", {"prompt": "pick a size"}),
+ ("add_to_cart", "navigation", {"prompt": "add the item"}),
+ )
+ ctx = _make_ctx()
+ ctx.last_workflow = _FakeWorkflow(definition)
+ ctx.last_workflow_yaml = "workflow: yaml"
+
+ _credit_composition_verified_labels(ctx, ["open", "add_to_cart"], "initial")
+
+ assert ctx.composition_verified_labels == []
+
+
+def test_a_passing_unanchored_run_still_leaves_the_workflow_composition_unverified() -> None:
+ prior = _wf_def(("open", "goto_url", {"url": "https://example.com"}))
+ appended = _wf_def(
+ ("open", "goto_url", {"url": "https://example.com"}),
+ ("add_to_cart", "navigation", {"prompt": "add the item to the cart"}),
+ )
+ ctx = _make_ctx()
+ _seed_verified(ctx, ["open"], current_url="https://example.com/list", full=False)
+ ctx.composition_verified_labels = ["open"]
+ ctx.last_workflow = _FakeWorkflow(appended)
+ ctx.last_workflow_yaml = "workflow: yaml"
+
+ labels, _seed, _frontier, provenance = _plan_frontier(ctx, ["open", "add_to_cart"], prior, appended)
+ _credit_composition_verified_labels(ctx, labels, provenance)
+ ctx.verified_prefix_labels = ["open", "add_to_cart"]
+
+ _record_run_blocks_result(
+ ctx,
+ {
+ "ok": True,
+ "data": {
+ "workflow_run_id": "wr_append",
+ "requested_block_labels": ["add_to_cart"],
+ "executed_block_labels": ["add_to_cart"],
+ "blocks": [{"label": "add_to_cart", "status": "completed", "extracted_data": {"in_cart": True}}],
+ },
+ },
+ )
+
+ assert ctx.last_unverified_block_labels == []
+ assert ctx.last_full_workflow_test_ok is False
+ assert ctx.verified_terminal_proposal_ready is False
+
+
+def test_editing_a_composed_block_truncates_composition_credit_at_that_block() -> None:
+ prior = _wf_def(
+ ("open", "goto_url", {"url": "https://example.com"}),
+ ("extract", "extraction", {"prompt": "grab the total"}),
+ )
+ edited = _wf_def(
+ ("open", "goto_url", {"url": "https://example.com"}),
+ ("extract", "extraction", {"prompt": "grab the grand total"}),
+ )
+ ctx = _make_ctx()
+ _seed_verified(ctx, ["open", "extract"], current_url="https://example.com/cart", full=True)
+ ctx.composition_verified_labels = ["open", "extract"]
+ ctx.verified_prefix_block_end_urls = {
+ "open": "https://example.com/cart",
+ "extract": "https://example.com/cart",
+ }
+ ctx.verified_prefix_block_end_session_id = "pbs_debug"
+ ctx.verified_prefix_terminal_label = "extract"
+
+ _invalidate_verified_state_on_edit(ctx, prior, edited)
+
+ assert ctx.composition_verified_labels == ["open"]
+
+ ctx.verified_prefix_labels = ["open"]
+ ctx.verified_prefix_block_end_urls = {"open": "https://example.com/cart"}
+ ctx.verified_prefix_terminal_label = "open"
+ labels, _seed, frontier, provenance = _plan_frontier(
+ ctx, ["open", "extract"], prior, edited, "https://example.com/cart"
+ )
+
+ assert labels == ["extract"]
+ assert frontier == "extract"
+ assert provenance == "resumed"
+
+ ctx.last_workflow = _FakeWorkflow(edited)
+ ctx.last_workflow_yaml = "workflow: yaml"
+ _credit_composition_verified_labels(ctx, labels, provenance)
+ ctx.verified_prefix_labels = ["open", "extract"]
+
+ _record_run_blocks_result(
+ ctx,
+ {
+ "ok": True,
+ "data": {
+ "workflow_run_id": "wr_edit",
+ "requested_block_labels": ["extract"],
+ "executed_block_labels": ["extract"],
+ "blocks": [{"label": "extract", "status": "completed", "extracted_data": {"total": "12"}}],
+ },
+ },
+ )
+
+ assert ctx.composition_verified_labels == ["open", "extract"]
+ assert ctx.last_full_workflow_test_ok is True
+ assert ctx.verified_terminal_proposal_ready is True
+
+
+def test_a_first_block_that_establishes_no_state_is_not_an_anchored_start() -> None:
+ definition = _wf_def(
+ ("add_to_cart", "task", {"prompt": "add the jacket to the cart"}),
+ ("read_total", "extraction", {"prompt": "grab the total"}),
+ )
+ ctx = _make_ctx()
+ ctx.last_workflow = _FakeWorkflow(definition)
+ ctx.last_workflow_yaml = "workflow: yaml"
+
+ labels, _seed, _frontier, provenance = _plan_frontier(ctx, ["add_to_cart", "read_total"], None, definition)
+
+ assert provenance == "unanchored"
+ _credit_composition_verified_labels(ctx, labels, provenance)
+ assert ctx.composition_verified_labels == []
+
+
+def test_full_workflow_run_from_the_first_block_earns_composition_credit() -> None:
+ definition = _wf_def(
+ ("open", "goto_url", {"url": "https://example.com"}),
+ ("extract", "extraction", {"prompt": "grab the total"}),
+ )
+ ctx = _make_ctx()
+ ctx.last_workflow = _FakeWorkflow(definition)
+ ctx.last_workflow_yaml = "workflow: yaml"
+
+ labels, _seed, frontier, provenance = _plan_frontier(ctx, ["open", "extract"], None, definition)
+
+ assert frontier == "open"
+ assert provenance == "initial"
+
+ _credit_composition_verified_labels(ctx, labels, provenance)
+ ctx.verified_prefix_labels = ["open", "extract"]
+
+ _record_run_blocks_result(
+ ctx,
+ {
+ "ok": True,
+ "data": {
+ "workflow_run_id": "wr_full",
+ "requested_block_labels": ["open", "extract"],
+ "executed_block_labels": ["open", "extract"],
+ "blocks": [
+ {"label": "open", "status": "completed"},
+ {"label": "extract", "status": "completed", "extracted_data": {"total": "12"}},
+ ],
+ },
+ },
+ )
+
+ assert ctx.composition_verified_labels == ["open", "extract"]
+ assert ctx.last_full_workflow_test_ok is True
+
+
+def test_frontier_planning_adds_no_rerun_floor_or_goal_classifier() -> None:
+ definition = _wf_def(
+ ("open", "goto_url", {"url": "https://example.com"}),
+ ("extract", "extraction", {"prompt": "grab the total"}),
+ )
+ ctx = _make_ctx()
+ _seed_verified(ctx, ["open"], current_url="https://example.com/list", full=False)
+
+ labels, _seed, frontier, _provenance = _plan_frontier(ctx, ["open", "extract"], definition, definition)
+
+ assert labels == ["extract"]
+ assert frontier == "extract"
+
+
if __name__ == "__main__":
pytest.main([__file__, "-v"])
+
+
+async def test_test_end_to_end_runs_every_label_from_a_run_owned_browser(monkeypatch: pytest.MonkeyPatch) -> None:
+ definition = _wf_def(
+ ("open", "goto_url", {"url": "https://example.com"}),
+ ("add_to_cart", "task", {"prompt": "add the jacket"}),
+ )
+ captured: dict[str, Any] = {}
+
+ async def _fake_process(**kwargs: Any) -> _FakeWorkflow:
+ return _FakeWorkflow(definition)
+
+ async def _fake_run(
+ params: dict[str, Any],
+ ctx: CopilotContext,
+ *,
+ labels_to_execute: list[str] | None = None,
+ block_outputs_to_seed: dict[str, Any] | None = None,
+ frontier_start_label: str | None = None,
+ force_fresh_session: bool = False,
+ definition_unpersisted: bool = False,
+ outside_turn_deadline: bool = False,
+ ) -> dict[str, Any]:
+ captured["requested"] = list(params["block_labels"])
+ captured["definition_unpersisted"] = definition_unpersisted
+ captured["executed"] = list(labels_to_execute or [])
+ captured["frontier_start_label"] = frontier_start_label
+ captured["force_fresh_session"] = force_fresh_session
+ captured["outside_turn_deadline"] = outside_turn_deadline
+ captured["provenance"] = ctx.frontier_start_provenance or "unanchored"
+ return {"ok": True, "data": {}}
+
+ async def _fake_verify(copilot_ctx: Any, result: dict[str, Any], handler_start: float) -> None:
+ return None
+
+ monkeypatch.setattr(run_execution_module, "_process_workflow_yaml", _fake_process)
+ monkeypatch.setattr(run_execution_module, "_run_blocks_and_collect_debug", _fake_run)
+ monkeypatch.setattr(run_execution_module, "_verify_and_record_run_blocks_result", _fake_verify)
+
+ ctx = _make_ctx()
+ ctx.verified_prefix_labels = ["open", "add_to_cart"]
+ ctx.composition_verified_labels = []
+
+ await run_workflow_end_to_end(ctx, "workflow: yaml")
+
+ assert captured["requested"] == ["open", "add_to_cart"]
+ assert captured["executed"] == ["open", "add_to_cart"]
+ assert captured["frontier_start_label"] == "open"
+ assert captured["force_fresh_session"] is True
+ assert captured["definition_unpersisted"] is True
+ assert captured["outside_turn_deadline"] is True
+ assert captured["provenance"] == "initial"
+
+
+def test_test_end_to_end_provenance_earns_composition_credit_and_flips_the_latch() -> None:
+ definition = _wf_def(
+ ("open", "goto_url", {"url": "https://example.com"}),
+ ("add_to_cart", "task", {"prompt": "add the jacket"}),
+ )
+ ctx = _make_ctx()
+ ctx.last_workflow = _FakeWorkflow(definition)
+ ctx.last_workflow_yaml = "workflow: yaml"
+ labels = ["open", "add_to_cart"]
+
+ _credit_composition_verified_labels(ctx, labels, "initial")
+ ctx.verified_prefix_labels = list(labels)
+
+ _record_run_blocks_result(
+ ctx,
+ {
+ "ok": True,
+ "data": {
+ "workflow_run_id": "wr_e2e",
+ "requested_block_labels": labels,
+ "executed_block_labels": labels,
+ "blocks": [
+ {"label": "open", "status": "completed"},
+ {"label": "add_to_cart", "status": "completed", "extracted_data": {"in_cart": True}},
+ ],
+ },
+ },
+ )
+
+ assert ctx.composition_verified_labels == labels
+ assert ctx.verified_terminal_proposal_ready is True
+ assert ctx.last_full_workflow_test_ok is True
+ # The proposal the turn surfaces is what moves the review gate onto this turn, so a clean
+ # end-to-end run is what repaints the pill.
+ assert _verified_workflow_or_none(ctx) == (ctx.last_workflow, ctx.last_workflow_yaml)
+
+
+async def test_test_end_to_end_will_not_touch_the_browser_after_a_raw_secret(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def _unreachable(*args: Any, **kwargs: Any) -> dict[str, Any]:
+ raise AssertionError("the browser must not be reached on a raw-secret turn")
+
+ monkeypatch.setattr(run_execution_module, "_process_workflow_yaml", _unreachable)
+ monkeypatch.setattr(run_execution_module, "_run_blocks_and_collect_debug", _unreachable)
+
+ ctx = _make_ctx()
+ ctx.request_policy = RequestPolicy(raw_secret_detected=True, raw_secret_handling="redacted_draft")
+
+ result = await run_workflow_end_to_end(ctx, "workflow: yaml")
+
+ assert result["ok"] is False
diff --git a/tests/unit/test_copilot_run_outcome_event.py b/tests/unit/test_copilot_run_outcome_event.py
index 412cdcf6a..003e275c0 100644
--- a/tests/unit/test_copilot_run_outcome_event.py
+++ b/tests/unit/test_copilot_run_outcome_event.py
@@ -155,6 +155,7 @@ def _ctx(blocks: list[dict[str, Any]] | None = None) -> CopilotContext:
ctx.last_workflow = SimpleNamespace(workflow_definition=SimpleNamespace(blocks=workflow_blocks)) # type: ignore[assignment]
ctx.last_workflow_yaml = "blocks: []"
ctx.verified_prefix_labels = labels
+ ctx.composition_verified_labels = list(labels)
ctx.last_run_blocks_block_ids = [f"wrb_{label}" for label in labels]
ctx.last_run_blocks_block_labels = labels
return ctx
diff --git a/tests/unit/test_copilot_run_output_content_gate.py b/tests/unit/test_copilot_run_output_content_gate.py
index 02aa4148f..4d2535198 100644
--- a/tests/unit/test_copilot_run_output_content_gate.py
+++ b/tests/unit/test_copilot_run_output_content_gate.py
@@ -137,6 +137,7 @@ def _ctx(blocks: list[dict[str, Any]] | None = None) -> CopilotContext:
ctx.last_workflow = SimpleNamespace(workflow_definition=SimpleNamespace(blocks=workflow_blocks)) # type: ignore[assignment]
ctx.last_workflow_yaml = "blocks: []"
ctx.verified_prefix_labels = labels
+ ctx.composition_verified_labels = list(labels)
return ctx
diff --git a/tests/unit/test_llm_response_parsing.py b/tests/unit/test_llm_response_parsing.py
index 2493379c8..a0340b5fb 100644
--- a/tests/unit/test_llm_response_parsing.py
+++ b/tests/unit/test_llm_response_parsing.py
@@ -96,9 +96,22 @@ def test_dict_with_own_actions_key_is_not_overridden_by_nested_list():
assert _coerce_response_to_dict([own, stray]) == own
-def test_two_reasoning_dicts_plus_action_list_keeps_first_dict():
+def test_stray_fragments_between_preamble_and_action_list_still_reattach():
+ # An unescaped quote inside `thoughts` ends that string early, so the rest of
+ # the reasoning text is stranded as extra top-level fragments sitting between
+ # the preamble and the action array.
+ preamble = {"page_info": "p1", "thoughts": "OCR output is `{'document_category': 'BILLING INVOICE'"}
+ dict_fragment = {"document_category": "BILLING INVOICE", "customer_number": "0206556463"}
+ list_fragment = ["0206556463"]
+ actions = [{"action_type": "COMPLETE", "reasoning": "done", "confidence_float": 1.0}]
+ expected = {**preamble, "actions": actions}
+ assert _coerce_response_to_dict([preamble, dict_fragment, actions], "decisive-criterion-validate") == expected
+ assert _coerce_response_to_dict([preamble, list_fragment, actions], "decisive-criterion-validate") == expected
+
+
+def test_later_dict_carrying_action_type_keeps_first_dict():
first = {"page_info": "p1"}
- second = {"thoughts": "t2"}
+ second = {"action_type": "TERMINATE", "reasoning": "competing decision"}
actions = [{"action_type": "COMPLETE", "reasoning": "done"}]
assert _coerce_response_to_dict([first, second, actions]) == first