fix: make runner task context ownership explicit (#13753)

<!-- Write all pull request text in Simplified Technical English
(ASD-STE100). -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Task descriptions, comments, continuation data, skills, and
execution rules enter several agent adapters.
> - The same source can be rendered by more than one automatic input
carrier.
> - Failed resumes can also rebuild input from stale or compact context.
> - This pull request gives each Paperclip-owned source one delivery
owner and preserves the required transport boundaries.
> - It adds deterministic adapter, interaction, runner, and browser
tests for these boundaries.
> - The benefit is more predictable context delivery with explicit
evidence for later live qualification.

## Linked Issues or Issue Description

Related: #13144 removes a duplicate environment payload and bounds wake
lists. Related: #11360 addresses Hermes resume behavior. This pull
request preserves compatible active-session formats while repairing
context ownership and stale question creation.

**What happened?**

Task descriptions and comments could enter more than one automatic
context block. Native transports could wrap a complete model input in a
second task envelope. Some legacy and gateway adapters could omit the
owned assignment on ordinary tasks or rebuild a failed resume with stale
compact context. A continuation could also request a question after
newer human comments had arrived.

**Expected behavior**

Each task or comment source has one automatic model-facing owner.
Distinct comment IDs and repeated wording remain distinct. Fresh
fallback attempts rebuild the required full context. A question request
is rejected when newer queued human direction makes it stale. Harness
access policy remains owned by execution configuration.

**Steps to reproduce**

1. Build a task with a description and current comments.
2. Capture the actual adapter or runner input.
3. Compare source ownership and task-envelope nesting.
4. Queue a human comment before a continuation requests a question.
5. Trigger a failed resume and inspect the fresh retry input.
6. Run the focused adapter, interaction, runner, and browser checks.

## What Changed

- Add shared prompt-section selection at the provider-attempt boundary.
- Deliver owned assignment context through native, legacy CLI, ACP,
gateway, cloud, Pi, Kimi, Grok, Gemini, OpenCode, Cursor, OpenClaw, and
Hermes paths.
- Rebuild full or compact context after resume recovery changes the
attempt. Add native and Claude ACP tests of actual recovery requests.
- Preserve custom templates, loaded instruction files, execution
policies, and older active-session formats.
- Record continuation source metadata and reject stale question creation
under the issue-row lock.
- Add explicit Product E2E context-integrity profiles, prerequisite
gates, credential-isolation checks, and report fixtures.
- Bypass service-worker forwarding for same-origin Vite development
modules. A real Chromium test fails with resource exhaustion before the
repair and passes after it. Production asset caching keeps its existing
policy.
- Add browser diagnostics and service-worker module-loading regressions.
- Add an explicit zero-retry eval option. The default retry behavior
remains unchanged. Each campaign records its effective policy.
- Remove the model-facing working-directory sentence from four prompt
builders. Existing workspace, sandbox, permission, and custom-template
configuration remains unchanged.
- Align the everyday workflow assertion with the current 47-entry
catalog.

Compared with current upstream master, the branch carries the
context-ownership implementation and its tests, the explicit
context-integrity catalog and evidence harness, and the focused browser
regression checks.

## Verification

**Merge assessment:** focused regression evidence supports merge. This
is not full completion of the original broad qualification matrix. The
maintainer has authorized merge after fresh verification of the master
integration.

- Current head: `bbd52f82114eabf09bc7b1a7e97d54a5b43bbc00`. This
integrates current master `2f585ef26a1814fa209715242d1ca791b63e4c4e`.
All 14 conflicts are resolved. Cancellation checks, workspace
finalization, native Grok support, and both sets of tests are retained.
- Current-head Greptile: **5/5**, with no blocking findings. The review
names this exact commit. All **59 reported checks are terminal: 55
successful, 4 skipped, zero pending or failing**. This includes the full
root general and serialized suites, separate runner checks, typecheck,
build, canary, browser E2E, Docker, and security checks. The successful
legacy security status is included in that total.
- After integration: workspace typecheck and full build passed. Separate
runner checks passed: **2,160 TypeScript tests (10 skipped), 582 Rust
tests, and 39 preparation checks**. Other passing checks include 621
Product E2E harness units, 376 focused shared/adapter tests, 160
real-database/API tests, 86 Hermes tests, 18 browser-support checks, and
Product E2E typechecking. The complete root suite passed in CI. The
duplicate local monolithic root run was stopped after that CI result; it
is not counted as a completed local pass.
- New native recovery coverage retains full assignment, completion
contract, and explicit skill selection after safe replacement, for old
and prepared input formats. Full native session test file: **136/136
passed**.
- New Claude ACP coverage captures actual fresh, resumed, and
missing-session fallback requests. It verifies one assignment copy,
comment order, identical text under distinct comment IDs, and full
fallback context. Full file: **33/33 passed**. Both affected TypeScript
checks passed.
- Existing deterministic tests cover source revisions, approval and
trust boundaries, completion validation, custom templates, compatible
sessions, standalone driver wrapping, and maintained adapter transport
requests.
- Provider-free browser support: **17/17 passed** after the master
merge. Service-worker unit tests: **33/33 passed**. The module-overload
regression failed before the repair and passed after it in real
Chromium.

### Fresh live comparisons

The new batch ran exactly four Product E2E attempts. **All four passed
on the first attempt; no retries.** Each has six terminal matchers plus
the existing browser lifecycle and invariant checks.

| Exact case ID | Control | Candidate |
|---|---|---|
| `core-compatibility.runner-codex.local.plan-revise-accept` | Passed |
Passed |
|
`local-session-integrity.runner-acpx-claude.local.structured-question-restart-resume`
| Passed | Passed |

The plan case checks a revised canonical plan and revision-bound
approval before completion. The question case restarts the server before
submitting the answer, then verifies the continuation completes.

Control source is `dfa4e1bda8d50a1a01746603251a9128dbe9d0d6`. Candidate
source is `79fcdb5dece501d28064ea9da306603881b46f0c`. They use identical
frozen definitions and provider versions: Codex `0.156.0` with
`gpt-5.6-sol`; ACPX `0.13.1` / Claude ACP `0.73.0` with
`claude-sonnet-5`. The September 24 head added master browser recovery
and test-only changes. The September 28 head also integrates newer
master changes, including cancellation, workspace finalization, and
native Grok. These are frozen-source live results, not exact-head live
runs.

The candidate received one description copy where the control initially
received three. The submitted initial plan envelopes were 7,969 versus
19,097 characters. Question envelopes were 7,592 versus 18,919. These
are structural measurements, not whole-provider token or dollar savings.

### Earlier evidence and failed attempts

- The preceding fresh batch has four effective passing pairs: OpenCode
comment continuation and assigned skill, native Codex comment
continuation, and native Claude comment continuation. It retains **11
attempts: eight passed and three failed**.
- Original failures remain recorded: missing local PostgreSQL library
links before task creation; host-sleep cleanup after task/page checks
passed; and a Claude **control** session-open rejection before a model
turn. Setup was repaired identically on both worktrees. The permitted
unchanged infrastructure retries passed. The underlying Claude provider
startup error was not retained and remains unknown.
- Older R2 retains **17 passes and one failure** across 18 attempts,
including eight both-pass native/legacy Codex/Claude pairs. Its OpenCode
blank-page failure led to the service-worker repair. R2 is historical
evidence: master changed the native fixed prompt and removed duplicate
wake environment data afterward.
- The September 24 CI run initially failed one unrelated preview
readiness test (`ECONNREFUSED` on its local fixture). Its test and
production code match master. Isolated local verification passed **28
tests, 3 skipped**. One unchanged CI retry passed the full shard: **831
passed, 1 skipped**, including all **31 preview-exposure tests**. The
aggregate CI gate passed afterward. The precise startup cause remains
unknown; a port race is a hypothesis, not a proved cause.

### Limits

The original wider profile/workflow matrix, repeated trials, and remote
Daytona qualification are incomplete. These results support a focused
merge recommendation, not statistical equivalence or universal harness
qualification. Some usage receipts are missing in both variants, so no
token or dollar savings are claimed. The $500 ceiling was preserved
using conservative allowances; failed attempts and unknown charges
remain in the ledger.

Reproduce the focused additions with `pnpm exec vitest run
packages/adapters/claude-local/src/server/acp.test.ts` and `pnpm
--filter @paperclipai/paperclip-runner exec vitest run
src/native-session-runtime.test.ts`. Full checks use `pnpm -r
typecheck`, `pnpm test:run`, `pnpm build`, and the separate runner
checks. Paid evals require the frozen definitions, profiles, and
credentials; do not use `--all` as a substitute for the selected cases.

## Risks

- Context placement changes can affect model behavior. Deterministic
checks cover the selected paths, but live qualification remains
incomplete.
- The stale-question guard can reject a request when queued human
comments arrived during the run. This is intended.
- New stored inputs and model envelopes retain compatibility readers for
older active sessions.
- Custom templates may intentionally repeat content.
- Removing a model-facing working-directory sentence does not change
filesystem, command, sandbox, or permission configuration.
- The worker bypass applies only to same-origin development module
paths. Cache-policy tests preserve private-response handling and
production asset caching. Mounted HTTP fixture changes remain test-only.
- This PR does not claim measured token savings or statistical
equivalence across every harness.

## Model Used

OpenAI Codex, exact model gpt-6-astra, with repository tools and code
execution. Bounded supporting work used gpt-5.6-luna and gpt-6-luna. The
serving context-window size is not exposed in this task.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have described the issue in-PR using the required issue fields
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal
ticket id
- [x] I have run the focused local checks and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect these changes
- [x] I have considered and documented risks above
- [x] All current-head Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
for the current head
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-09-28 14:49:14 -05:00
1 parent 2f585ef26a
commit 992f720262
122 files changed
+5487 -636

No files matched your search

@@ -280,7 +280,7 @@ describeEmbeddedPostgres(
const mismatchedRun = await service.create(
{ id: fixture.issueId, companyId: fixture.companyId },
{ ...question, sourceRunId: foreignRunId },
{ agentId: fixture.agentId },
{ agentId: foreignAgentId },
);
await expect(
@@ -4,6 +4,7 @@ import os from "node:os";
import path from "node:path";
import type { AdapterRuntimeMcpServer } from "@paperclipai/adapter-utils";
import { runChildProcess } from "@paperclipai/adapter-utils/server-utils";
import { buildPaperclipTaskMarkdown } from "../services/heartbeat.js";
import {
claudeCommandSupportsEffortFlag,
claudeSessionCwdMatchesExecutionTarget,
@@ -351,6 +352,63 @@ function createLocalSandboxRunner() {
}
describe("claude execute", () => {
it("passes real assignment markdown and ordered current events once through the CLI", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-claude-context-owner-"));
const { workspace, commandPath, capturePath, restore } = await setupExecuteEnv(root);
const markdown = buildPaperclipTaskMarkdown({
issue: { id: "issue-1", identifier: "PAP-901", title: "Repeat phrase Repeat phrase", description: "Repeat phrase Repeat phrase" },
wakeComments: [
{ id: "comment-a", body: "Same event body." },
{ id: "comment-b", body: "Same event body." },
],
includeWakeComments: false,
});
const historicalMarkdown = buildPaperclipTaskMarkdown({
issue: { id: "issue-1", identifier: "PAP-901", title: "Repeat phrase Repeat phrase", description: "Repeat phrase Repeat phrase" },
wakeComments: [
{ id: "comment-a", body: "Same event body." },
{ id: "comment-b", body: "Same event body." },
],
});
try {
await execute({
runId: "run-context-owner",
agent: { id: "agent-1", companyId: "company-1", name: "Claude", adapterType: "claude_local", adapterConfig: {} },
runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
config: {
engine: "cli", command: commandPath, cwd: workspace,
env: { PAPERCLIP_TEST_CAPTURE_PATH: capturePath },
promptTemplate: "Custom template keeps {{paperclipTaskMarkdown}} and {{paperclipWakePrompt}}.",
},
context: {
issueId: "issue-1",
paperclipTaskMarkdown: historicalMarkdown,
paperclipTaskMarkdownAssignment: markdown,
paperclipWake: {
reason: "issue_commented",
issue: { id: "issue-1", identifier: "PAP-901", title: "Repeat phrase Repeat phrase", description: "Repeat phrase Repeat phrase", status: "in_progress" },
comments: [
{ id: "comment-a", issueId: "issue-1", body: "Same event body.", bodyTruncated: false, createdAt: "2026-09-21T00:00:00.000Z" },
{ id: "comment-b", issueId: "issue-1", body: "Same event body.", bodyTruncated: false, createdAt: "2026-09-21T00:01:00.000Z" },
],
commentWindow: { requestedCount: 2, includedCount: 2, missingCount: 0 },
fallbackFetchNeeded: false,
},
paperclipTurnContext: { version: 1, assignment: { owner: "task_markdown" }, events: { owner: "wake_prompt", comments: [{ id: "comment-a", revision: "a" }, { id: "comment-b", revision: "b" }] } },
},
onLog: async () => {},
});
const capture = JSON.parse(await fs.readFile(capturePath, "utf8")) as CapturePayload;
expect(capture.prompt).toContain("Custom template keeps");
expect(capture.prompt.indexOf("comment-a")).toBeLessThan(capture.prompt.indexOf("comment-b"));
expect(capture.prompt.split("Same event body.")).toHaveLength(3);
expect(capture.prompt.split("Repeat phrase Repeat phrase")).toHaveLength(4);
} finally {
restore();
await fs.rm(root, { recursive: true, force: true });
}
});
it.each([
[undefined, "claude-opus-5"],
["", "claude-opus-5"],
@@ -659,6 +659,84 @@ describe("codex execute", () => {
}
});
it("keeps real assignment markdown and current wake events single-owned at the CLI boundary", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-codex-context-owner-"));
const workspace = path.join(root, "workspace");
const commandPath = path.join(root, "codex");
const capturePath = path.join(root, "capture.json");
await fs.mkdir(workspace, { recursive: true });
await writeFakeCodexCommand(commandPath);
const markdown = buildPaperclipTaskMarkdown({
issue: { id: "issue-1", identifier: "PAP-900", title: "Repeat phrase Repeat phrase", description: "Repeat phrase Repeat phrase" },
wakeComments: [
{ id: "comment-a", body: "Same event body." },
{ id: "comment-b", body: "Same event body." },
],
includeWakeComments: false,
});
const historicalMarkdown = buildPaperclipTaskMarkdown({
issue: { id: "issue-1", identifier: "PAP-900", title: "Repeat phrase Repeat phrase", description: "Repeat phrase Repeat phrase" },
wakeComments: [
{ id: "comment-a", body: "Same event body." },
{ id: "comment-b", body: "Same event body." },
],
});
try {
await execute({
runId: "run-context-owner",
agent: { id: "agent-1", companyId: "company-1", name: "Codex", adapterType: "codex_local", adapterConfig: {} },
runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
config: {
engine: "cli", command: commandPath, cwd: workspace,
env: { PAPERCLIP_TEST_CAPTURE_PATH: capturePath },
promptTemplate: "Custom template keeps {{paperclipTaskMarkdown}} and {{paperclipWakePrompt}}.",
},
context: {
issueId: "issue-1",
paperclipTaskMarkdown: historicalMarkdown,
paperclipTaskMarkdownAssignment: markdown,
paperclipWake: {
reason: "issue_commented",
issue: { id: "issue-1", identifier: "PAP-900", title: "Repeat phrase Repeat phrase", description: "Repeat phrase Repeat phrase", status: "in_progress" },
executionContinuation: {
version: 1,
companyId: "company-1",
issueId: "issue-1",
trigger: { reason: "issue_commented", interactionId: null, sourceRunId: null },
originCommentIds: [],
objective: "Repeat phrase Repeat phrase",
objectiveSource: { kind: "description", id: "issue-1", revision: "2e2ed64c2ca5be0343f591d037a6f40a0b9cee733fedb7fdafa69e4158299957" },
messages: [],
interactionOutcomes: [],
completedWork: null,
unresolvedInteractionIds: [],
coverage: { kind: "full_task_history", throughCommentId: null, summaryThroughCommentId: null },
},
comments: [
{ id: "comment-a", issueId: "issue-1", body: "Same event body.", bodyTruncated: false, createdAt: "2026-09-21T00:00:00.000Z" },
{ id: "comment-b", issueId: "issue-1", body: "Same event body.", bodyTruncated: false, createdAt: "2026-09-21T00:01:00.000Z" },
],
commentWindow: { requestedCount: 2, includedCount: 2, missingCount: 0 },
fallbackFetchNeeded: false,
},
paperclipTurnContext: { version: 1, assignment: { owner: "task_markdown" }, events: { owner: "wake_prompt", comments: [{ id: "comment-a", revision: "a" }, { id: "comment-b", revision: "b" }] } },
},
onLog: async () => {},
});
const capture = JSON.parse(await fs.readFile(capturePath, "utf8")) as CapturePayload;
expect(capture.prompt).toContain("Custom template keeps");
expect(capture.prompt).toContain("comment-a");
expect(capture.prompt.indexOf("comment-a")).toBeLessThan(capture.prompt.indexOf("comment-b"));
expect(capture.prompt.split("Same event body.")).toHaveLength(3);
// The custom template intentionally repeats task context; ownership only
// removes automatic wake-event duplication.
expect(capture.prompt.split("Repeat phrase Repeat phrase")).toHaveLength(4);
expect(capture.prompt).not.toContain('"objective":"Repeat phrase Repeat phrase"');
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
it("classifies remote-compaction high-demand failures as retryable transient upstream errors", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-codex-execute-transient-"));
const workspace = path.join(root, "workspace");
@@ -352,7 +352,9 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
});
await db
.update(executionWorkspaces)
.set({ sourceIssueId })
// Keep delivery eligibility independent of the sweep's JavaScript clock
// boundary; database defaultNow() can be a few microseconds newer.
.set({ sourceIssueId, updatedAt: new Date("2020-01-01T00:00:00Z") })
.where(eq(executionWorkspaces.id, executionWorkspaceId));
if (options.childStatus) {
await db.insert(issues).values({
@@ -217,6 +217,32 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => {
runningProcesses.clear();
});
async function readGatewayWakePayload(
payload: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const message = String(payload.message ?? "");
if (message.includes("```json\n")) {
return parseWakePayloadFromMessage(message);
}
const runId = typeof payload.idempotencyKey === "string"
? payload.idempotencyKey
: null;
if (!runId) throw new Error("Gateway payload did not include its run id");
const run = await db
.select({ contextSnapshot: heartbeatRuns.contextSnapshot })
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null);
const context = run?.contextSnapshot;
const wake = context && typeof context === "object" && !Array.isArray(context)
? (context as Record<string, unknown>).paperclipWake
: null;
if (!wake || typeof wake !== "object" || Array.isArray(wake)) {
throw new Error("Gateway payload omitted JSON without a structured wake context");
}
return wake as Record<string, unknown>;
}
it("defers approval-approved wakes for a running issue so the assignee resumes after the run", async () => {
const companyId = randomUUID();
const agentId = randomUUID();
@@ -682,7 +708,7 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => {
expect(promotedTaskMarkdown).not.toContain("First comment");
expect(secondPayload.paperclip).toBeUndefined();
const secondWake = parseWakePayloadFromMessage(secondPayload.message);
const secondWake = await readGatewayWakePayload(secondPayload);
expect(secondWake).toMatchObject({
commentIds: [comment2.id, comment3.id],
latestCommentId: comment3.id,
@@ -1179,7 +1205,7 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => {
const secondPayload = gateway.getAgentPayloads()[1] ?? {};
expect(secondPayload.paperclip).toBeUndefined();
const secondWake = parseWakePayloadFromMessage(secondPayload.message);
const secondWake = await readGatewayWakePayload(secondPayload);
expect(secondWake).toMatchObject({
reason: "issue_commented",
commentIds: [comment2.id],
@@ -1430,7 +1456,7 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => {
const secondPayload = gateway.getAgentPayloads()[1] ?? {};
expect(secondPayload.paperclip).toBeUndefined();
const secondWake = parseWakePayloadFromMessage(secondPayload.message);
const secondWake = await readGatewayWakePayload(secondPayload);
expect(secondWake).toMatchObject({
reason: wakeReason,
commentIds: [comment.id],
@@ -1833,8 +1859,8 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => {
commentId: selfComment.id,
});
expect(gateway.getAgentPayloads()).toHaveLength(2);
const continuationWake = parseWakePayloadFromMessage(
gateway.getAgentPayloads()[1]?.message,
const continuationWake = await readGatewayWakePayload(
gateway.getAgentPayloads()[1] ?? {},
);
expect(continuationWake?.commentIds).toEqual([sourceComment.id]);
expect(continuationWake?.comments).toEqual([
@@ -2290,8 +2316,8 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => {
expect(String(gateway.getAgentPayloads()[0]?.message ?? "")).toContain(
"Do not narrate Paperclip workflow, checkout, status, or completion bookkeeping.",
);
const continuationWake = parseWakePayloadFromMessage(
gateway.getAgentPayloads()[0]?.message,
const continuationWake = await readGatewayWakePayload(
gateway.getAgentPayloads()[0] ?? {},
);
expect(continuationWake).toMatchObject({
externalChatProvider: "slack",
@@ -2302,13 +2328,13 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => {
endpointId,
conversationId,
}),
questionResponse: {
interactionId: answered.id,
summaryMarkdown:
"Resolved questions and answers:\n- Continue the release?: Yes",
truncated: false,
},
});
// The gateway's structured JSON is intentionally omitted when the
// wake prompt owns comments. The authoritative interaction answer is
// still carried in the rendered prompt.
expect(String(gateway.getAgentPayloads()[0]?.message ?? "")).toContain(
"Continue the release?: Yes",
);
gateway.releaseFirstWait();
await waitFor(async () => {
@@ -2546,7 +2572,7 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => {
const secondPayload = gateway.getAgentPayloads()[1] ?? {};
expect(secondPayload.paperclip).toBeUndefined();
const secondWake = parseWakePayloadFromMessage(secondPayload.message);
const secondWake = await readGatewayWakePayload(secondPayload);
expect(secondWake).toMatchObject({
reason: "issue_commented",
commentIds: [humanComment.id],
@@ -3190,7 +3216,7 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => {
expect(String(firstPayload.message ?? "")).toContain(
`${issuePrefix}-1 Require a comment`,
);
const firstWake = parseWakePayloadFromMessage(firstPayload.message);
const firstWake = await readGatewayWakePayload(firstPayload);
expect(firstWake).toMatchObject({
reason: "issue_assigned",
checkedOutByHarness: true,
@@ -5,8 +5,74 @@ import {
summarizeHeartbeatRunContextSnapshot,
summarizeHeartbeatRunListResultJson,
} from "../services/heartbeat.js";
import { renderPaperclipWakePrompt } from "@paperclipai/adapter-utils/server-utils";
describe("buildPaperclipTaskMarkdown", () => {
it("leaves current comments to the wake renderer when assignment-only rendering is selected", () => {
const commentBody = "Keep this current comment exactly once.";
const markdown = buildPaperclipTaskMarkdown({
issue: {
id: "issue-overlap",
identifier: "PAP-5002",
title: "Current comment overlap",
description: "Assignment brief.",
},
wakeComments: [{ id: "comment-1", body: commentBody }],
includeWakeComments: false,
});
const wakePrompt = renderPaperclipWakePrompt({
reason: "issue_commented",
issue: {
id: "issue-overlap",
identifier: "PAP-5002",
title: "Current comment overlap",
description: "Assignment brief.",
},
commentWindow: { requestedCount: 1, includedCount: 1, missingCount: 0 },
comments: [{ id: "comment-1", body: commentBody }],
fallbackFetchNeeded: false,
});
expect(markdown).not.toContain(commentBody);
expect(wakePrompt).toContain(commentBody);
expect(`${markdown}\n${wakePrompt}`.split(commentBody)).toHaveLength(2);
});
it("keeps attachment descriptors and follow-up rules when assignment markdown omits wake bodies", () => {
const markdown = buildPaperclipTaskMarkdown({
issue: { id: "issue-files", identifier: "PAP-5003", title: "Files", description: "Brief" },
wakeComments: [{
id: "comment-files",
body: "Inspect the file.",
attachments: [{
id: "attachment-1",
filename: "evidence.png",
contentType: "image/png",
byteSize: 42,
contentPath: "/api/attachments/attachment-1/content",
}],
}],
includeWakeComments: false,
});
expect(markdown).not.toContain("Inspect the file.");
expect(markdown).toContain("Follow-up directive:");
expect(markdown).toContain('Attachments on wake comment "comment-files":');
expect(markdown).toContain('"id":"attachment-1"');
});
it("preserves repeated same-body wake events as distinct ordered comments", () => {
const markdown = buildPaperclipTaskMarkdown({
issue: { id: "issue-order", identifier: "PAP-5004", title: "Order", description: null },
wakeComments: [
{ id: "comment-a", body: "Repeat me." },
{ id: "comment-b", body: "Repeat me." },
],
});
expect(markdown!.indexOf('"comment-a"')).toBeLessThan(markdown!.indexOf('"comment-b"'));
expect(markdown!.split("Repeat me.")).toHaveLength(3);
});
it.each(["standard", "planning", "ask"])("selects directives only from explicit %s mode, even when a plan is requested", (workMode) => {
for (const prose of [
{ title: "Prepare rollout steps", description: "Describe the steps." },
@@ -90,6 +90,8 @@ import {
import { buildNativeExecutionInput } from "../services/native-runtime/native-execution-input.js";
import { nativeRuntimeContextFixture } from "../services/native-runtime/runtime-context.test-fixture.js";
import { NativeRunnerOwnershipUnverifiedError } from "../services/native-runtime/native-runner-ownership.js";
import { nativeCompletionSource } from "../services/native-runtime/completion-contracts.js";
import { buildNativeModelEnvelope } from "@paperclipai/paperclip-runner";
import {
CHAT_CONTROL_RECOVERY_ADMISSION_KEY,
CHAT_CONTROL_RECOVERY_STOP_CODE,
@@ -2744,6 +2746,51 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
});
});
it("carries the ordinary initial description provenance through native heartbeat assembly", async () => {
await withTempPaperclipHome(async () => {
const { agentId, issueId, runId } = await seedQueuedIssueRunFixture();
await db.update(agents).set({
adapterType: "paperclip_runner",
adapterConfig: { provider: "codex", model: "gpt-5.6-luna" },
}).where(eq(agents.id, agentId));
const nativeSessionBackendFactory = vi.fn(
(_execution: { workspace: { cwd: string } }) => {
throw new NativeRunnerOwnershipUnverifiedError();
},
);
const heartbeat = heartbeatService(db, { nativeSessionBackendFactory });
await heartbeat.resumeQueuedRuns();
await waitForValue(
async () => nativeSessionBackendFactory.mock.calls.length > 0 ||
Boolean((await heartbeat.getRun(runId))?.errorCode),
8_000,
);
await heartbeat.waitForRunExecutionDrain(runId);
expect(nativeSessionBackendFactory).toHaveBeenCalledTimes(1);
const input = nativeSessionBackendFactory.mock.calls[0]![0] as ReturnType<typeof buildNativeExecutionInput>;
const description = "Verify the successful-run handoff and choose an honest disposition.";
const source = nativeCompletionSource("description", issueId, description);
expect(input.completionContract.contract.criteria).toEqual([{
id: "objective",
requirement: description,
}]);
expect(input.completionSources).toMatchObject({
criteria: [{ id: "objective", source }],
});
expect(input.task.prompt).toContain(description);
expect(input.task.prompt.split(description)).toHaveLength(2);
const modelEnvelope = buildNativeModelEnvelope(input);
expect(modelEnvelope.schema).toBe("paperclip.native-model-envelope.v3");
expect(modelEnvelope.task).not.toHaveProperty("description");
expect(modelEnvelope.task.prompt.split(description)).toHaveLength(2);
expect(modelEnvelope.completionContract.criteria).toEqual([{
id: "objective",
source: { ...source, location: "task.prompt" },
}]);
});
});
it("holds admitted native chat with a legacy shared cwd without replacing input or releasing ownership", async () => {
await withTempPaperclipHome(async () => {
const { companyId, agentId, issueId, runId } =
@@ -19,14 +19,16 @@ export type RunnerConnectionScenario = "fresh" | "pending" | "declined" | "custo
const CONNECTION_SCENARIOS: readonly RunnerConnectionScenario[] = ["fresh", "pending", "declined", "custom", "foreign", "stale_owner", "ready"];
/** Disposable real routes, database and storage. A fresh company isolates each attempt. */
export async function startRunnerApiTestServer() {
export async function startRunnerApiTestServer(options: {
deploymentMode?: "authenticated" | "local_trusted";
} = {}) {
const root = await mkdtemp(join(tmpdir(), "paperclip-api-eval-"));
const temporary = await startEmbeddedPostgresTestDatabase("paperclip-api-eval-db-");
const db = createDb(temporary.connectionString);
const storage = createStorageService(createLocalDiskStorageProvider(join(root, "storage")));
const app = await createApp(db, {
uiMode: "none", serverPort: 0, storageService: storage,
deploymentMode: "authenticated", deploymentExposure: "private",
deploymentMode: options.deploymentMode ?? "authenticated", deploymentExposure: "private",
allowedHostnames: ["127.0.0.1"], bindHost: "127.0.0.1", authReady: true,
companyDeletionEnabled: false, instanceId: `eval-${randomUUID()}`,
localPluginDir: join(root, "plugins"), managedPluginAutoInstall: [],
@@ -42,7 +44,7 @@ export async function startRunnerApiTestServer() {
setupRunnerPrpWebSocketServer(http, { apiUrl });
return {
db, root, apiUrl, storage,
async fixture(options: { mode?: "standard" | "ask" | "planning"; apiToolsEnabled?: boolean; reset?: boolean; conversation?: boolean; connectionScenario?: RunnerConnectionScenario } = {}) {
async fixture(options: { mode?: "standard" | "ask" | "planning"; apiToolsEnabled?: boolean; reset?: boolean; conversation?: boolean; connectionScenario?: RunnerConnectionScenario; contextSnapshot?: Record<string, unknown>; disableWakeOnDemand?: boolean } = {}) {
if (options.connectionScenario !== undefined && !CONNECTION_SCENARIOS.includes(options.connectionScenario)) throw new Error(`Unknown connection eval scenario: ${String(options.connectionScenario)}`);
// This DB is created inside this helper, never supplied by a caller. Paid
// paired runs reset it between attempts so modeled IDs and data match.
@@ -85,7 +87,7 @@ export async function startRunnerApiTestServer() {
await db.insert(authUsers).values({ id: responsibleUserId, name: "Eval responsible user", email: `${responsibleUserId}@fixture.invalid`, emailVerified: true, createdAt: new Date(), updatedAt: new Date() }).onConflictDoNothing();
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: responsibleUserId, status: "active", membershipRole: "member" });
}
await db.insert(agents).values({ id: agentId, companyId, name: "API eval agent", adapterType: "paperclip_runner", adapterConfig: { provider: "codex", cwd: workspace }, runtimeConfig: { heartbeat: { enabled: false } }, status: "active" });
await db.insert(agents).values({ id: agentId, companyId, name: "API eval agent", adapterType: "paperclip_runner", adapterConfig: { provider: "codex", cwd: workspace }, runtimeConfig: { heartbeat: { enabled: false, ...(options.disableWakeOnDemand ? { wakeOnDemand: false } : {}) } }, status: "active" });
await db.insert(projects).values([
{ id: projectId, companyId, name: "Aurora", description: "The project verification code is violet-otter.", status: "in_progress" },
{ id: foreignProjectId, companyId: foreignCompanyId, name: "Private project", description: "foreign-data-must-not-leak" },
@@ -97,7 +99,7 @@ export async function startRunnerApiTestServer() {
await db.insert(assets).values({ id, companyId, ...saved, createdByAgentId: agentId });
}
await db.insert(issues).values({ id: issueId, companyId, projectId, projectWorkspaceId, issueNumber: 1, identifier: "E" + companyId.replaceAll("-", "").slice(0, 8) + "-1", ...(options.conversation ? { conversationAgentId: agentId, conversationUserId: responsibleUserId, conversationState: "active" as const } : {}), title: "Verify runner API tools", description: "Fixture marker: amber-fox.", status: "in_progress", workMode: options.mode ?? "standard", assigneeAgentId: agentId });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", responsibleUserId, runtimeMode: "native", nativeIssueId: issueId, invocationSource: "assignment", triggerDetail: "system", contextSnapshot: { issueId, ...(options.conversation ? { conversationSessionGeneration: 0 } : {}) } });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", responsibleUserId, runtimeMode: "native", nativeIssueId: issueId, invocationSource: "assignment", triggerDetail: "system", contextSnapshot: { issueId, ...(options.conversation ? { conversationSessionGeneration: 0 } : {}), ...options.contextSnapshot } });
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
if (responsibleUserId) await initializeRunIdentity(db, { companyId, runId, issueId, responsibleUserId, cause: "instruction" });
await db.insert(issues).values({ id: blockerId, companyId, projectId, issueNumber: 2, identifier: "E" + companyId.replaceAll("-", "").slice(0, 8) + "-2", title: "Dependency gate", description: "Complete before shipping.", status: "todo", assigneeAgentId: agentId });
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import {
activityLog,
@@ -160,6 +160,328 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => {
});
}
async function seedSourceQuestionFixture(contextSnapshot: Record<string, unknown>) {
const { companyId, issueId } = await seedConfirmationIssue("Source question race");
const agentId = randomUUID();
const runId = randomUUID();
await db.insert(agents).values({
id: agentId,
companyId,
name: "Questioner",
role: "engineer",
status: "active",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
});
await db.insert(heartbeatRuns).values({
id: runId,
companyId,
agentId,
invocationSource: "manual",
status: "running",
createdAt: new Date("2026-07-25T12:00:00.000Z"),
startedAt: new Date("2026-07-25T12:00:01.000Z"),
contextSnapshot: { issueId, ...contextSnapshot },
});
return { companyId, issueId, agentId, runId };
}
function questionCreateInput(sourceRunId: string) {
return {
kind: "ask_user_questions" as const,
sourceRunId,
continuationPolicy: "wake_assignee" as const,
payload: {
version: 1 as const,
questions: [{
id: "scope",
prompt: "Which scope?",
selectionMode: "single" as const,
options: [{ id: "phase-1", label: "Phase 1" }],
}],
},
};
}
it("rejects a source-run question when a newer human comment was not delivered", async () => {
const fixture = await seedSourceQuestionFixture({ paperclipWake: { comments: [] } });
const commentId = randomUUID();
await db.insert(issueComments).values({
id: commentId,
companyId: fixture.companyId,
issueId: fixture.issueId,
authorType: "user",
authorUserId: "board-user",
body: "The requested scope is already specified.",
createdAt: new Date("2026-07-25T12:01:00.000Z"),
updatedAt: new Date("2026-07-25T12:01:00.000Z"),
});
await expect(interactionsSvc.create(
{ id: fixture.issueId, companyId: fixture.companyId },
questionCreateInput(fixture.runId),
{ agentId: fixture.agentId, runId: fixture.runId },
)).rejects.toMatchObject({
status: 409,
details: expect.objectContaining({
reason: "newer_comment_not_delivered",
commentIds: [commentId],
}),
});
expect(await interactionsSvc.listForIssue(fixture.companyId, fixture.issueId)).toEqual([]);
});
it("allows a source-run question when the newer human comment is explicitly delivered", async () => {
const commentId = randomUUID();
const fixture = await seedSourceQuestionFixture({ paperclipWake: { comments: [{ id: commentId }] } });
await db.insert(issueComments).values({
id: commentId,
companyId: fixture.companyId,
issueId: fixture.issueId,
authorType: "user",
authorUserId: "board-user",
body: "Choose phase one.",
createdAt: new Date("2026-07-25T12:01:00.000Z"),
updatedAt: new Date("2026-07-25T12:01:00.000Z"),
});
const created = await interactionsSvc.create(
{ id: fixture.issueId, companyId: fixture.companyId },
questionCreateInput(fixture.runId),
{ agentId: fixture.agentId, runId: fixture.runId },
);
expect(created).toMatchObject({ kind: "ask_user_questions", status: "pending" });
});
it("keeps legacy source snapshots compatible when delivered comments are unknown", async () => {
const fixture = await seedSourceQuestionFixture({});
await db.insert(issueComments).values({
companyId: fixture.companyId,
issueId: fixture.issueId,
authorType: "user",
authorUserId: "board-user",
body: "A legacy context cannot prove delivery.",
createdAt: new Date("2026-07-25T12:01:00.000Z"),
updatedAt: new Date("2026-07-25T12:01:00.000Z"),
});
const created = await interactionsSvc.create(
{ id: fixture.issueId, companyId: fixture.companyId },
questionCreateInput(fixture.runId),
{ agentId: fixture.agentId, runId: fixture.runId },
);
expect(created.status).toBe("pending");
});
it("does not apply the delivery guard to approval interactions", async () => {
const fixture = await seedSourceQuestionFixture({ paperclipWake: { comments: [] } });
await db.insert(issueComments).values({
companyId: fixture.companyId,
issueId: fixture.issueId,
authorType: "user",
authorUserId: "board-user",
body: "Please review the plan.",
createdAt: new Date("2026-07-25T12:01:00.000Z"),
updatedAt: new Date("2026-07-25T12:01:00.000Z"),
});
const created = await interactionsSvc.create(
{ id: fixture.issueId, companyId: fixture.companyId },
{
kind: "request_confirmation",
sourceRunId: fixture.runId,
continuationPolicy: "wake_assignee",
payload: { version: 1, prompt: "Approve this plan?" },
},
{ agentId: fixture.agentId, runId: fixture.runId },
);
expect(created).toMatchObject({ kind: "request_confirmation", status: "pending" });
});
it("does not treat the board concierge reply as human direction", async () => {
const fixture = await seedSourceQuestionFixture({ paperclipWake: { comments: [] } });
await db.insert(issueComments).values({
companyId: fixture.companyId,
issueId: fixture.issueId,
authorType: "user",
authorUserId: "board-concierge",
body: "The concierge relay replied.",
createdAt: new Date("2026-07-25T12:01:00.000Z"),
updatedAt: new Date("2026-07-25T12:01:00.000Z"),
});
const created = await interactionsSvc.create(
{ id: fixture.issueId, companyId: fixture.companyId },
questionCreateInput(fixture.runId),
{ agentId: fixture.agentId, runId: fixture.runId },
);
expect(created.status).toBe("pending");
});
it("rejects an explicitly mismatched source-run issue or agent", async () => {
const fixture = await seedSourceQuestionFixture({ paperclipWake: { comments: [] } });
const otherAgentId = randomUUID();
await db.insert(agents).values({
id: otherAgentId,
companyId: fixture.companyId,
name: "Other questioner",
role: "engineer",
status: "active",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
});
await db.update(heartbeatRuns)
.set({ nativeIssueId: randomUUID() })
.where(eq(heartbeatRuns.id, fixture.runId));
await expect(interactionsSvc.create(
{ id: fixture.issueId, companyId: fixture.companyId },
questionCreateInput(fixture.runId),
{ agentId: fixture.agentId, runId: fixture.runId },
)).rejects.toMatchObject({ status: 422, message: "sourceRunId must belong to the same issue" });
await db.update(heartbeatRuns)
.set({ nativeIssueId: null, contextSnapshot: { issueId: randomUUID(), paperclipWake: { comments: [] } } })
.where(eq(heartbeatRuns.id, fixture.runId));
await expect(interactionsSvc.create(
{ id: fixture.issueId, companyId: fixture.companyId },
questionCreateInput(fixture.runId),
{ agentId: fixture.agentId, runId: fixture.runId },
)).rejects.toMatchObject({ status: 422, message: "sourceRunId must belong to the same issue" });
await db.update(heartbeatRuns)
.set({ contextSnapshot: { issueId: fixture.issueId, paperclipWake: { comments: [] } } })
.where(eq(heartbeatRuns.id, fixture.runId));
await expect(interactionsSvc.create(
{ id: fixture.issueId, companyId: fixture.companyId },
questionCreateInput(fixture.runId),
{ agentId: otherAgentId, runId: fixture.runId },
)).rejects.toMatchObject({ status: 422, message: "sourceRunId must belong to the creating agent" });
});
it("expires a question when a comment transaction started earlier inserts after it commits", async () => {
const fixture = await seedSourceQuestionFixture({});
let transactionStarted!: () => void;
let allowCommentInsert!: () => void;
const started = new Promise<void>((resolve) => { transactionStarted = resolve; });
const continueComment = new Promise<void>((resolve) => { allowCommentInsert = resolve; });
const commentPromise = db.transaction(async (tx) => {
// Establish the PostgreSQL transaction before the question is created;
// the old DEFAULT now() would therefore make this comment appear older.
await tx.execute(sql`select now()`);
transactionStarted();
await continueComment;
return issuesSvc.addComment(
fixture.issueId,
"The board supplied the missing scope.",
{ userId: "board-user" },
{ authorType: "user" },
tx,
);
});
await started;
let created: Awaited<ReturnType<typeof interactionsSvc.create>>;
try {
created = await interactionsSvc.create(
{ id: fixture.issueId, companyId: fixture.companyId },
{
kind: "ask_user_questions",
continuationPolicy: "wake_assignee",
payload: {
version: 1,
questions: [{
id: "scope",
prompt: "Which scope?",
selectionMode: "single",
options: [{ id: "phase-1", label: "Phase 1" }],
}],
},
},
{ agentId: fixture.agentId },
);
} finally {
allowCommentInsert();
}
await commentPromise;
const [comment] = await db
.select({ createdAt: issueComments.createdAt, updatedAt: issueComments.updatedAt })
.from(issueComments)
.where(eq(issueComments.issueId, fixture.issueId));
expect(comment?.updatedAt.toISOString()).toBe(comment?.createdAt.toISOString());
await expect(interactionsSvc.getById(created.id)).resolves.toMatchObject({
status: "expired",
result: { expirationReason: "superseded_by_comment" },
});
});
it("locks the issue before inserting a supplied-transaction comment", async () => {
const fixture = await seedSourceQuestionFixture({});
let insertReached!: () => void;
let releaseInsert!: () => void;
const reached = new Promise<void>((resolve) => { insertReached = resolve; });
const release = new Promise<void>((resolve) => { releaseInsert = resolve; });
await db.transaction(async (tx) => {
const lockedTx = new Proxy(tx as any, {
get(target, property, receiver) {
if (property !== "insert") return Reflect.get(target, property, receiver);
return (table: unknown) => {
const builder = target.insert(table);
if (table !== issueComments) return builder;
return new Proxy(builder, {
get(insertBuilder, builderProperty, builderReceiver) {
if (builderProperty !== "values") {
return Reflect.get(insertBuilder, builderProperty, builderReceiver);
}
return (...values: unknown[]) => {
const valued = insertBuilder.values(...values);
return new Proxy(valued, {
get(returningBuilder, returningProperty, returningReceiver) {
if (returningProperty !== "returning") {
return Reflect.get(returningBuilder, returningProperty, returningReceiver);
}
return (...returningArgs: unknown[]) => {
insertReached();
return release.then(() => returningBuilder.returning(...returningArgs));
};
},
});
};
},
});
};
},
});
const commentPromise = issuesSvc.addComment(
fixture.issueId,
"Comment inserted under a caller-owned transaction.",
{ userId: "board-user" },
{ authorType: "user" },
lockedTx,
);
await reached;
try {
await expect(db.transaction(async (observer) => {
await observer.execute(sql`
select id from issues
where id = ${fixture.issueId}
for update nowait
`);
})).rejects.toMatchObject({ cause: { code: "55P03" } });
} finally {
releaseInsert();
await commentPromise;
}
});
});
it("reuses human-addressed connection intents across runs and ordinary comments", async () => {
const { companyId, issueId } = await seedConfirmationIssue("Connection intent");
const agentId = randomUUID();
@@ -852,6 +852,32 @@ describeEmbeddedPostgres(
ReturnType<typeof startEmbeddedPostgresTestDatabase>
> | null = null;
async function readGatewayWakePayload(
payload: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const message = String(payload.message ?? "");
if (message.includes("```json\n")) {
return parseWakePayloadFromMessage(message);
}
const runId = typeof payload.idempotencyKey === "string"
? payload.idempotencyKey
: null;
if (!runId) throw new Error("Gateway payload did not include its run id");
const run = await db
.select({ contextSnapshot: heartbeatRuns.contextSnapshot })
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null);
const context = run?.contextSnapshot;
const wake = context && typeof context === "object" && !Array.isArray(context)
? (context as Record<string, unknown>).paperclipWake
: null;
if (!wake || typeof wake !== "object" || Array.isArray(wake)) {
throw new Error("Gateway payload omitted JSON without a structured wake context");
}
return wake as Record<string, unknown>;
}
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase(
"paperclip-low-trust-red-team-routes-",
@@ -1978,7 +2004,7 @@ describeEmbeddedPostgres(
// The gateway rejects unknown root params, so the wake context rides in the
// generated message rather than a top-level `paperclip` field.
expect(payload.paperclip).toBeUndefined();
const wake = parseWakePayloadFromMessage(payload.message);
const wake = await readGatewayWakePayload(payload);
// Security-critical: low-trust quarantined output is redacted to the sanitized
// stub before it reaches the higher-trust wake/continuation context. The raw
// body must never appear (asserted by expectNoCanary below). The sourceTrust
@@ -2014,6 +2040,8 @@ describeEmbeddedPostgres(
expect(String(payload.message ?? "")).toContain(
"## Paperclip Wake Payload",
);
expect(String(payload.message ?? "")).toContain(LOW_TRUST_QUARANTINED_BODY);
expect(String(payload.message ?? "")).toContain("Continue from the sanitized quarantine stub only.");
expectNoCanary(payload, fixture.canaries.raw);
gateway.releaseFirstWait();
await waitFor(async () => {
+21
View File
@@ -213,6 +213,27 @@ describe("redaction", () => {
});
});
it("preserves native execution v5 and model envelope v3 schema identifiers", () => {
const input = {
schema: "paperclip.native-execution-input.v5",
nested: {
runtimeSchema: "paperclip.native-model-envelope.v3",
providerValue: "paperclip.native-execution-input.v5",
},
};
expect(sanitizeRecord(input)).toEqual({
schema: input.schema,
nested: {
runtimeSchema: input.nested.runtimeSchema,
providerValue: REDACTED_EVENT_VALUE,
},
});
expect(sanitizeRecord({ schema: "paperclip.native-execution-input.v4", runtimeSchema: "paperclip.native-model-envelope.v2" })).toEqual({
schema: "paperclip.native-execution-input.v4",
runtimeSchema: "paperclip.native-model-envelope.v2",
});
});
it("preserves only known PRP v1 event discriminators inside validated envelopes", () => {
const payload = {
prpEvent: {
+2
View File
@@ -92,6 +92,7 @@ export const PAPERCLIP_PUBLIC_SCHEMA_IDS = new Set([
"paperclip.native-execution-input.v2",
"paperclip.native-execution-input.v3",
"paperclip.native-execution-input.v4",
"paperclip.native-execution-input.v5",
"paperclip.native-finalization.v1",
"paperclip.native-finalization.v2",
"paperclip.native-harness-backup-stamp.v1",
@@ -99,6 +100,7 @@ export const PAPERCLIP_PUBLIC_SCHEMA_IDS = new Set([
"paperclip.native-harness-backup.v1",
"paperclip.native-model-envelope.v1",
"paperclip.native-model-envelope.v2",
"paperclip.native-model-envelope.v3",
"paperclip.native-session-scope.v2",
"paperclip.native-session-supervisor.v1",
"paperclip.plan.updated.v1",
@@ -146,6 +146,16 @@ const support = await getEmbeddedPostgresTestSupport();
summary: "Notion read completed.",
exposeLowTrustRaw: false,
});
it("attests the exact latest user comment selected as the objective", async () => {
const envelope = await build();
const latest = await db.select().from(issueComments).where(eq(issueComments.id, laterId)).then(rows => rows[0]!);
expect(envelope.objective).toBe(latest.body);
expect(envelope.objectiveSource).toEqual({
kind: "comment",
id: laterId,
revision: latest.updatedAt.toISOString(),
});
});
it("loads authenticated human answers from stored resolver identity", async () => {
const answerId = randomUUID();
await db.insert(issueThreadInteractions).values({ id: answerId, companyId, issueId,
@@ -1,3 +1,4 @@
import { createHash } from "node:crypto";
import { and, asc, desc, eq, inArray, isNotNull, isNull, or, sql } from "drizzle-orm";
import { z } from "zod";
import {
@@ -46,6 +47,33 @@ export function continuationOriginCommentIds(context: unknown): string[] {
];
}
/**
* Return the comment IDs explicitly represented in a delivered continuation.
* An absent list is intentionally different from an empty list: historical or
* third-party snapshots cannot prove what the provider received.
*/
export function deliveredContinuationCommentIds(context: unknown): {
known: boolean;
ids: Set<string>;
} {
const c = object(context);
const wake = object(c.paperclipWake);
const continuation = object(c.executionContinuation);
const ids = new Set<string>();
let known = false;
const collect = (value: unknown) => {
if (!Array.isArray(value)) return;
known = true;
for (const item of value) {
const id = typeof item === "string" ? item : string(object(item).id);
if (id) ids.add(id);
}
};
collect(wake.comments);
collect(continuation.messages);
return { known, ids };
}
/** Keep service/tool results and generated summaries out of human authority. */
export function projectHumanInteractionResponse(row: {
id: string; kind: string; status: string; result: unknown;
@@ -275,6 +303,12 @@ export async function buildExecutionContinuation(input: {
(row) =>
row.authorType === "user" && !row.createdByRunId && !row.deleted && row.body.trim().length > 0,
);
const hashObjectiveSource = (value: string) => createHash("sha256").update(value.trim()).digest("hex");
const objectiveSource = latestRequest
? { kind: "comment" as const, id: latestRequest.id, revision: latestRequest.updatedAt }
: issue.description !== null && issue.description !== undefined
? { kind: "description" as const, id: issue.id, revision: hashObjectiveSource(issue.description) }
: { kind: "title" as const, id: issue.id, revision: hashObjectiveSource(issue.title) };
const priorRuns = await db
.select({ id: heartbeatRuns.id, result: heartbeatRuns.resultJson, status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode, runtimeMode: heartbeatRuns.runtimeMode, retryOfRunId: heartbeatRuns.retryOfRunId })
.from(heartbeatRuns)
@@ -391,6 +425,7 @@ export async function buildExecutionContinuation(input: {
},
originCommentIds,
objective: latestRequest?.body ?? issue.description ?? issue.title,
objectiveSource,
messages,
humanResponses: interactions.flatMap(row => {
const response = projectHumanInteractionResponse(row);
+138 -45
View File
@@ -1,3 +1,4 @@
import type { PaperclipTurnContext } from "@paperclipai/adapter-utils/server-utils";
import { restoreNativeWorkspaceBestEffort } from "./native-runtime/native-workspace-best-effort.js";
import {
withNativeWorkspaceFinalizationOwnership,
@@ -229,7 +230,9 @@ import {
isRunnerIngressAuthorized,
materializeLegacyQuestionResponseWakeProjection,
materializeNativeInteractionResponses,
nativeCompletionRequestsForComments,
nativeCompletionRequestsWithSources,
nativeCompletionSource,
nativeImmediateObjectiveSource,
NativeCancellationPendingRecoveryError,
NativeControllerDetachedForRestartError,
nativeToolContractFingerprintForTarget,
@@ -8583,6 +8586,9 @@ export function buildPaperclipTaskMarkdown(input: {
// false builds the compact variant used for resume deltas, where the session
// already received the description with the assignment.
includeDescription?: boolean;
// Current wake events are rendered by the structured wake prompt on
// adapter lanes. Keep the legacy default for standalone callers.
includeWakeComments?: boolean;
}) {
const quoteTaskScalar = (value: string) => JSON.stringify(value);
const fenceTaskText = (value: string) => {
@@ -8608,6 +8614,7 @@ export function buildPaperclipTaskMarkdown(input: {
: null);
const effectiveWakeComments =
wakeComments.length > 0 ? wakeComments : wakeComment ? [wakeComment] : [];
const renderWakeCommentBodies = input.includeWakeComments !== false;
const rejectedPlan = input.planReview?.status === "rejected";
const acceptedPlanContinuation =
!rejectedPlan && !issue?.conversationAgentId && !wakeComment &&
@@ -8808,7 +8815,9 @@ export function buildPaperclipTaskMarkdown(input: {
"Apply the latest wake comment to the current task. Later direction replaces conflicting scope; preserve other requirements and approval gates. Clarification is not approval. Reuse completed work rather than repeating it.",
"",
"Latest wake comment:",
fenceTaskText(effectiveWakeComments[0]!.body),
...(renderWakeCommentBodies
? [fenceTaskText(effectiveWakeComments[0]!.body)]
: []),
);
appendWakeAttachments(effectiveWakeComments[0]!);
} else if (effectiveWakeComments.length > 1) {
@@ -8823,7 +8832,7 @@ export function buildPaperclipTaskMarkdown(input: {
lines.push(
"",
`Wake comment ${index + 1} (${quoteTaskScalar(comment.id)}):`,
fenceTaskText(comment.body),
...(renderWakeCommentBodies ? [fenceTaskText(comment.body)] : []),
);
appendWakeAttachments(comment);
}
@@ -20897,15 +20906,27 @@ export function heartbeatService(
})
: null;
let taskMarkdown = buildPaperclipTaskMarkdown({ ...taskMarkdownInput, taskPlan });
let taskMarkdownAssignment = buildPaperclipTaskMarkdown({
...taskMarkdownInput,
taskPlan,
includeWakeComments: false,
});
if (isConversation(issueContext) && !taskSession && issueId) {
const replay = await conversationReplay(db, agent.companyId, issueId, wakeCommentId);
if (replay) taskMarkdown += `\n\nEarlier messages in this session (quoted user data):\n${replay}`;
if (replay) taskMarkdownAssignment += `\n\nEarlier messages in this session (quoted user data):\n${replay}`;
}
const taskMarkdownCompact = buildPaperclipTaskMarkdown({
...taskMarkdownInput,
taskPlan,
includeDescription: false,
});
const taskMarkdownAssignmentCompact = buildPaperclipTaskMarkdown({
...taskMarkdownInput,
taskPlan,
includeDescription: false,
includeWakeComments: false,
});
if (issueRef) {
context.paperclipIssue = {
id: issueRef.id,
@@ -20927,11 +20948,21 @@ export function heartbeatService(
} else {
delete context.paperclipTaskMarkdown;
}
if (taskMarkdownAssignment) {
context.paperclipTaskMarkdownAssignment = taskMarkdownAssignment;
} else {
delete context.paperclipTaskMarkdownAssignment;
}
if (taskMarkdownCompact && taskMarkdownCompact !== taskMarkdown) {
context.paperclipTaskMarkdownCompact = taskMarkdownCompact;
} else {
delete context.paperclipTaskMarkdownCompact;
}
if (taskMarkdownAssignmentCompact && taskMarkdownAssignmentCompact !== taskMarkdownAssignment) {
context.paperclipTaskMarkdownAssignmentCompact = taskMarkdownAssignmentCompact;
} else {
delete context.paperclipTaskMarkdownAssignmentCompact;
}
if (issueRef) {
const redactedWakeContext = await createRunSecretRedactionRegistry(
db,
@@ -20941,6 +20972,8 @@ export function heartbeatService(
paperclipTaskCommunicationGuidance: context.paperclipTaskCommunicationGuidance,
paperclipTaskMarkdown: context.paperclipTaskMarkdown,
paperclipTaskMarkdownCompact: context.paperclipTaskMarkdownCompact,
paperclipTaskMarkdownAssignment: context.paperclipTaskMarkdownAssignment,
paperclipTaskMarkdownAssignmentCompact: context.paperclipTaskMarkdownAssignmentCompact,
});
context.paperclipIssue = redactedWakeContext.paperclipIssue;
context.paperclipTaskCommunicationGuidance = redactedWakeContext.paperclipTaskCommunicationGuidance;
@@ -20956,6 +20989,42 @@ export function heartbeatService(
context.paperclipTaskMarkdownCompact =
redactedWakeContext.paperclipTaskMarkdownCompact;
}
if (redactedWakeContext.paperclipTaskMarkdownAssignment) {
context.paperclipTaskMarkdownAssignment =
redactedWakeContext.paperclipTaskMarkdownAssignment;
}
if (redactedWakeContext.paperclipTaskMarkdownAssignmentCompact) {
context.paperclipTaskMarkdownAssignmentCompact =
redactedWakeContext.paperclipTaskMarkdownAssignmentCompact;
}
}
if (issueRef) {
const digest = (value: string | null | undefined) =>
value?.trim()
? createHash("sha256")
.update(value.trim().replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ""))
.digest("hex")
: null;
const redactedIssue = parseObject(context.paperclipIssue);
context.paperclipTurnContext = {
version: 1,
assignment: {
owner: "task_markdown",
description: {
id: issueRef.id,
revision: digest(readNonEmptyString(redactedIssue.description)),
},
},
events: {
owner: "wake_prompt",
comments: safeWakeComments.map((comment) => ({
id: comment.id,
revision: digest(comment.body),
})),
},
} satisfies PaperclipTurnContext;
} else {
delete context.paperclipTurnContext;
}
// A native run's execution input is immutable once persisted. Recovery must therefore
// restore the workspace bound to that input rather than consulting the issue's current
@@ -21209,12 +21278,21 @@ export function heartbeatService(
context.paperclipTaskMarkdown = appendConcurrentWorkspaceNote(
context.paperclipTaskMarkdown,
);
context.paperclipTaskMarkdownAssignment = appendConcurrentWorkspaceNote(
context.paperclipTaskMarkdownAssignment,
);
if (typeof context.paperclipTaskMarkdownCompact === "string") {
context.paperclipTaskMarkdownCompact =
appendConcurrentWorkspaceNote(
context.paperclipTaskMarkdownCompact,
);
}
if (typeof context.paperclipTaskMarkdownAssignmentCompact === "string") {
context.paperclipTaskMarkdownAssignmentCompact =
appendConcurrentWorkspaceNote(
context.paperclipTaskMarkdownAssignmentCompact,
);
}
logger.info(
{
event: "shared_workspace_concurrent_dispatch",
@@ -23121,6 +23199,50 @@ export function heartbeatService(
(response) => response.id === executionContinuation.trigger.interactionId,
)?.id
: undefined;
const immediateCompletion = (() => {
if (nativeReviewRequest) return { requests: [nativeReviewRequest], sources: [null] };
const { requests, sources } = nativeCompletionRequestsWithSources(
safeWakeComments.length > 0
? safeWakeComments
: safeWakeCommentContext?.body
? [safeWakeCommentContext]
: [],
{
requiredFullWakeCommentCount:
paperclipWakePayload?.fallbackFetchNeeded === true &&
CHAT_PROVIDERS.some(
(provider) =>
provider ===
paperclipWakePayload.externalChatProvider,
) &&
Array.isArray(paperclipWakePayload.commentIds)
? paperclipWakePayload.commentIds.length
: undefined,
},
);
// Preserve every admitted pending chat request while also
// retaining newer user direction materialized by recovery.
// A file-only wake must not inherit an old task objective.
const latestComment =
executionContinuation?.messages.findLast(
(message) =>
message.authorType === "user" &&
!message.createdByRunId &&
!message.deleted &&
message.body.trim().length > 0,
);
const latestRequest = latestComment?.body;
if (
latestRequest &&
!requests.some(
(request) => request === latestRequest.trim(),
)
) {
requests.push(latestRequest.trim());
sources.push(nativeCompletionSource("comment", latestComment!.id, latestRequest));
}
return { requests: requests.length > 0 ? requests : undefined, sources };
})();
// Rebuilding a default contract is not a change in user direction.
// In particular, an upgraded checkpoint may have an intentionally
// authored contract and no continuation envelope yet.
@@ -23139,49 +23261,18 @@ export function heartbeatService(
nativeReviewRequest ?? (currentHumanResponseId
? null
: executionContinuation?.objective ?? safeWakeCommentContext?.body ?? null),
// The ordinary initial objective is selected by the server-owned
// continuation envelope. Carry its explicit description source
// through the singular-request compatibility path; do not infer
// provenance for review requests, answers, or wake fallbacks.
immediateRequestSource: nativeImmediateObjectiveSource({
issueId: issueRef.id,
objectiveSource: executionContinuation?.objectiveSource,
excluded: Boolean(nativeReviewRequest || currentHumanResponseId),
}),
humanResponseId: currentHumanResponseId,
immediateRequests: (() => {
if (nativeReviewRequest) return [nativeReviewRequest];
const requests = nativeCompletionRequestsForComments(
safeWakeComments.length > 0
? safeWakeComments
: safeWakeCommentContext?.body
? [{ body: safeWakeCommentContext.body }]
: [],
{
requiredFullWakeCommentCount:
paperclipWakePayload?.fallbackFetchNeeded === true &&
CHAT_PROVIDERS.some(
(provider) =>
provider ===
paperclipWakePayload.externalChatProvider,
) &&
Array.isArray(paperclipWakePayload.commentIds)
? paperclipWakePayload.commentIds.length
: undefined,
},
);
// Preserve every admitted pending chat request while also
// retaining newer user direction materialized by recovery.
// A file-only wake must not inherit an old task objective.
const latestRequest =
executionContinuation?.messages.findLast(
(message) =>
message.authorType === "user" &&
!message.createdByRunId &&
!message.deleted &&
message.body.trim().length > 0,
)?.body;
if (
latestRequest &&
!requests.some(
(request) => request === latestRequest.trim(),
)
) {
requests.push(latestRequest.trim());
}
return requests.length > 0 ? requests : undefined;
})(),
immediateRequests: immediateCompletion.requests,
immediateRequestSources: immediateCompletion.sources,
});
const taskNativeSessionId = !taskSessionCredentialCompatible ? null : readNonEmptyString(
taskSessionDecodedParams?.sessionId,
@@ -23520,6 +23611,7 @@ export function heartbeatService(
].filter(Boolean).join("\n\n"),
initialCommunicationGuidance: nativeReviewRequest ? null : readNonEmptyString(context.paperclipTaskCommunicationGuidance),
wakePayload: context.paperclipWake,
turnContext: context.paperclipTurnContext,
resumedSession,
previousTurn: (() => {
if (!previousNativeRun || nativeReviewRequest) return null;
@@ -23586,6 +23678,7 @@ export function heartbeatService(
sha256: completionContract.row.canonicalSha256,
schemaVersion: completionContract.row.schemaVersion,
contract: completionContract.contract,
sources: "sources" in completionContract ? completionContract.sources : undefined,
},
runtimeContext: nativeRuntimeContext,
}),
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { buildQueuedCommentQueueSnapshot, decideQueuedCommentQueueSteering } from "./issue-queued-comment-queue.js";
import { buildQueuedCommentQueueSnapshot, decideQueuedCommentQueueSteering, withQueuedCommentIdsInRunContext } from "./issue-queued-comment-queue.js";
describe("decideQueuedCommentQueueSteering", () => {
it("answers unsupported on the legacy protocol", () => {
@@ -115,3 +115,34 @@ describe("buildQueuedCommentQueueSnapshot entry permissions", () => {
expect(queue.entries[0]?.canDiscard).toBe(false);
});
});
describe("withQueuedCommentIdsInRunContext", () => {
it("invalidates every generated task projection and ownership metadata", () => {
const result = withQueuedCommentIdsInRunContext({
issueId: "issue-1",
preserved: "keep",
paperclipWake: { comments: [{ id: "comment-1" }] },
paperclipWakeComment: { id: "comment-1" },
paperclipTaskMarkdown: "historical",
paperclipTaskMarkdownCompact: "historical compact",
paperclipTaskMarkdownAssignment: "assignment",
paperclipTaskMarkdownAssignmentCompact: "assignment compact",
paperclipTurnContext: { version: 1, events: { owner: "wake_prompt" } },
}, ["comment-2"]);
expect(result).toMatchObject({
issueId: "issue-1",
preserved: "keep",
wakeCommentIds: ["comment-2"],
wakeCommentId: "comment-2",
commentId: "comment-2",
});
expect(result).not.toHaveProperty("paperclipWake");
expect(result).not.toHaveProperty("paperclipWakeComment");
expect(result).not.toHaveProperty("paperclipTaskMarkdown");
expect(result).not.toHaveProperty("paperclipTaskMarkdownCompact");
expect(result).not.toHaveProperty("paperclipTaskMarkdownAssignment");
expect(result).not.toHaveProperty("paperclipTaskMarkdownAssignmentCompact");
expect(result).not.toHaveProperty("paperclipTurnContext");
});
});
@@ -95,6 +95,9 @@ export function withQueuedCommentIdsInRunContext(
delete context.paperclipWakeComment;
delete context.paperclipTaskMarkdown;
delete context.paperclipTaskMarkdownCompact;
delete context.paperclipTaskMarkdownAssignment;
delete context.paperclipTaskMarkdownAssignmentCompact;
delete context.paperclipTurnContext;
return context;
}
@@ -1,4 +1,7 @@
import { currentContinuationOrigins } from "./execution-continuation.js";
import {
currentContinuationOrigins,
deliveredContinuationCommentIds,
} from "./execution-continuation.js";
import { assertAgentRunWriteAllowed } from "../agent-run-cancellation.js";
import { connectionIntentDeliveries } from "@paperclipai/db";
import { isDeepStrictEqual } from "node:util";
@@ -7,6 +10,7 @@ import {
asc,
desc,
eq,
gte,
inArray,
isNotNull,
isNull,
@@ -3441,11 +3445,16 @@ export function issueThreadInteractionService(
let originCommentIds: string[] = data.sourceCommentId ? [data.sourceCommentId] : [];
let sourceIdentityContextId: string | null = null;
let sourceRunContext: Record<string, unknown> | null = null;
let sourceRunCreatedAt: Date | null = null;
if (data.sourceRunId) {
const sourceRun = await db
.select({
contextSnapshot: heartbeatRuns.contextSnapshot,
companyId: heartbeatRuns.companyId,
agentId: heartbeatRuns.agentId,
nativeIssueId: heartbeatRuns.nativeIssueId,
createdAt: heartbeatRuns.createdAt,
activeIdentityContextId: heartbeatRuns.activeIdentityContextId,
})
.from(heartbeatRuns)
@@ -3454,6 +3463,22 @@ export function issueThreadInteractionService(
if (!sourceRun || sourceRun.companyId !== issue.companyId) {
throw unprocessable("sourceRunId must belong to the same company");
}
if (data.kind === "ask_user_questions") {
if (actor.agentId && sourceRun.agentId !== actor.agentId) {
throw unprocessable("sourceRunId must belong to the creating agent");
}
const snapshot = sourceRun.contextSnapshot ?? {};
const boundIssueIds = [
sourceRun.nativeIssueId,
snapshot.issueId,
snapshot.taskId,
].filter((value): value is string => typeof value === "string" && value.length > 0);
if (boundIssueIds.some((boundIssueId) => boundIssueId !== issue.id)) {
throw unprocessable("sourceRunId must belong to the same issue");
}
}
sourceRunContext = sourceRun.contextSnapshot;
sourceRunCreatedAt = sourceRun.createdAt;
originCommentIds = [...new Set([...originCommentIds, ...await currentContinuationOrigins(db, issue.companyId, issue.id, sourceRun.contextSnapshot)])];
sourceIdentityContextId = actor.identityContextId ?? sourceRun.activeIdentityContextId;
if (sourceIdentityContextId) {
@@ -3493,6 +3518,42 @@ export function issueThreadInteractionService(
if (!issueRow || isTerminalIssueStatus(issueRow.status)) {
throw conflict("Cannot create an interaction on a closed issue");
}
if (
data.kind === "ask_user_questions" &&
sourceRunContext &&
sourceRunCreatedAt
) {
const delivered = deliveredContinuationCommentIds(sourceRunContext);
if (delivered.known) {
const newerHumanComments = await tx
.select({ id: issueComments.id })
.from(issueComments)
.where(
and(
eq(issueComments.companyId, issue.companyId),
eq(issueComments.issueId, issue.id),
eq(issueComments.authorType, "user"),
isNotNull(issueComments.authorUserId),
ne(issueComments.authorUserId, "board-concierge"),
isNull(issueComments.createdByRunId),
isNull(issueComments.deletedAt),
gte(issueComments.createdAt, sourceRunCreatedAt),
),
);
const undelivered = newerHumanComments.filter(
(comment) => !delivered.ids.has(comment.id),
);
if (undelivered.length > 0) {
throw conflict(
"New user comments arrived after this run's context; continue after queued comments are delivered",
{
reason: "newer_comment_not_delivered",
commentIds: undelivered.map((comment) => comment.id),
},
);
}
}
}
// Validate the plan/document confirmation target inside the same
// transaction (locking the document row) so the latest-revision check
// is atomic with the insert below. A concurrent revision publish can no
+20 -8
View File
@@ -12116,14 +12116,15 @@ export function issueService(db: Db) {
? retryNativeChatReviewPresentation(append)
: append();
}
// Callers supplying a transaction still share the settlement fence.
if (actor.userId && dbOrTx !== db) {
await dbOrTx.select({ id: issues.id }).from(issues).where(eq(issues.id, issueId)).for("update");
}
const issue = await dbOrTx
// The query below locks human comments on caller-owned transactions too,
// sharing the fence with both question creation and Slack settlement.
const issueQuery = dbOrTx
.select({ companyId: issues.companyId, conversationAgentId: issues.conversationAgentId })
.from(issues)
.where(eq(issues.id, issueId))
.where(eq(issues.id, issueId));
// Caller-owned transactions (including chat and review comments) must
// serialize with question creation before inserting the human comment.
const issue = await (actor.userId ? issueQuery.for("update") : issueQuery)
.then((rows: Array<{ companyId: string; conversationAgentId: string | null }>) => rows[0] ?? null);
if (!issue) throw notFound("Issue not found");
@@ -12164,6 +12165,16 @@ export function issueService(db: Db) {
.nullable()
.parse(options?.presentation ?? null);
const createdAt = options?.createdAt ? new Date(options.createdAt) : null;
const validCreatedAt =
createdAt && !Number.isNaN(createdAt.getTime()) ? createdAt : null;
// Use one statement timestamp for both columns when the caller did not
// supply a valid historical timestamp. This keeps the comment's
// recency fields equal even when the surrounding transaction started
// earlier, while preserving imported timestamps and the normal default
// updatedAt behavior for those historical rows.
const currentInsertTimestamp = validCreatedAt
? null
: sql`statement_timestamp()`;
// Invalid/stale run ids must not 500 the insert — null out unknowns.
const createdByRun = await resolveCommentCreatedByRun(
dbOrTx,
@@ -12369,8 +12380,9 @@ export function issueService(db: Db) {
presentation,
metadata,
sourceTrust: options?.sourceTrust ?? null,
...(createdAt && !Number.isNaN(createdAt.getTime())
? { createdAt }
createdAt: validCreatedAt ?? currentInsertTimestamp!,
...(currentInsertTimestamp
? { updatedAt: currentInsertTimestamp }
: {}),
})
.returning();
@@ -2,6 +2,10 @@ import { describe, expect, it } from "vitest";
import {
buildNativeCompletionContract,
buildNativeCompletionContractSources,
nativeCompletionRequestsWithSources,
nativeCompletionSource,
nativeImmediateObjectiveSource,
nativeCompletionRequestsForComments,
resolveNativeCompletionPolicy,
} from "./completion-contracts.js";
@@ -175,3 +179,48 @@ describe("resolveNativeCompletionPolicy", () => {
}
});
});
describe("completion source ownership", () => {
it("selects only an explicitly bound initial description objective", () => {
const source = nativeCompletionSource("description", "task", "Same text");
expect(nativeImmediateObjectiveSource({ issueId: "task", objectiveSource: source, excluded: false })).toEqual(source);
expect(nativeImmediateObjectiveSource({ issueId: "other-task", objectiveSource: source, excluded: false })).toBeNull();
expect(nativeImmediateObjectiveSource({ issueId: "task", objectiveSource: source, excluded: true })).toBeNull();
expect(nativeImmediateObjectiveSource({ issueId: "task", objectiveSource: nativeCompletionSource("comment", "comment", "Same text"), excluded: false })).toBeNull();
});
it("preserves separate identical comment sources and their criterion order", () => {
const comments = [{ id: "first", body: " Repeat. Repeat. " }, { id: "second", body: " Repeat. Repeat. " }];
const { requests, sources } = nativeCompletionRequestsWithSources(comments);
const issue = { id: "task", title: "Task", description: "Brief" };
const contract = buildNativeCompletionContract(issue, { immediateRequests: requests });
expect(contract.criteria).toEqual([
{ id: "pending_comment_1", requirement: "Repeat. Repeat." },
{ id: "pending_comment_2", requirement: "Repeat. Repeat." },
]);
expect(buildNativeCompletionContractSources({ issue, immediateRequests: requests, immediateRequestSources: sources })).toEqual([
{ id: "pending_comment_1", source: nativeCompletionSource("comment", "first", comments[0]!.body) },
{ id: "pending_comment_2", source: nativeCompletionSource("comment", "second", comments[1]!.body) },
]);
});
it("does not infer comment provenance from identical requirement text", () => {
const issue = { id: "task", title: "Task", description: "Same text" };
expect(buildNativeCompletionContractSources({ issue, immediateRequests: ["Same text"] })).toEqual([]);
expect(buildNativeCompletionContractSources({ issue, immediateRequest: "Same text" })).toEqual([]);
expect(buildNativeCompletionContractSources({
issue,
immediateRequest: "Same text",
immediateRequestSource: nativeCompletionSource("description", "task", "Same text"),
})).toEqual([{ id: "objective", source: nativeCompletionSource("description", "task", "Same text") }]);
expect(buildNativeCompletionContractSources({ issue })).toEqual([{ id: "objective", source: nativeCompletionSource("description", "task", "Same text") }]);
expect(buildNativeCompletionContractSources({ issue, humanResponseId: "answer" })).toEqual([]);
});
it("keeps attachment-only and incomplete-wake requirements independent", () => {
const comments = [{ id: "file", body: "", attachments: [{ id: "attachment" }] }];
expect(nativeCompletionRequestsWithSources(comments).sources).toEqual([null]);
expect(nativeCompletionRequestsWithSources(comments, { requiredFullWakeCommentCount: 8 }).sources).toEqual([null]);
});
});
@@ -1,38 +1,67 @@
import { createHash } from "node:crypto";
import { and, desc, eq, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { completionContracts } from "@paperclipai/db";
import type { StrictCompletionContractInput } from "../../vendor/paperclip-runner/index.js";
import type { NativeCompletionSource, StrictCompletionContractInput } from "../../vendor/paperclip-runner/index.js";
import { nativeSha256 } from "./canonical.js";
export const NATIVE_COMPLETION_CONTRACT_SCHEMA = "paperclip.completion-contract.v1";
export const NATIVE_COMPLETION_POLICY_VERSION = "phase6-v4";
export function nativeCompletionRequestsForComments(
comments: readonly {
body: string;
attachments?: readonly unknown[];
}[],
type CompletionComment = {
id?: string;
body: string;
attachments?: readonly unknown[];
};
export function nativeCompletionSource(kind: NativeCompletionSource["kind"], id: string, content: string): NativeCompletionSource {
return { kind, id, revision: createHash("sha256").update(content.trim()).digest("hex") };
}
/** Select only the server-owned description source for the ordinary objective path. */
export function nativeImmediateObjectiveSource(input: {
issueId: string;
objectiveSource?: {
kind: "comment" | "description" | "title";
id: string;
revision: string | null;
} | null;
excluded: boolean;
}): NativeCompletionSource | null {
const source = input.objectiveSource;
return !input.excluded && source?.kind === "description" && source.id === input.issueId && source.revision
? { kind: "description", id: source.id, revision: source.revision }
: null;
}
/** The same source operation produces both the requirement and its provenance. */
export function nativeCompletionRequestsWithSources(
comments: readonly CompletionComment[],
options: { requiredFullWakeCommentCount?: number } = {},
): string[] {
if (
Number.isSafeInteger(options.requiredFullWakeCommentCount) &&
(options.requiredFullWakeCommentCount ?? 0) > 0
) {
return [
): { requests: string[]; sources: Array<NativeCompletionSource | null> } {
if (Number.isSafeInteger(options.requiredFullWakeCommentCount) && (options.requiredFullWakeCommentCount ?? 0) > 0) {
return { requests: [
`Read every server-bound pending external-chat comment with read_current_wake_comments until complete=true, then answer all ${options.requiredFullWakeCommentCount} accepted comments in order without omitting a request. Report any unavailable attachment honestly; metadata alone is not its content.`,
];
], sources: [null] };
}
return comments.flatMap((comment, index) => {
const entries = comments.flatMap((comment, index) => {
const body = comment.body.trim();
if (body) return [body];
// A file-only message is still the current request. Never fall back to an
// older imperative title or treat a user-controlled filename as policy.
if (body) return [{ request: body, source: comment.id ? nativeCompletionSource("comment", comment.id, body) : null }];
// A file-only message has an independent inspection requirement.
return comment.attachments?.length
? [`Inspect and respond to the attached file(s) on pending comment ${index + 1}.`]
? [{ request: `Inspect and respond to the attached file(s) on pending comment ${index + 1}.`, source: null }]
: [];
});
return { requests: entries.map((entry) => entry.request), sources: entries.map((entry) => entry.source) };
}
export function nativeCompletionRequestsForComments(
comments: readonly CompletionComment[],
options: { requiredFullWakeCommentCount?: number } = {},
): string[] {
return nativeCompletionRequestsWithSources(comments, options).requests;
}
export function resolveNativeCompletionPolicy(issue: {
@@ -103,7 +132,10 @@ export async function ensureNativeCompletionContract(input: {
};
actorId: string;
immediateRequest?: string | null;
/** Provenance for a singular server-selected request, when explicitly known. */
immediateRequestSource?: NativeCompletionSource | null;
immediateRequests?: readonly string[] | null;
immediateRequestSources?: readonly (NativeCompletionSource | null)[];
humanResponseId?: string | null;
}) {
return input.db.transaction(async (tx) => {
@@ -137,7 +169,7 @@ export async function ensureNativeCompletionContract(input: {
contract: latestCandidate,
});
if (latest?.canonicalSha256 === latestCandidateSha256) {
return { row: latest, contract: latestCandidate };
return { row: latest, contract: latestCandidate, sources: buildNativeCompletionContractSources(input) };
}
const nextRevision = latest ? latest.revision + 1 : 1;
@@ -168,6 +200,34 @@ export async function ensureNativeCompletionContract(input: {
supersedesContractId: latest?.id ?? null,
}).returning();
if (!row) throw new Error("native_completion_contract_not_persisted");
return { row, contract };
return { row, contract, sources: buildNativeCompletionContractSources(input) };
});
}
export function buildNativeCompletionContractSources(input: {
issue: { id: string; description: string | null };
immediateRequest?: string | null;
immediateRequestSource?: NativeCompletionSource | null;
immediateRequests?: readonly string[] | null;
immediateRequestSources?: readonly (NativeCompletionSource | null)[];
humanResponseId?: string | null;
}): Array<{ id: string; source: NativeCompletionSource }> {
const requests = (input.immediateRequests ?? (input.immediateRequest == null ? [] : [input.immediateRequest]))
.map((body, index) => ({
body: body.trim(),
source: input.immediateRequests
? input.immediateRequestSources?.[index]
: input.immediateRequestSource,
}))
.filter((entry) => entry.body.length > 0);
if (requests.length > 0) {
return requests.flatMap((entry, index) => entry.source ? [{
id: requests.length === 1 ? "objective" : `pending_comment_${index + 1}`,
source: entry.source,
}] : []);
}
return !input.humanResponseId?.trim() && input.issue.description?.trim()
? [{ id: "objective", source: nativeCompletionSource("description", input.issue.id, input.issue.description) }]
: [];
}
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
import type { ExecutionContinuationEnvelope, AskUserQuestionsInteraction } from "@paperclipai/shared";
import { formatDurableQuestionResponseSummary } from "../question-response-delivery.js";
import { buildNativeCompletionContract } from "./completion-contracts.js";
import { nativeCompletionSource, buildNativeCompletionContract } from "./completion-contracts.js";
import { renderPaperclipWakePrompt } from "@paperclipai/adapter-utils/server-utils";
import { buildNativeExecutionInput } from "./native-execution-input.js";
import { nativeRuntimeContextFixture } from "./runtime-context.test-fixture.js";
@@ -545,3 +545,40 @@ describe("follow-up context size", () => {
expect(resumed.length + JSON.stringify(contract).length).toBeLessThan(fresh.length);
});
});
describe("native completion references", () => {
const source = nativeCompletionSource("description", "task", "Repeat. Repeat.");
const args: Parameters<typeof buildNativeExecutionInput>[0] = {
companyId: "company", runId: "run", agentId: "agent",
issue: { id: "task", identifier: "PAP-1", title: "Brief", description: "Repeat. Repeat.", workMode: "standard" },
taskPrompt: "Issue description:\nRepeat. Repeat.",
workspace: { id: "workspace", cwd: "/workspace", repoUrl: null, repoRef: null, branchName: null },
normalizedSessionId: null,
runtimeContext: nativeRuntimeContextFixture(),
completionContract: {
id: "contract", sha256: "a".repeat(64), schemaVersion: "paperclip.completion-contract.v1",
contract: { revision: "1", objective: "Brief", criteria: [{ id: "objective", requirement: "Repeat. Repeat." }] },
sources: [{ id: "objective", source }],
},
};
it("binds only source identities and revisions attested by the task renderer", () => {
const input = buildNativeExecutionInput({ ...args, turnContext: {
version: 1,
assignment: { owner: "task_markdown", description: { id: source.id, revision: source.revision } },
events: { owner: "wake_prompt", comments: [] },
} });
expect(input.completionSources).toMatchObject({ contractRevision: "1", criteria: [{ id: "objective", source }] });
expect(input.completionContract.contract).toEqual(args.completionContract.contract);
expect(input.task.description).toBe("Repeat. Repeat.");
});
it.each([
undefined,
{ version: 1, assignment: { owner: "task_markdown", description: { id: "another-task", revision: source.revision } } },
{ version: 1, assignment: { owner: "task_markdown", description: { id: source.id, revision: "stale" } } },
])("keeps the full requirement when provenance is absent or stale", (turnContext) => {
const input = buildNativeExecutionInput({ ...args, turnContext });
expect(input.completionSources).toBeUndefined();
expect(input.completionContract.contract).toEqual(args.completionContract.contract);
});
});
@@ -1,9 +1,12 @@
import type { PaperclipTurnContext } from "@paperclipai/adapter-utils/server-utils";
import { createHash } from "node:crypto";
import { buildNativeContinuationPrompt } from "./native-continuation.js";
import type {
NativeAcpxAgent,
NativeAcpxPermissionMode,
NativeCodexApprovalPolicy,
NativeExecutionInputV4,
NativeExecutionInputV5,
NativeCompletionSource,
NativeInteractionResponseEnvelope,
NativeOpenCodePermissionMode,
NativePlanningContext,
@@ -17,7 +20,7 @@ import {
import {
isPaperclipExternalChatContractTurn,
isPaperclipExternalChatQuestionResponseTurn,
renderPaperclipWakePrompt,
selectPaperclipPromptSections,
} from "@paperclipai/adapter-utils/server-utils";
const NATIVE_GITHUB_ATTACHMENT_RECOVERY_GUIDANCE = [
@@ -46,6 +49,8 @@ export function buildNativeExecutionInput(input: {
* that legacy adapters place in their provider prompt.
*/
wakePayload?: unknown;
/** Additive source ownership emitted by the server task/wake builders. */
turnContext?: unknown;
resumedSession?: boolean;
previousTurn?: { runId: string; task: { title: string; description: string | null } } | null;
conversationMode?: boolean;
@@ -65,20 +70,20 @@ export function buildNativeExecutionInput(input: {
acpxPermissionMode?: NativeAcpxPermissionMode;
model?: string | null;
managedProfile?: Extract<
NativeExecutionInputV4["provider"],
NativeExecutionInputV5["provider"],
{ kind: "claude_managed" }
>["managedProfile"];
maxSessionListCostUsd?: number;
agentCoreProfile?: Extract<
NativeExecutionInputV4["provider"],
NativeExecutionInputV5["provider"],
{ kind: "aws_agentcore" }
>["agentCoreProfile"];
maxEstimatedSessionCostUsd?: number;
invocationLimits?: Extract<
NativeExecutionInputV4["provider"],
NativeExecutionInputV5["provider"],
{ kind: "aws_agentcore" }
>["invocationLimits"];
lifecyclePolicy?: NativeExecutionInputV4["session"]["lifecyclePolicy"];
lifecyclePolicy?: NativeExecutionInputV5["session"]["lifecyclePolicy"];
executionMode?: "default" | "plan";
planningContext?: NativePlanningContext | null;
interactionResponses?: NativeInteractionResponseEnvelope[];
@@ -87,9 +92,10 @@ export function buildNativeExecutionInput(input: {
sha256: string;
schemaVersion: string;
contract: StrictCompletionContractInput;
sources?: Array<{ id: string; source: NativeCompletionSource }>;
};
runtimeContext: NativeRuntimeContextSnapshot;
}): NativeExecutionInputV4 {
}): NativeExecutionInputV5 {
if (input.issue.workMode !== "standard" && input.issue.workMode !== "planning" && input.issue.workMode !== "ask") {
throw new Error("native_execution_input_invalid: issue work mode must be standard, planning, or ask");
}
@@ -148,10 +154,15 @@ export function buildNativeExecutionInput(input: {
},
}
: input.wakePayload;
const wakePrompt = renderPaperclipWakePrompt(wakePayload, {
// Build the full bootstrap through the same owner as legacy adapters.
// Verified native resume selection stays at the existing session boundary.
const { taskContextNote, wakePrompt } = selectPaperclipPromptSections({
paperclipTaskMarkdownAssignment: input.taskPrompt,
paperclipWake: wakePayload,
conversationMode: input.conversationMode,
}, {
resumedSession: false,
conversationMode: input.conversationMode === true,
suppressIssueDescription: input.taskPrompt.trim().length > 0,
includeCommunicationGuidance: false,
nativeWakeReaderAvailable: true,
});
const externalChatTurn =
@@ -165,12 +176,15 @@ export function buildNativeExecutionInput(input: {
externalChatTurn && wake?.externalChatProvider === "github"
? NATIVE_GITHUB_ATTACHMENT_RECOVERY_GUIDANCE
: "",
input.taskPrompt.trim(),
taskContextNote,
]
.filter((section) => section.length > 0)
.join("\n\n");
const completionSources = !externalChatTurn && !input.conversationMode && input.taskPrompt.trim()
? verifiedCompletionSources(input.turnContext, input.completionContract.sources ?? [])
: [];
return parseNativeExecutionInput({
schema: "paperclip.native-execution-input.v4",
schema: "paperclip.native-execution-input.v5",
...(input.initialCommunicationGuidance ? { initialCommunicationGuidance: input.initialCommunicationGuidance } : {}),
...(input.resumedSession && input.previousTurn && !input.conversationMode ? {
continuationPrompt: buildNativeContinuationPrompt({
@@ -268,9 +282,36 @@ export function buildNativeExecutionInput(input: {
model: input.model ?? null,
approvalPolicy: input.codexApprovalPolicy ?? "never",
},
completionContract: input.completionContract,
completionContract: {
id: input.completionContract.id,
sha256: input.completionContract.sha256,
schemaVersion: input.completionContract.schemaVersion,
contract: input.completionContract.contract,
},
...(completionSources.length ? { completionSources: {
promptSha256: createHash("sha256").update(taskPrompt).digest("hex"),
contractRevision: input.completionContract.contract.revision,
criteria: completionSources,
} } : {}),
interactionResponses: input.interactionResponses ?? [],
credentialBindings: [],
runtimeContext: input.runtimeContext,
}) as NativeExecutionInputV4;
}) as NativeExecutionInputV5;
}
/** Verify source identities and revisions, never guess provenance from requirement text. */
function verifiedCompletionSources(
value: unknown,
sources: Array<{ id: string; source: NativeCompletionSource }>,
): Array<{ id: string; source: NativeCompletionSource }> {
if (!value || typeof value !== "object" || Array.isArray(value)) return [];
const context = value as Partial<PaperclipTurnContext>;
if (context.version !== 1) return [];
return sources.filter(({ source }) => {
if (source.kind === "description") {
return context.assignment?.owner === "task_markdown" && context.assignment.description?.id === source.id && context.assignment.description.revision === source.revision;
}
return context.events?.owner === "wake_prompt" && Array.isArray(context.events.comments) && context.events.comments.some((comment) => comment.id === source.id && comment.revision === source.revision);
});
}
@@ -102,7 +102,21 @@ const support = externalDatabaseUrl
nativeIssueId: issueId,
runtimeMode: "native",
status: "failed",
contextSnapshot: { issueId },
contextSnapshot: {
issueId,
preservedRecoveryContext: true,
paperclipWake: { comments: [{ id: "stale-comment" }] },
paperclipWakeComment: { id: "stale-comment" },
paperclipTaskMarkdown: "stale historical task",
paperclipTaskMarkdownCompact: "stale historical compact task",
paperclipTaskMarkdownAssignment: "stale assignment task",
paperclipTaskMarkdownAssignmentCompact: "stale assignment compact task",
paperclipTurnContext: {
version: 1,
assignment: { owner: "task_markdown" },
events: { owner: "wake_prompt", comments: [{ id: "stale-comment" }] },
},
},
runnerProfileJson: {
recoveryEventInventoryVersion: 1,
nativeExecutionInput: {
@@ -170,6 +184,21 @@ const support = externalDatabaseUrl
if (mode === "verified") {
expect(retire).toHaveBeenCalledOnce();
expect(task!.status).toBe("in_progress");
expect(successors[0]!.contextSnapshot).toMatchObject({
issueId: source.issueId,
preservedRecoveryContext: true,
});
for (const key of [
"paperclipWake",
"paperclipWakeComment",
"paperclipTaskMarkdown",
"paperclipTaskMarkdownCompact",
"paperclipTaskMarkdownAssignment",
"paperclipTaskMarkdownAssignmentCompact",
"paperclipTurnContext",
]) {
expect(successors[0]!.contextSnapshot).not.toHaveProperty(key);
}
const continuation = await buildExecutionContinuation({
db, companyId: source.companyId, issueId: source.issueId, agentId: source.agentId,
context: successors[0]!.contextSnapshot!, summary: null, exposeLowTrustRaw: false,
@@ -375,6 +375,7 @@ export async function reconcileSafeNativeReplacements(
"explicitUserContinuation", "wakeCommentId", "wakeCommentIds", "commentId",
"commentIds", "latestCommentId", "resumeIntent", "followUpRequested",
"paperclipWake", "paperclipWakeComment", "paperclipTaskMarkdown", "paperclipTaskMarkdownCompact",
"paperclipTaskMarkdownAssignment", "paperclipTaskMarkdownAssignmentCompact", "paperclipTurnContext",
]) delete predecessorContext[key];
const context = {
...predecessorContext,
@@ -12307,8 +12307,8 @@ async function createRunnerdBackendWithinSessionClaim(
acpxAgent: input.execution.provider.agent,
acpxPermissionMode: input.execution.provider.permissionMode,
acpxPermissionModePinned:
input.execution.schema ===
"paperclip.native-execution-input.v4",
input.execution.schema === "paperclip.native-execution-input.v4" ||
input.execution.schema === "paperclip.native-execution-input.v5",
acpxRuntimeDirectory: remoteRunnerFilesystemRoot
? posix.join(remoteRunnerFilesystemRoot, "acpx")
: resolve(
@@ -1755,6 +1755,35 @@ describe("rebindNativeSessionCheckpoint", () => {
},
);
it.each([
["paperclip.native-execution-input.v4", "paperclip.native-execution-input.v5"],
["paperclip.native-execution-input.v5", "paperclip.native-execution-input.v4"],
] as const)("retains a recoverable %s session when the constructor defaults to %s", (priorSchema, currentSchema) => {
const prior = previousRun();
const profile = prior.runnerProfileJson as Record<string, unknown>;
profile.nativeExecutionInput = { ...execution(previousRunId), schema: priorSchema };
const checkpoint = profile.sessionCheckpoint as Record<string, unknown>;
checkpoint.goal = { status: "paused", objective: "Preserve the existing durable work" };
const before = structuredClone(prior);
const result = buildNativeExecutionWithCheckpoint({
previousRun: prior,
normalizedSessionId,
buildExecution: ({ normalizedSessionId: sessionId, resumedSession }) => parseNativeExecutionInput({
...execution(currentRunId), schema: currentSchema,
session: { ...execution(currentRunId).session, normalizedSessionId: sessionId },
continuationPrompt: resumedSession ? "New direction only; do not replay completed actions" : null,
}),
});
expect(result.execution.schema).toBe(priorSchema);
expect(result.normalizedSessionId).toBe(normalizedSessionId);
expect(result.checkpoint).toMatchObject({
providerSessionId: "provider-thread-123",
providerRecoveryPolicy: "same_session_only",
goal: { status: "paused", objective: "Preserve the existing durable work" },
});
expect(prior).toEqual(before);
});
it("keeps a valid checkpoint and does not rebuild the resumed task", () => {
const calls: boolean[] = [];
const result = buildNativeExecutionWithCheckpoint({
@@ -2514,15 +2543,15 @@ describe("buildNativeExecutionInput wake projection", () => {
});
expect(codex).toMatchObject({
schema: "paperclip.native-execution-input.v4",
schema: "paperclip.native-execution-input.v5",
provider: { kind: "codex", approvalPolicy: "on-request" },
});
expect(opencode).toMatchObject({
schema: "paperclip.native-execution-input.v4",
schema: "paperclip.native-execution-input.v5",
provider: { kind: "opencode", permissionMode: "ask" },
});
expect(acpx).toMatchObject({
schema: "paperclip.native-execution-input.v4",
schema: "paperclip.native-execution-input.v5",
provider: { kind: "acpx", permissionMode: "deny-all" },
});
expect(claudeManaged).toMatchObject({
@@ -399,6 +399,22 @@ export function buildNativeExecutionWithCheckpoint(input: {
normalizedSessionId: input.normalizedSessionId,
resumedSession: input.previousRun !== null,
});
// A presentation-only upgrade must not rotate a healthy provider session or
// lose a durable goal. Keep its v4/v5 format until that session naturally ends.
// All ordinary identity, workspace, provider, tool and recovery checks still apply.
if (input.previousRun && (execution.schema === "paperclip.native-execution-input.v4" || execution.schema === "paperclip.native-execution-input.v5")) {
const previousSchema = record(record(input.previousRun.runnerProfileJson).nativeExecutionInput).schema;
if ((previousSchema === "paperclip.native-execution-input.v4" || previousSchema === "paperclip.native-execution-input.v5") && previousSchema !== execution.schema) {
const { completionSources: _sources, ...common } = execution as typeof execution & { completionSources?: unknown };
const retainedFormat = parseNativeExecutionInput({ ...common, schema: previousSchema });
const retainedCheckpoint = rebindNativeSessionCheckpoint({
previousRun: input.previousRun,
currentExecution: retainedFormat,
executionTargetKind: input.executionTargetKind,
});
if (retainedCheckpoint) return { execution: retainedFormat, checkpoint: retainedCheckpoint, normalizedSessionId: input.normalizedSessionId };
}
}
const checkpoint = input.previousRun
? rebindNativeSessionCheckpoint({
previousRun: input.previousRun,
@@ -9,6 +9,7 @@ import { startRunnerApiTestServer } from "../../__tests__/helpers/runner-api-ser
import { createRunnerdCodexTransport, defaultCapabilityRunnerdBinary } from "../../vendor/paperclip-runner/index.js";
import { runnerApiCatalog } from "./runner-api-catalog.js";
import { registerRunnerPrpAuthority } from "../../realtime/runner-prp-ws.js";
import { createLocalAgentJwt } from "../../agent-auth-jwt.js";
import { RUNNER_API_RESPONSE_MAX_BYTES, RUNNER_API_RESPONSE_RUN_MAX_BYTES } from "./runner-api-response-limits.js";
import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js";
@@ -510,6 +511,111 @@ else if(m.id!==undefined) send({id:m.id,result:{}});
expect((await fixture.snapshot()).comments).toEqual(expect.arrayContaining([expect.objectContaining({ body: "Identity proof", authorAgentId: fixture.agentId, authorUserId: null })]));
});
it("rejects a stale source-run question over public HTTP and accepts it from the next run", async () => {
const localTrustedServer = await startRunnerApiTestServer({ deploymentMode: "local_trusted" });
try {
const fixture = await localTrustedServer.fixture({
disableWakeOnDemand: true,
contextSnapshot: { paperclipWake: { comments: [] } },
});
const sourceToken = createLocalAgentJwt(
fixture.agentId,
fixture.companyId,
"paperclip_runner",
fixture.runId,
);
expect(sourceToken).toBeTruthy();
const requestHeaders = (token: string) => ({
authorization: `Bearer ${token}`,
"content-type": "application/json",
"x-paperclip-run-id": fixture.runId,
});
const humanCommentResponse = await fetch(
`${fixture.apiUrl}/api/issues/${fixture.issueId}/comments`,
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ body: "Human direction committed after the old wake." }),
},
);
expect(humanCommentResponse.status).toBe(201);
const humanComment = await humanCommentResponse.json() as { id: string; authorUserId?: string | null; authorAgentId?: string | null; createdByRunId?: string | null };
expect(humanComment).toMatchObject({ authorUserId: "local-board", authorAgentId: null, createdByRunId: null });
const questionPayload = {
kind: "ask_user_questions",
idempotencyKey: `stale-source-question-${fixture.runId}`,
continuationPolicy: "wake_assignee",
payload: {
version: 1,
title: "One real question",
questions: [{
id: "scope",
prompt: "Choose a scope.",
selectionMode: "single",
required: true,
options: [{ id: "small", label: "Small" }],
}],
},
};
const staleResponse = await fetch(
`${fixture.apiUrl}/api/issues/${fixture.issueId}/interactions`,
{ method: "POST", headers: requestHeaders(sourceToken!), body: JSON.stringify(questionPayload) },
);
expect(staleResponse.status).toBe(409);
const staleBody = await staleResponse.json() as { details?: { reason?: string; commentIds?: string[] } };
expect(staleBody.details).toMatchObject({ reason: "newer_comment_not_delivered", commentIds: [humanComment.id] });
const afterStale = await fetch(`${fixture.apiUrl}/api/issues/${fixture.issueId}/interactions`);
expect(afterStale.status).toBe(200);
expect(await afterStale.json()).toEqual([]);
const successorRunId = randomUUID();
await localTrustedServer.db.insert(heartbeatRuns).values({
id: successorRunId,
companyId: fixture.companyId,
agentId: fixture.agentId,
status: "running",
runtimeMode: "native",
nativeIssueId: fixture.issueId,
invocationSource: "continuation",
triggerDetail: "comment",
contextSnapshot: { issueId: fixture.issueId, paperclipWake: { comments: [{ id: humanComment.id }] } },
});
await localTrustedServer.db.update(issues).set({ executionRunId: successorRunId, checkoutRunId: successorRunId }).where(eq(issues.id, fixture.issueId));
const successorToken = createLocalAgentJwt(
fixture.agentId,
fixture.companyId,
"paperclip_runner",
successorRunId,
);
expect(successorToken).toBeTruthy();
const acceptedResponse = await fetch(
`${fixture.apiUrl}/api/issues/${fixture.issueId}/interactions`,
{
method: "POST",
headers: { ...requestHeaders(successorToken!), "x-paperclip-run-id": successorRunId },
body: JSON.stringify({ ...questionPayload, idempotencyKey: `fresh-source-question-${successorRunId}` }),
},
);
const acceptedText = await acceptedResponse.text();
expect(acceptedResponse.status, acceptedText).toBe(201);
const accepted = JSON.parse(acceptedText) as { id: string; status: string; sourceRunId: string };
expect(accepted).toMatchObject({ status: "pending", sourceRunId: successorRunId });
const answerResponse = await fetch(
`${fixture.apiUrl}/api/issues/${fixture.issueId}/interactions/${accepted.id}/respond`,
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ answers: [{ questionId: "scope", optionIds: ["small"] }] }),
},
);
expect(answerResponse.status).toBe(200);
expect((await answerResponse.json() as { status: string }).status).toBe("answered");
} finally {
await localTrustedServer.close();
}
});
it("creates child tasks after seeding and preserves company numbering", async () => {
const fixture = await server.fixture();
await expect(fixture.authority.execute({ tool: "create_task", callId: "child", arguments: { title: "Verify release notes", description: "Check before shipping.", assigneeActorId: null, idempotencyKey: "child" } })).resolves.toBeDefined();
+3
View File
@@ -31,6 +31,9 @@ export type {
NativeCodexApprovalPolicy,
NativeExecutionInput,
NativeExecutionInputV4,
NativeExecutionInputV5,
NativeCompletionSource,
NativeCompletionSources,
NativeInteractionResponseEnvelope,
NativeOpenCodePermissionMode,
NativePlanningContext,