fix(runner): repair native connection continuations and tool evidence

Preserve authenticated Claude asset-path rotation, reject duplicate tool-action approvals, await durable service continuation dispatch, and retain OpenCode tool failures through the runner facade.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-07 01:19:08 -05:00
1 parent 162cc90fda
commit a704a0b912
15 files changed
+468 -16

No files matched your search

@@ -34,12 +34,46 @@ The historical Everyday fixture and prompts remain unchanged. The new fixture an
## Validation and remaining gate ## Validation and remaining gate
Credential-free checks pass: eval typecheck; 1,801 support tests plus 128 Node tests (one intentional support skip); 51 connection/schema tests; one real-server fixture test; one focused Rust feedback test; and local browser wrong-task/title calibration. Repository typecheck and build pass. The full repository test run is still under inspection after Telegram and workspace-runtime integration tests failed outside the changed paths. No full local pass is claimed. Credential-free checks pass: eval typecheck; 1,801 support tests plus 128 Node tests (one intentional support skip); 51 connection/schema tests; one real-server fixture test; one focused Rust feedback test; and local browser wrong-task/title calibration. Repository typecheck and build pass. The full local repository test run was stopped after five failures outside the changed paths; those five passed in a separate focused invocation. The full run is incomplete, not passing, and the original failures remain retained. Exact-head normal CI at `162cc90fdabe7f505b88ae095044531b82784c92` passed (52 successful checks, four intentional skips, separate Snyk success); its fresh review completed 5/5.
A corrected paid baseline is pending. Run an explicit provider-choice canary first, then the other distinct cells only after that evidence is usable. Preserve every attempt, decision, actual run, cost gap and failure. No instruction reduction or general integration quality claim is qualified yet. The corrected Codex provider-choice canary passed before the other 14 distinct cells were dispatched. The completed corrected baseline is **10 PASS / 5 FAIL**, with further continuation defects described below. It is not ready to qualify an instruction reduction. Preserve every attempt, decision, actual run, cost gap and failure. No instruction reduction or general integration quality claim is qualified yet.
## Initial corrected campaign stopped before provider execution ## Initial corrected campaign stopped before provider execution
[Campaign 37574251834](https://github.com/paperclipai/paperclip/actions/runs/37574251834) resolved source `cbf1c4fba8eabbf779435f550c455f6a66c5aae5` on trusted master workflow `99a9de9940bf5974352d9dbfbb2f21e62e89689f`. It was cancelled during the shared build after review identified another browser precondition defect. The matrix job has no steps and no runner execution; no provider cell or behavioral grade occurred. Preserve this cancelled campaign separately. [Campaign 37574251834](https://github.com/paperclipai/paperclip/actions/runs/37574251834) resolved source `cbf1c4fba8eabbf779435f550c455f6a66c5aae5` on trusted master workflow `99a9de9940bf5974352d9dbfbb2f21e62e89689f`. It was cancelled during the shared build after review identified another browser precondition defect. The matrix job has no steps and no runner execution; no provider cell or behavioral grade occurred. Preserve this cancelled campaign separately.
The initial stable-ID check assumed whitespace around the identifier. The real breadcrumb uses adjacent title/identifier spans. A regression reproduces the failure with `Renamed taskRUN-1`; the corrected check targets the visible identifier element under the current breadcrumb and matches its text exactly. All five browser checks now pass, including wrong route, wrong/partial identifier and an identifier present only in the mutable title or elsewhere on the page. Seven focused suite checks and eval typecheck pass. This review correction changes only browser support and this report; production logic is unchanged. The initial stable-ID check assumed whitespace around the identifier. The real breadcrumb uses adjacent title/identifier spans. A regression reproduces the failure with `Renamed taskRUN-1`; the corrected check targets the visible identifier element under the current breadcrumb and matches its text exactly. All five browser checks now pass, including wrong route, wrong/partial identifier and an identifier present only in the mutable title or elsewhere on the page. Seven focused suite checks and eval typecheck pass. This review correction changes only browser support and this report; production logic is unchanged.
## Continuation failures exposed by the corrected baseline
Frozen measured source: `162cc90fdabe7f505b88ae095044531b82784c92`; trusted workflow: `99a9de9940bf5974352d9dbfbb2f21e62e89689f`. These results do not retroactively change the original baseline.
- [Codex provider-second canary 37575158761](https://github.com/paperclipai/paperclip/actions/runs/37575158761): PASS, 17/17 checks, three actual succeeded runs. The saved Arcade choice, separate exact HubSpot access approval, one authorized provider call, persisted Ada Fixture response and actual verification marker all pass. No harness retry. Cleanup and both budget readbacks pass.
- [Remaining 14 distinct cells, campaign 37576261807](https://github.com/paperclipai/paperclip/actions/runs/37576261807): preserve every first-attempt original grade. Claude provider-decline and provider-second fail after the saved choice on `run.attach`: their run-scoped instruction working-copy path changes while runtime content identity is unchanged. This is not evidence for the unrelated old missing-final failure.
- Claude service-approve executes the approved service call, then the evaluator fails fast in the gap between the first blocked run finalizing and its continuation appearing. The final ledger retains a second run that starts and is cancelled by cleanup. The earlier workflow snapshot misses it; count both records and do not claim the continuation behavior passed.
- Codex service-approve executes the approved call, but a yielded result requests another human approval for the same referenced card. Finalization materializes a redundant completion-review card. The original FAIL is retained.
The corrected fifteen-cell result is:
| Profile | Connection decline | Provider decline | Provider second | Service approve | Service decline |
| --- | --- | --- | --- | --- | --- |
| Codex | PASS | PASS | PASS (separate canary) | FAIL | PASS |
| ACPX Claude | PASS | FAIL | FAIL | FAIL | PASS |
| OpenCode | PASS | PASS | FAIL | PASS | PASS |
OpenCode provider-second saved both the Arcade choice and the exact access grant. Gateway discovery occurred twice, but the fixture observed zero HubSpot calls. The third run reached the existing deadline without a final answer. The facade was dropping canonical tool events, so retained outer logs cannot establish the exact tool-rejection cause. This is a real incomplete workflow; do not infer its cause from the model's self-diagnosis or treat a larger timeout as a fix.
The final ledgers contain **31 actual runs: 27 succeeded, two failed, two cancelled during cleanup**. Earlier polling counted 30; the final Claude service-approve ledger adds a late continuation absent from its workflow snapshot. Its API snapshot has that run queued, and its final ledger records start and cancellation. OpenCode's third run is running in the failure snapshot and cancelled in the final ledger. Preserve these capture-time differences. All result/API/final-ledger run-ID sets agree; Claude service-approve's earlier workflow run set does not. All fifteen cleanup and 1,000-cent company/agent readbacks pass, and all attempts are first attempts with no harness retries. The independent local audit retains 279 evidence-file hashes, source/suite/model/attempt identities and original grades. The [remaining campaign's original public report](https://d1p6rlowie26tp.cloudfront.net/runner-e2e/campaigns/gha-37576261807-1/index.html) is accessible (HTTP 200).
Recorded LLM subtotal for the corrected fifteen cells is **$0.04553787**, with incomplete token/cost coverage. Only OpenCode reports positive amounts. Codex/Claude zeros have unknown billing type, invoices are unknown, and local/hosted runtime is unmetered. Count the cancelled continuations as actual executions; do not describe zero reports as free.
The next source correction admits only Claude's authenticated registered-copy path rotation while preserving prompt/custom-entry bytes, content identities, model, permissions, session and lifecycle guards. TypeScript/Rust shared fixtures bind the exact canonical asset suffix. It rejects stale paths and changed custom text instead of replacing arbitrary path strings. Cursor's separate authenticated run-grant policy is unchanged.
Completion feedback rejects a duplicate human-approval request when a response-wake result references this exact run/agent/task's tool-action card. A resolved reference instructs the agent to inspect the recorded result without repeating the call. Unrelated reviews and other runs' cards are not silently dismissed. The evaluator waits for the specifically recorded executed-action continuation within its existing deadline; a consumed response followed by another blocker still fails. No expected outcome, service-call limit, approval requirement, overall deadline, automatic retry policy or paid prompt is relaxed.
Provider-free regression evidence: the original Claude reattachment error and duplicate approval acceptance both reproduce before their fixes. Nine Rust attachment checks (including cross-language suffix parity), 127 ACPX runtime/adapter checks, 33 completion/control-plane tests, 1,802 evaluator support tests plus 128 Node tests pass; one support skip is intentional. New live qualification is still required for these source changes. Recorded zero costs do not establish free calls or complete billing; runtime and actual invoices remain unknown.
The OpenCode repair forwards bounded tool start/progress/completion events through the existing provider facade, retaining the actual execution-part identity, tool name, status and provider-visible result. It does not invent a host-call-ID join, expose tool arguments, or change the model prompt, permissions, tool catalog, timeouts or grading. A real bundled-proxy regression emits an invalid-tool failure: the old forwarding path drops all three events, and the repaired path retains all three. Runnerd normalizes builtin tool activity and preserves the error while redacting secret patterns. The output digest describes the bounded forwarded result, not an unretained full provider payload. This closes an evidence gap; it does not establish the old OpenCode failure's cause or claim its behavior fixed.
New local verification also passes repository typecheck and build, nine continuation deadline tests, 59 OpenCode driver/proxy checks and the focused Rust tool-error/redaction check. The earlier interrupted full repository suite remains incomplete; current-source full CI and live canaries remain required. The next paid selection is bounded to Claude provider-decline (restart repair), Codex service-approve (duplicate approval repair), and OpenCode provider-second (one diagnostic attempt with repaired evidence). Other failed cells wait for usable canary evidence. Preserve all old outcomes, frozen aliases and costs.
@@ -183,6 +183,71 @@ fn runtime_context_session_identity(context: &Value) -> Option<Value> {
Some(identity) Some(identity)
} }
// Mirrors only the canonical asset suffix from composeNativeSystemInstructions.
// No replacement is allowed inside the prompt or a user's custom entry.
fn registered_asset_suffix(context: &Value) -> Option<String> {
let instructions = context.get("instructions")?;
let root = instructions.pointer("/bundle/rootPath")?.as_str()?;
if root.is_empty() {
return None;
}
let mut blocks = Vec::new();
if let Some(copy) = instructions
.get("workingCopy")
.filter(|value| !value.is_null())
{
let path = copy.get("rootPath")?.as_str()?;
let entry = copy.get("entryPath")?.as_str()?;
if path.is_empty() || entry.is_empty() {
return None;
}
blocks.push(if copy.get("kind").and_then(Value::as_str) == Some("agent_files") {
format!("Your persistent agent directory (AGENT_HOME) is {path}. Your instruction entry is {entry}, relative to that directory. All supported files and subfolders there are restored across tasks and sessions, and collected after this provider stops. Write task deliverables in the task working directory. Only changed or deleted files synchronize; the last sync wins for the same file. Temporary copies are cleaned up without retaining file history. Check the save receipt before claiming persistence.")
} else {
format!("Your editable agent instruction file is {path}/{entry}. Edit this registered private copy normally. After this run stops, Paperclip saves changed content as a persistent revision if your responsible user still has permission and the baseline has not changed. Check the run's instruction-save receipt before claiming persistence. Conflicts are preserved for explicit resolution. Repository instruction files, skills, and this run's loaded prompt are separate and are not collected.")
});
}
blocks.push(format!("Read-only instruction sibling root: {root}"));
Some(blocks.join("\n\n"))
}
fn only_registered_asset_text_changed(
current: &AcpxProviderDescriptor,
prior: &AcpxProviderDescriptor,
) -> bool {
if current.instructions == prior.instructions
&& current
.runtime_context
.pointer("/instructions/workingCopy/rootPath")
== prior
.runtime_context
.pointer("/instructions/workingCopy/rootPath")
&& current
.runtime_context
.pointer("/instructions/bundle/rootPath")
== prior
.runtime_context
.pointer("/instructions/bundle/rootPath")
{
return true;
}
let Some(current_suffix) = registered_asset_suffix(&current.runtime_context) else {
return false;
};
let Some(prior_suffix) = registered_asset_suffix(&prior.runtime_context) else {
return false;
};
current
.instructions
.strip_suffix(&format!("\n\n{current_suffix}"))
.zip(
prior
.instructions
.strip_suffix(&format!("\n\n{prior_suffix}")),
)
.is_some_and(|(current_prefix, prior_prefix)| current_prefix == prior_prefix)
}
impl AcpxProviderDescriptor { impl AcpxProviderDescriptor {
fn validate_session( fn validate_session(
&self, &self,
@@ -1055,7 +1120,8 @@ impl AcpxCommandExecutor {
object.remove("aggregateDigest"); object.remove("aggregateDigest");
} }
} }
if run_attachment_policy(&descriptor.agent) == RunAttachmentPolicy::AuthenticatedRunGrants { let attachment_policy = run_attachment_policy(&descriptor.agent);
if attachment_policy != RunAttachmentPolicy::ImmutableInstructions {
// New runs rotate authenticated instruction text and registered // New runs rotate authenticated instruction text and registered
// file-copy grants. Preserve mainline MCP refresh while comparing // file-copy grants. Preserve mainline MCP refresh while comparing
// every remaining context identity, including unknown policy fields. // every remaining context identity, including unknown policy fields.
@@ -1066,7 +1132,12 @@ impl AcpxCommandExecutor {
.is_some_and(|(current, prior)| current == prior); .is_some_and(|(current, prior)| current == prior);
let grants_changed = descriptor.instructions != state.descriptor.instructions let grants_changed = descriptor.instructions != state.descriptor.instructions
|| descriptor.runtime_context != state.descriptor.runtime_context; || descriptor.runtime_context != state.descriptor.runtime_context;
if !compatible || (grants_changed && descriptor.run_id == state.descriptor.run_id) { let text_compatible = attachment_policy == RunAttachmentPolicy::AuthenticatedRunGrants
|| only_registered_asset_text_changed(&descriptor, &state.descriptor);
if !compatible
|| !text_compatible
|| (grants_changed && descriptor.run_id == state.descriptor.run_id)
{
return Err(DurableRunnerError::invalid( return Err(DurableRunnerError::invalid(
"ACPX run.attach changed runtime context outside a new authenticated run", "ACPX run.attach changed runtime context outside a new authenticated run",
)); ));
@@ -2953,6 +3024,30 @@ mod tests {
fs::remove_dir_all(directory).unwrap(); fs::remove_dir_all(directory).unwrap();
} }
#[test]
fn attachment_asset_suffix_matches_typescript_composer() {
let fixtures: Value = serde_json::from_str(include_str!(
"../../../../test/fixtures/registered-asset-instructions.json"
))
.unwrap();
for fixture in fixtures.as_array().unwrap() {
let suffix = registered_asset_suffix(&fixture["context"]).unwrap();
assert_eq!(
fixture["instructions"]
.as_str()
.unwrap()
.strip_suffix(&format!("\n\n{suffix}")),
Some(
format!(
"Pinned prompt.\n\n{}\n\nPinned connection policy.",
fixture["entry"].as_str().unwrap()
)
.as_str()
)
);
}
}
#[cfg(unix)] #[cfg(unix)]
#[test] #[test]
fn restores_settled_session_for_explicit_run_attachment_only() { fn restores_settled_session_for_explicit_run_attachment_only() {
@@ -3157,6 +3252,17 @@ mod tests {
#[cfg(unix)] #[cfg(unix)]
#[test] #[test]
fn cursor_attachment_rotates_only_authenticated_run_grants() { fn cursor_attachment_rotates_only_authenticated_run_grants() {
authenticated_run_grant_attachment("cursor");
}
#[cfg(unix)]
#[test]
fn claude_attachment_rotates_only_authenticated_asset_paths() {
authenticated_run_grant_attachment("claude");
}
#[cfg(unix)]
fn authenticated_run_grant_attachment(agent: &str) {
let directory = temporary_directory("cursor-cross-run-attach"); let directory = temporary_directory("cursor-cross-run-attach");
let runtime = directory.join("runtime"); let runtime = directory.join("runtime");
let workspace = directory.join("workspace"); let workspace = directory.join("workspace");
@@ -3177,7 +3283,7 @@ mod tests {
args: Vec::new(), args: Vec::new(),
artifacts: vec![artifact(&command)], artifacts: vec![artifact(&command)],
}; };
let mut descriptor_value = descriptor("cursor"); let mut descriptor_value = descriptor(agent);
descriptor_value["sidecarCommand"] = json!(command); descriptor_value["sidecarCommand"] = json!(command);
descriptor_value["runtimeContext"] = json!({ "instructions": { "digest": "stable" }, "mcp": { "digest": "before" }, "aggregateDigest": "before" }); descriptor_value["runtimeContext"] = json!({ "instructions": { "digest": "stable" }, "mcp": { "digest": "before" }, "aggregateDigest": "before" });
descriptor_value["sidecarArgs"] = json!([]); descriptor_value["sidecarArgs"] = json!([]);
@@ -3203,6 +3309,12 @@ mod tests {
"mcp": {"assignmentSetId": "assignment-1", "digest": "e".repeat(64), "bindingId": "old-run-binding"}, "mcp": {"assignmentSetId": "assignment-1", "digest": "e".repeat(64), "bindingId": "old-run-binding"},
"futurePolicy": {"companyId": "company-1"}, "futurePolicy": {"companyId": "company-1"},
}); });
if agent == "claude" {
descriptor_value["instructions"] = json!(format!(
"Pinned prompt. Custom entry mentioning /old-bundle.\n\n{}",
registered_asset_suffix(&descriptor_value["runtimeContext"]).unwrap()
));
}
let original_descriptor: AcpxProviderDescriptor = let original_descriptor: AcpxProviderDescriptor =
serde_json::from_value(descriptor_value.clone()).unwrap(); serde_json::from_value(descriptor_value.clone()).unwrap();
let identity = AcpxProviderSessionIdentity { let identity = AcpxProviderSessionIdentity {
@@ -3330,6 +3442,52 @@ mod tests {
json!("/new-bundle"); json!("/new-bundle");
descriptor_value["runtimeContext"]["skills"][0]["bundle"]["rootPath"] = json!("/new-skill"); descriptor_value["runtimeContext"]["skills"][0]["bundle"]["rootPath"] = json!("/new-skill");
descriptor_value["runtimeContext"]["mcp"]["bindingId"] = json!("new-run-binding"); descriptor_value["runtimeContext"]["mcp"]["bindingId"] = json!("new-run-binding");
if agent == "claude" {
descriptor_value["instructions"] = json!(format!(
"Pinned prompt. Custom entry mentioning /old-bundle.\n\n{}",
registered_asset_suffix(&descriptor_value["runtimeContext"]).unwrap()
));
let mut stale_text = descriptor_value.clone();
stale_text["instructions"] =
json!(original.state.as_ref().unwrap().descriptor.instructions);
assert!(attached
.attach_run(&json!({"provider": stale_text}))
.is_err());
let mut changed_text = descriptor_value.clone();
changed_text["instructions"] = json!(descriptor_value["instructions"]
.as_str()
.unwrap()
.replace("Custom entry", "Changed entry"));
assert!(attached
.attach_run(&json!({"provider": changed_text}))
.is_err());
// A path inside the custom entry is content, not a relocatable grant.
let mut changed_example = descriptor_value.clone();
changed_example["instructions"] = json!(descriptor_value["instructions"]
.as_str()
.unwrap()
.replace("mentioning /old-bundle", "mentioning /new-bundle"));
assert!(attached
.attach_run(&json!({"provider": changed_example}))
.is_err());
for pointer in [
"/prompt/digest",
"/instructions/bundle/digest",
"/skills/0/bundle/digest",
"/futurePolicy/companyId",
] {
let mut changed_identity = descriptor_value.clone();
*changed_identity["runtimeContext"]
.pointer_mut(pointer)
.unwrap() = json!("changed");
assert!(
attached
.attach_run(&json!({"provider": changed_identity}))
.is_err(),
"{pointer}"
);
}
}
attached attached
.attach_run(&json!({"provider": descriptor_value})) .attach_run(&json!({"provider": descriptor_value}))
.unwrap(); .unwrap();
@@ -6,11 +6,13 @@
pub(crate) enum RunAttachmentPolicy { pub(crate) enum RunAttachmentPolicy {
ImmutableInstructions, ImmutableInstructions,
AuthenticatedRunGrants, AuthenticatedRunGrants,
AuthenticatedAssetPaths,
} }
pub(crate) fn run_attachment_policy(agent: &str) -> RunAttachmentPolicy { pub(crate) fn run_attachment_policy(agent: &str) -> RunAttachmentPolicy {
match agent { match agent {
"cursor" => RunAttachmentPolicy::AuthenticatedRunGrants, "cursor" => RunAttachmentPolicy::AuthenticatedRunGrants,
"claude" => RunAttachmentPolicy::AuthenticatedAssetPaths,
_ => RunAttachmentPolicy::ImmutableInstructions, _ => RunAttachmentPolicy::ImmutableInstructions,
} }
} }
@@ -25,7 +27,11 @@ mod tests {
run_attachment_policy("cursor"), run_attachment_policy("cursor"),
RunAttachmentPolicy::AuthenticatedRunGrants RunAttachmentPolicy::AuthenticatedRunGrants
); );
for agent in ["claude", "codex", "grok", "pi", "copilot", "unknown"] { assert_eq!(
run_attachment_policy("claude"),
RunAttachmentPolicy::AuthenticatedAssetPaths
);
for agent in ["codex", "grok", "pi", "copilot", "unknown"] {
assert_eq!( assert_eq!(
run_attachment_policy(agent), run_attachment_policy(agent),
RunAttachmentPolicy::ImmutableInstructions RunAttachmentPolicy::ImmutableInstructions
@@ -875,7 +875,7 @@ pub fn normalize_codex_notification(method: &str, params: &Value) -> Vec<Normali
"text": bounded_text(string(params.get("delta")), MAX_TEXT_CHARS), "text": bounded_text(string(params.get("delta")), MAX_TEXT_CHARS),
}), }),
), ),
"item/started" | "item/completed" => { "item/started" | "item/updated" | "item/completed" => {
let provider_item = item(params); let provider_item = item(params);
let item_id = stable_id(string(provider_item.get("id")), "codex-item"); let item_id = stable_id(string(provider_item.get("id")), "codex-item");
let item_type = string(provider_item.get("type")); let item_type = string(provider_item.get("type"));
@@ -883,12 +883,12 @@ pub fn normalize_codex_notification(method: &str, params: &Value) -> Vec<Normali
let completed = method == "item/completed"; let completed = method == "item/completed";
if matches!( if matches!(
item_type, item_type,
"commandExecution" | "mcpToolCall" | "dynamicToolCall" "commandExecution" | "mcpToolCall" | "dynamicToolCall" | "builtinToolCall"
) { ) {
let mut payload = json!({ let mut payload = json!({
"schema": "paperclip.tool.execution.v1", "schema": "paperclip.tool.execution.v1",
"executionId": item_id, "executionId": item_id,
"transport": match item_type { "mcpToolCall" => "mcp", "dynamicToolCall" => "dynamic", _ => "process" }, "transport": match item_type { "mcpToolCall" => "mcp", "dynamicToolCall" => "dynamic", "builtinToolCall" => "builtin", _ => "process" },
"operation": if item_type == "commandExecution" { "execute" } else { "unknown" }, "operation": if item_type == "commandExecution" { "execute" } else { "unknown" },
"name": provider_item.get("tool").or_else(|| provider_item.get("command")).and_then(Value::as_str).map(|value| bounded_text(value, 240)), "name": provider_item.get("tool").or_else(|| provider_item.get("command")).and_then(Value::as_str).map(|value| bounded_text(value, 240)),
"target": Value::Null, "target": Value::Null,
@@ -913,6 +913,8 @@ pub fn normalize_codex_notification(method: &str, params: &Value) -> Vec<Normali
&mut events, &mut events,
if completed { if completed {
"tool.execution.completed" "tool.execution.completed"
} else if method == "item/updated" {
"tool.execution.progressed"
} else { } else {
"tool.execution.started" "tool.execution.started"
}, },
@@ -1752,6 +1754,30 @@ mod tests {
assert!(!events[0].payload.to_string().contains("top-secret")); assert!(!events[0].payload.to_string().contains("top-secret"));
} }
#[test]
fn preserves_opencode_builtin_tool_activity_and_bounded_errors() {
for (method, event_type, status) in [
("item/started", "tool.execution.started", "running"),
("item/updated", "tool.execution.progressed", "running"),
("item/completed", "tool.execution.completed", "failed"),
] {
let events = normalize_codex_notification(method, &json!({
"threadId": "session-1", "turnId": "turn-1", "item": {
"id": "part-invalid", "type": "builtinToolCall", "tool": "invalid",
"status": status, "output": "Tool not found: fixture_missing; token=top-secret",
}
}));
assert_eq!(events[0].event_type, event_type);
assert_eq!(events[0].payload["executionId"], "part-invalid");
assert_eq!(events[0].payload["transport"], "builtin");
assert_eq!(events[0].payload["name"], "invalid");
assert_eq!(events[0].payload["status"], status);
assert!(events[0].payload["output"].as_str().unwrap().contains("fixture_missing"));
assert!(!events[0].payload.to_string().contains("top-secret"));
assert!(events[0].payload.get("callId").is_none());
}
}
#[test] #[test]
fn maps_codex_final_answer_as_final_agent_message() { fn maps_codex_final_answer_as_final_agent_message() {
let final_answer = normalize_codex_notification( let final_answer = normalize_codex_notification(
@@ -13,6 +13,7 @@ import { parseNativeRuntimeContext } from "../contracts/runtime-context.js";
import { openCodeProxyTaskEnvelope } from "./opencode-proxy-task-envelope.js"; import { openCodeProxyTaskEnvelope } from "./opencode-proxy-task-envelope.js";
import { import {
openCodeProxyItemNotification, openCodeProxyItemNotification,
openCodeProxyToolNotification,
openCodeProxyTerminalNotification, openCodeProxyTerminalNotification,
shouldAnnounceOpenCodeProxyTurn, shouldAnnounceOpenCodeProxyTurn,
shouldForwardOpenCodeProxyItem, shouldForwardOpenCodeProxyItem,
@@ -192,7 +193,11 @@ function announceTurnStarted(opened: HarnessSession, turnId: string): void {
async function pumpEvents(opened: HarnessSession): Promise<void> { async function pumpEvents(opened: HarnessSession): Promise<void> {
for await (const event of opened.events()) { for await (const event of opened.events()) {
const payload = record(event.payload); const payload = record(event.payload);
if (event.eventType === "turn.started") { const toolActivity = openCodeProxyToolNotification({ eventType: event.eventType,
threadId: opened.ids().driverSessionId, turnId: event.turnId, payload });
if (toolActivity) {
send(toolActivity);
} else if (event.eventType === "turn.started") {
if (typeof event.turnId === "string") if (typeof event.turnId === "string")
announceTurnStarted(opened, event.turnId); announceTurnStarted(opened, event.turnId);
} else if ( } else if (
@@ -1,3 +1,24 @@
/** Forward bounded tool activity without inventing a host-call identity or arguments. */
export function openCodeProxyToolNotification(input: {
eventType: string; threadId: string; turnId?: string; payload: Record<string, unknown>;
}): { method: string; params: Record<string, unknown> } | null {
const phase = ({ "tool.execution.started": "started", "tool.execution.progressed": "updated", "tool.execution.completed": "completed" } as Record<string, string>)[input.eventType];
if (!phase) return null;
const p = input.payload;
if (!input.turnId || typeof p.executionId !== "string" || !p.executionId || p.schema !== "paperclip.tool.execution.v1")
throw new Error("OpenCode tool activity omitted its bound identity");
const type = ({ builtin: "builtinToolCall", mcp: "mcpToolCall", dynamic: "dynamicToolCall", process: "commandExecution" } as Record<string, string>)[String(p.transport)];
if (!type) throw new Error("OpenCode tool activity has an unsupported transport");
return { method: `item/${phase}`, params: {
threadId: input.threadId, turnId: input.turnId, itemId: p.executionId,
item: { id: p.executionId, type, tool: p.name, server: p.namespace,
readOnlyHint: p.readOnly, status: p.status, durationMs: p.durationMs, exitCode: p.exitCode,
// This is the already bounded provider-visible result, not raw input or a private trace.
output: typeof p.output === "string" ? p.output.slice(0, 16_384) : "",
},
} };
}
export function shouldForwardOpenCodeProxyItem(input: { export function shouldForwardOpenCodeProxyItem(input: {
turnId?: string; turnId?: string;
kind?: unknown; kind?: unknown;
@@ -106,11 +106,17 @@ it.each([true, false])("settles a real proxy interrupt with controller feedback
await response(1); await response(1);
send({ id: 2, method: "thread/start", params: { cwd: root, model: "openrouter/deepseek/deepseek-v4-flash-0731", completionContract: { revision: "proxy-v1", criterionIds: ["objective"] }, conversationMode: "prepared" } }); send({ id: 2, method: "thread/start", params: { cwd: root, model: "openrouter/deepseek/deepseek-v4-flash-0731", completionContract: { revision: "proxy-v1", criterionIds: ["objective"] }, conversationMode: "prepared" } });
await response(2); await response(2);
send({ id: 3, method: "turn/start", params: { input: [{ type: "text", text: JSON.stringify({ schema: "paperclip.native-model-envelope.v3", task: { prompt: "completion-feedback" }, completionContract: { revision: "proxy-v1", criteria: [{ id: "objective", requirement: "Complete the fixture." }] } }) }] } }); send({ id: 3, method: "turn/start", params: { input: [{ type: "text", text: JSON.stringify({ schema: "paperclip.native-model-envelope.v3", task: { prompt: "invalid-tool-feedback completion-feedback" }, completionContract: { revision: "proxy-v1", criteria: [{ id: "objective", requirement: "Complete the fixture." }] } }) }] } });
await response(3); await response(3);
await expect.poll(() => messages.find(message => message.method === "item/tool/call"), { timeout: 5_000 }).toBeDefined(); await expect.poll(() => messages.find(message => message.method === "item/tool/call"), { timeout: 5_000 }).toBeDefined();
const call = messages.find(message => message.method === "item/tool/call")!; const call = messages.find(message => message.method === "item/tool/call")!;
expect(call.params!.tool).toBe("paperclip_finish"); expect(call.params!.tool).toBe("paperclip_finish");
const toolFrames = messages.filter(message => (message.params?.item as { id?: string } | undefined)?.id === "part-invalid");
expect(toolFrames.map(message => message.method)).toEqual(["item/started", "item/updated", "item/completed"]);
expect(toolFrames.at(-1)?.params).toMatchObject({
threadId: call.params!.threadId, turnId: call.params!.turnId,
item: { id: "part-invalid", type: "builtinToolCall", tool: "invalid", status: "failed", output: "Tool not found: fixture_missing" },
});
const feedback = "Accepted. Include [Saved document](/PAP/issues/PAP-1#document-plan)."; const feedback = "Accepted. Include [Saved document](/PAP/issues/PAP-1#document-plan).";
// The interrupt is ahead of the response on stdin. Commands stay serial, // The interrupt is ahead of the response on stdin. Commands stay serial,
// but their awaited response must not queue behind the command itself. // but their awaited response must not queue behind the command itself.
@@ -0,0 +1,8 @@
import { readFileSync } from "node:fs";
import { expect, it } from "vitest";
import { composeNativeSystemInstructions, type NativeRuntimeContextSnapshot } from "./runtime-context.js";
it("keeps the TypeScript instruction composer and Rust attachment fixture in sync", () => {
const fixtures = JSON.parse(readFileSync(new URL("../../test/fixtures/registered-asset-instructions.json", import.meta.url), "utf8")) as Array<{context: NativeRuntimeContextSnapshot; entry: string; instructions: string}>;
for (const fixture of fixtures) expect(composeNativeSystemInstructions(fixture.context, fixture.entry)).toBe(fixture.instructions);
});
@@ -619,6 +619,15 @@ const server = createServer(async (request, response) => {
}, },
}, },
}); });
if (String(parsedPrompt.message ?? parsedPrompt.task?.prompt ?? "").includes("invalid-tool-feedback")) {
for (const [status, state] of [
["pending", {}], ["running", { title: "Checking tool name" }],
["error", { error: "Tool not found: fixture_missing" }],
]) emit({ type: "message.part.updated", id: `event-invalid-${status}`, properties: {
sessionID: session.id, part: { id: "part-invalid", messageID: "message-assistant",
type: "tool", tool: "invalid", callID: "call-invalid", state: { status, ...state } },
} });
}
emit({ emit({
type: "message.part.updated", type: "message.part.updated",
id: "event-patch", id: "event-patch",
@@ -0,0 +1,64 @@
[
{
"context": {
"prompt": {
"text": "Pinned prompt."
},
"connectionInstructions": {
"text": "Pinned connection policy."
},
"instructions": {
"bundle": {
"rootPath": "/registered/bundle"
},
"workingCopy": {
"kind": "agent_files",
"rootPath": "/registered/run-copy",
"entryPath": "AGENTS.md"
}
}
},
"entry": "Custom entry quoting /registered/run-copy stays unchanged.",
"instructions": "Pinned prompt.\n\nCustom entry quoting /registered/run-copy stays unchanged.\n\nPinned connection policy.\n\nYour persistent agent directory (AGENT_HOME) is /registered/run-copy. Your instruction entry is AGENTS.md, relative to that directory. All supported files and subfolders there are restored across tasks and sessions, and collected after this provider stops. Write task deliverables in the task working directory. Only changed or deleted files synchronize; the last sync wins for the same file. Temporary copies are cleaned up without retaining file history. Check the save receipt before claiming persistence.\n\nRead-only instruction sibling root: /registered/bundle"
},
{
"context": {
"prompt": {
"text": "Pinned prompt."
},
"connectionInstructions": {
"text": "Pinned connection policy."
},
"instructions": {
"bundle": {
"rootPath": "/registered/bundle"
},
"workingCopy": {
"kind": "instruction_file",
"rootPath": "/registered/run-copy",
"entryPath": "AGENTS.md"
}
}
},
"entry": "Custom entry quoting /registered/run-copy stays unchanged.",
"instructions": "Pinned prompt.\n\nCustom entry quoting /registered/run-copy stays unchanged.\n\nPinned connection policy.\n\nYour editable agent instruction file is /registered/run-copy/AGENTS.md. Edit this registered private copy normally. After this run stops, Paperclip saves changed content as a persistent revision if your responsible user still has permission and the baseline has not changed. Check the run's instruction-save receipt before claiming persistence. Conflicts are preserved for explicit resolution. Repository instruction files, skills, and this run's loaded prompt are separate and are not collected.\n\nRead-only instruction sibling root: /registered/bundle"
},
{
"context": {
"prompt": {
"text": "Pinned prompt."
},
"connectionInstructions": {
"text": "Pinned connection policy."
},
"instructions": {
"bundle": {
"rootPath": "/registered/bundle"
},
"workingCopy": null
}
},
"entry": "Custom entry quoting /registered/run-copy stays unchanged.",
"instructions": "Pinned prompt.\n\nCustom entry quoting /registered/run-copy stays unchanged.\n\nPinned connection policy.\n\nRead-only instruction sibling root: /registered/bundle"
}
]
@@ -1,7 +1,7 @@
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { agents, companies, createDb, heartbeatRuns, issues } from "@paperclipai/db"; import { agents, companies, createDb, heartbeatRuns, issues, issueThreadInteractions } from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import type { PrpStructuredRunResult } from "../../vendor/paperclip-runner/index.js"; import type { PrpStructuredRunResult } from "../../vendor/paperclip-runner/index.js";
import { documentService } from "../documents.js"; import { documentService } from "../documents.js";
@@ -32,6 +32,28 @@ describe("native final-response feedback", () => {
} }) as { document: { id: string; latestRevisionId: string }; documentHref: string }; } }) as { document: { id: string; latestRevisionId: string }; documentHref: string };
return { companyId, agentId, issueId, runId, saved }; return { companyId, agentId, issueId, runId, saved };
} }
it("rejects a duplicate approval report for the exact pending tool-action card", async () => {
const value = await fixture(), interactionId = randomUUID();
await db.insert(issueThreadInteractions).values({ id: interactionId, companyId: value.companyId, issueId: value.issueId,
sourceRunId: value.runId, createdByAgentId: value.agentId, kind: "request_confirmation", status: "pending",
continuationPolicy: "wake_assignee", payload: { version: 1, prompt: "Approve service read", toolAction: { version: 1, actionRequestId: randomUUID(), invocationId: randomUUID(), toolName: "pages.read", toolDisplayName: "Read pages", connectionId: null, applicationId: null, appDisplayName: null, risk: "read", previewMarkdown: "Read pages", argumentsSummaryJson: "{}", argumentsHash: "test-hash", expiresAt: "2026-10-07T12:00:00Z" } },
});
const waiting: PrpStructuredRunResult = { ...done, reportedWorkDisposition: "yielded",
completionClaim: { ...done.completionClaim, objectiveSatisfied: false, remainingWork: [{ description: "Read the approved result", blocksCompletion: true }] },
evidence: [{ ref: `interaction:${interactionId}` }], continuation: { kind: "response_wake", idempotencyKey: "service-wait", summary: "Await the service decision" },
attentionRequests: [{ kind: "approval", ownerClass: "human", summary: "Approve the service card" }],
};
await expect(nativeCompletionFeedback(db, value.runId, waiting)).rejects.toThrow("already has an approval card");
// Waiting on the existing gate is valid; it must not become a second review.
await expect(nativeCompletionFeedback(db, value.runId, { ...waiting, attentionRequests: [] })).resolves.toContain("still waiting for a response");
// A separate review request is not silently removed or treated as this gate.
await expect(nativeCompletionFeedback(db, value.runId, { ...waiting, evidence: [] })).resolves.toContain("still waiting for a response");
await db.update(issueThreadInteractions).set({ status: "accepted", result: { version: 1, outcome: "accepted", toolAction: { version: 1, status: "executed", updatedAt: "2026-10-07T06:00:00Z" } } }).where(eq(issueThreadInteractions.id, interactionId));
await expect(nativeCompletionFeedback(db, value.runId, waiting)).rejects.toThrow("already resolved");
// An old run cannot bind a new completion report to its card.
await db.update(issueThreadInteractions).set({ sourceRunId: null }).where(eq(issueThreadInteractions.id, interactionId));
await expect(nativeCompletionFeedback(db, value.runId, waiting)).resolves.toContain("Completion report accepted");
});
it("returns a concrete final-answer link without treating the document title as instructions", async () => { it("returns a concrete final-answer link without treating the document title as instructions", async () => {
const value = await fixture(); const value = await fixture();
const feedback = await nativeCompletionFeedback(db, value.runId, done); const feedback = await nativeCompletionFeedback(db, value.runId, done);
@@ -136,6 +136,31 @@ export async function nativeCompletionFeedback(
? continuation.objective : [issue.title, issue.description].filter(Boolean).join("\n"); ? continuation.objective : [issue.title, issue.description].filter(Boolean).join("\n");
await validateNativeDeliverableEvidence(db, { companyId: run.companyId, issueId: issue.id, runId, await validateNativeDeliverableEvidence(db, { companyId: run.companyId, issueId: issue.id, runId,
objective, semanticToolReceipts: run.resultJson?.semanticToolReceipts }, result); objective, semanticToolReceipts: run.resultJson?.semanticToolReceipts }, result);
// A response wake for this run's tool action already has a durable approval
// surface. Reject a second approval report before it can materialize a new
// completion review after the original card is answered during this turn.
if (result.reportedWorkDisposition === "yielded" && result.continuation?.kind === "response_wake") {
const referencedIds = result.evidence.flatMap(({ ref }) => {
const match = typeof ref === "string" ? /^interaction:([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/i.exec(ref) : null;
return match ? [match[1]!] : [];
});
const referenced = referencedIds.length ? await db.select().from(issueThreadInteractions).where(and(
eq(issueThreadInteractions.companyId, run.companyId), eq(issueThreadInteractions.issueId, issue.id),
eq(issueThreadInteractions.sourceRunId, run.id), eq(issueThreadInteractions.createdByAgentId, run.agentId),
eq(issueThreadInteractions.kind, "request_confirmation"), eq(issueThreadInteractions.continuationPolicy, "wake_assignee"),
inArray(issueThreadInteractions.id, referencedIds),
)) : [];
for (const card of referenced) {
const action = record(record(card.payload).toolAction);
if (action.version !== 1 || typeof action.actionRequestId !== "string") continue;
if (["accepted", "rejected"].includes(card.status)) {
throw new Error(`The referenced tool-action approval is already resolved (${card.id}). Read its persisted interaction result and continue from that decision. Do not repeat the service call or request approval again.`);
}
if (card.status === "pending" && signals.actionableAttentionRequests.some(request => request.kind === "approval" && request.ownerClass === "human")) {
throw new Error(`This tool action already has an approval card (${card.id}). Wait on that existing interaction with a yielded response_wake report and no duplicate approval attentionRequest. Paperclip will resume from its decision; do not create a completion review or repeat the service call.`);
}
}
}
const retiredCandidates = await findAutomaticCompletionReviews(db, issue.id); const retiredCandidates = await findAutomaticCompletionReviews(db, issue.id);
const retiredIds = retiredCandidates.map(({ interaction }) => interaction.id); const retiredIds = retiredCandidates.map(({ interaction }) => interaction.id);
const [interaction, approval] = await Promise.all([ const [interaction, approval] = await Promise.all([
+6 -3
View File
@@ -41,6 +41,7 @@ import {
storyReviewContinuationTimeoutDetail, storyReviewContinuationTimeoutDetail,
storyHasStrandedBlockedLeaf, storyHasStrandedBlockedLeaf,
storyHasDurableAgentReviewContinuation, storyHasDurableAgentReviewContinuation,
storyHasDurableServiceContinuation,
storyIssueHasBlockedTimelineBefore, storyIssueHasBlockedTimelineBefore,
storyIssueHasUnresolvedDependency, storyIssueHasUnresolvedDependency,
storyRunReportsDependencyBlock, storyRunReportsDependencyBlock,
@@ -304,11 +305,12 @@ export async function runEverydayFlow(input: Input) {
const settledState = await pollUntil({ const settledState = await pollUntil({
label: `everyday ${caseId} settled`, label: `everyday ${caseId} settled`,
deadlineAt: input.deadlineAt, deadlineAt: input.deadlineAt,
timeoutDetail: (state) => state && timeoutDetail: (state) => state && (
storyReviewContinuationTimeoutDetail( storyReviewContinuationTimeoutDetail(
state.issues, parent?.id ?? "", fixtures.agent.id, state.runs, state.issues, parent?.id ?? "", fixtures.agent.id, state.runs,
observableAgentIds(state), observableAgentIds(state),
), ) ?? (storyHasDurableServiceContinuation(state.issues, parent?.id ?? "", fixtures.agent.id, state.runs)
? "task is Blocked without an active continuation after executed service approval" : undefined)),
intervalMs: 1000, intervalMs: 1000,
load: refresh, load: refresh,
accept: (state) => accept: (state) =>
@@ -346,7 +348,8 @@ export async function runEverydayFlow(input: Input) {
parent?.id ?? "", parent?.id ?? "",
fixtures.agent.id, fixtures.agent.id,
state.runs, state.runs,
) ) &&
!storyHasDurableServiceContinuation(state.issues, parent?.id ?? "", fixtures.agent.id, state.runs)
) )
return "task is Blocked without an active continuation"; return "task is Blocked without an active continuation";
if ( if (
+28
View File
@@ -37,6 +37,8 @@ export interface StoryActivityRecord {
createdAt?: string; createdAt?: string;
} }
export interface StoryInteraction { export interface StoryInteraction {
sourceRunId?: string | null;
createdByAgentId?: string | null;
id?: string; id?: string;
kind?: string; kind?: string;
issueId?: string | null; issueId?: string | null;
@@ -443,6 +445,32 @@ export function storyHasDurableAgentReviewContinuation(
); );
} }
/** An executed approval may enqueue its wake just after run finalization.
* Wait within the original deadline only for this task/run's recorded response.
* Once a follow-up run has consumed it, a new blocker is a real failure.
*/
export function storyHasDurableServiceContinuation(issues: StoryIssue[], parentId: string, agentId: string, runs: StoryRun[]): boolean {
const issue = issues.find(i => i.id === parentId);
if (issue?.status !== "blocked" || issue.assigneeAgentId !== agentId) return false;
return issue.interactions?.some(interaction => {
const source = runs.find(run => run.id === interaction.sourceRunId);
const action = interaction.payload?.toolAction as Record<string, unknown> | undefined;
const result = interaction.result?.toolAction as Record<string, unknown> | undefined;
if (interaction.issueId !== parentId || interaction.createdByAgentId !== agentId ||
interaction.kind !== "request_confirmation" || interaction.continuationPolicy !== "wake_assignee" ||
interaction.status !== "accepted" || interaction.result?.outcome !== "accepted" ||
action?.version !== 1 || typeof action.actionRequestId !== "string" || result?.status !== "executed" ||
source?.agentId !== agentId || source.companyId !== issue.companyId || source.status !== "succeeded" ||
!(Date.parse(source.finishedAt ?? "") >= Date.parse(interaction.resolvedAt ?? ""))) return false;
return !runs.some(run => {
const input = run.runnerProfileJson?.nativeExecutionInput as
{ interactionResponses?: Array<{ interactionId?: string }> } | undefined;
return run.id !== source.id && run.agentId === agentId &&
input?.interactionResponses?.some(response => response.interactionId === interaction.id);
});
}) ?? false;
}
/** Timeout evidence requires a stranded leaf with durable accepted-review evidence. */ /** Timeout evidence requires a stranded leaf with durable accepted-review evidence. */
export function storyReviewContinuationTimeoutDetail( export function storyReviewContinuationTimeoutDetail(
issues: StoryIssue[], issues: StoryIssue[],
+38 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from "vitest"; import { describe, expect, it, vi } from "vitest";
import { pollUntil } from "./api.js"; import { pollUntil } from "./api.js";
import { classifyFailure } from "./failure-classifier.js"; import { classifyFailure } from "./failure-classifier.js";
import { storyHasDurableAgentReviewContinuation, storyHasStrandedBlockedLeaf, storyReviewContinuationTimeoutDetail, type StoryIssue } from "./everyday-observations.js"; import { storyHasDurableServiceContinuation, storyHasDurableAgentReviewContinuation, storyHasStrandedBlockedLeaf, storyReviewContinuationTimeoutDetail, type StoryIssue } from "./everyday-observations.js";
describe("workflow timeout classification", () => { describe("workflow timeout classification", () => {
it("does not classify observed task data as an infrastructure error", async () => { it("does not classify observed task data as an infrastructure error", async () => {
@@ -145,3 +145,40 @@ describe("review continuation deadline", () => {
} finally { vi.useRealTimers(); } } finally { vi.useRealTimers(); }
}); });
}); });
describe("approved service continuation deadline", () => {
it.each([true, false])("keeps the original deadline for a delayed dispatch (arrives: %s)", async arrives => {
vi.useFakeTimers();
try {
const start = Date.now();
const issues: StoryIssue[] = [{ id: "task", companyId: "company", title: "Briefing", status: "blocked", assigneeAgentId: "agent", interactions: [{
id: "approval", issueId: "task", sourceRunId: "first", createdByAgentId: "agent", kind: "request_confirmation", status: "accepted", continuationPolicy: "wake_assignee",
resolvedAt: new Date(start - 1000).toISOString(), payload: { toolAction: { version: 1, actionRequestId: "action" } }, result: { outcome: "accepted", toolAction: { status: "executed" } },
}] }];
const runs = [{ id: "first", companyId: "company", agentId: "agent", status: "succeeded", finishedAt: new Date(start).toISOString() }];
const caught = pollUntil({ label: "service continuation", deadlineAt: start + 30_000, intervalMs: 1000,
load: async () => { if (arrives && Date.now() >= start + 20_000) issues[0]!.status = "done"; return { issues, runs }; },
accept: state => state.issues[0]!.status === "done",
reject: state => storyHasStrandedBlockedLeaf(state.issues, "agent") && !storyHasDurableServiceContinuation(state.issues, "task", "agent", state.runs) ? "stranded" : undefined,
timeoutDetail: state => state && storyHasDurableServiceContinuation(state.issues, "task", "agent", state.runs) ? "missing service continuation" : undefined,
}).catch((error: unknown) => error);
await vi.advanceTimersByTimeAsync(30_001);
const result = await caught;
if (arrives) expect(result).toEqual({ issues, runs });
else { expect((result as Error).message).toContain("missing service continuation"); expect(classifyFailure(result)).toBe("candidate_failure"); }
} finally { vi.useRealTimers(); }
});
it("waits for dispatch only until the same response has been consumed", () => {
const issues: StoryIssue[] = [{ id: "task", companyId: "company", title: "Briefing", status: "blocked", assigneeAgentId: "agent", interactions: [{
id: "approval", issueId: "task", sourceRunId: "first", createdByAgentId: "agent", kind: "request_confirmation", status: "accepted", continuationPolicy: "wake_assignee",
resolvedAt: "2026-10-07T05:37:19Z", payload: { toolAction: { version: 1, actionRequestId: "action" } }, result: { outcome: "accepted", toolAction: { status: "executed" } },
}] }];
const runs = [{ id: "first", companyId: "company", agentId: "agent", status: "succeeded", finishedAt: "2026-10-07T05:37:28Z" }];
expect(storyHasDurableServiceContinuation(issues, "task", "agent", runs)).toBe(true);
expect(storyHasDurableServiceContinuation(issues, "task", "other", runs)).toBe(false);
const continued = [...runs, { id: "next", companyId: "company", agentId: "agent", status: "succeeded", runnerProfileJson: { nativeExecutionInput: { interactionResponses: [{ interactionId: "approval" }] } } }];
expect(storyHasDurableServiceContinuation(issues, "task", "agent", continued)).toBe(false);
issues[0]!.interactions![0]!.result = { outcome: "accepted", toolAction: { status: "failed" } };
expect(storyHasDurableServiceContinuation(issues, "task", "agent", runs)).toBe(false);
});
});