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

@@ -1,6 +1,7 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { createPromptContextFixture } from "@paperclipai/adapter-utils/test-fixtures/prompt-context";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { AdapterExecutionContext, AdapterInvocationMeta } from "@paperclipai/adapter-utils";
import { runChildProcess } from "@paperclipai/adapter-utils/server-utils";
@@ -197,6 +198,22 @@ class FakeRuntime {
}
}
class MissingResumeRuntime extends FakeRuntime {
override async ensureSession(input: {
sessionKey: string;
agent: string;
mode: "persistent" | "oneshot";
cwd?: string;
resumeSessionId?: string;
}): Promise<FakeRuntimeHandle> {
if (input.resumeSessionId) {
this.ensureInputs.push(input);
throw new Error("resume session not found");
}
return super.ensureSession(input);
}
}
async function makeTempRoot(prefix: string) {
const root = await fs.mkdtemp(path.join(os.tmpdir(), prefix));
tempRoots.push(root);
@@ -1220,6 +1237,175 @@ describe("claude_local ACP lane", () => {
});
});
it("sends assignment-owned markdown and ordered distinct wake comments at the ACP boundary", async () => {
const root = await makeTempRoot("paperclip-claude-acp-context-owner-");
const runtimes: FakeRuntime[] = [];
const execute = createClaudeAcpExecutor({
createRuntime: (options: FakeRuntimeOptions) => {
const runtime = new FakeRuntime(options);
runtimes.push(runtime);
return runtime as never;
},
});
const issue = {
id: "issue-1",
identifier: "PAP-902",
title: "Repeat phrase Repeat phrase",
description: "Repeat phrase Repeat phrase",
};
const comments = [
{ id: "comment-a", body: "Same event body." },
{ id: "comment-b", body: "Same event body." },
];
// The adapter receives server-rendered fields. Keep the server builder's
// own tests in the server package; adapter packages compile independently.
const assignmentMarkdown = [
"Paperclip task context:",
`- Issue: ${JSON.stringify(issue.identifier)}`,
`- Title: ${JSON.stringify(issue.title)}`,
"", "Issue description:", "```text", issue.description, "```",
].join("\n");
const historicalMarkdown = [
assignmentMarkdown,
...comments.map((comment) => `${comment.id}: ${comment.body}`),
].join("\n");
const result = await execute(buildContext(root, {
context: {
issueId: issue.id,
paperclipTaskMarkdown: historicalMarkdown,
paperclipTaskMarkdownAssignment: assignmentMarkdown,
paperclipWake: {
reason: "issue_commented",
issue: { ...issue, status: "in_progress" },
comments: comments.map((comment, index) => ({
...comment,
issueId: issue.id,
createdAt: `2026-09-21T00:0${index}: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" },
],
},
},
paperclipWorkspace: { cwd: root, source: "project_workspace", workspaceId: "workspace-1" },
},
}));
expect(result.exitCode).toBe(0);
const prompt = String(runtimes[0]?.startInputs[0]?.text ?? "");
expect(prompt.split("Same event body.")).toHaveLength(3);
expect(prompt.indexOf("comment comment-a")).toBeLessThan(prompt.indexOf("comment comment-b"));
expect(prompt).toContain("Repeat phrase Repeat phrase");
});
it("delivers owned assignment and current events through fresh and healthy resumed ACP turns", async () => {
const root = await makeTempRoot("paperclip-claude-acp-owned-context-");
const runtimes: FakeRuntime[] = [];
const fixture = createPromptContextFixture();
const context = {
...fixture,
issueId: "issue-1",
paperclipWorkspace: { cwd: root, source: "project_workspace", workspaceId: "workspace-1" },
};
const execute = createClaudeAcpExecutor({
createRuntime: (options: FakeRuntimeOptions) => {
const runtime = new FakeRuntime(options);
runtimes.push(runtime);
return runtime as never;
},
});
const fresh = await execute(buildContext(root, { context }));
const freshPrompt = String(runtimes[0]?.startInputs[0]?.text ?? "");
expect(fresh.exitCode).toBe(0);
expect(freshPrompt).toContain(context.paperclipTaskMarkdownAssignment);
expect(freshPrompt.split(context.paperclipTaskMarkdownAssignment).length).toBe(2);
expect(freshPrompt).toContain(context.paperclipTaskCommunicationGuidance);
expect(freshPrompt).not.toContain(context.paperclipTaskMarkdownAssignmentCompact);
expect(freshPrompt).toContain("\"id\":\"comment-first\"");
expect(freshPrompt).toContain("\"id\":\"comment-second\"");
expect(freshPrompt).toContain("\"id\":\"comment-scope\"");
expect(freshPrompt.indexOf("\"id\":\"comment-first\"")).toBeLessThan(freshPrompt.indexOf("\"id\":\"comment-second\""));
expect(freshPrompt.indexOf("\"id\":\"comment-second\"")).toBeLessThan(freshPrompt.indexOf("\"id\":\"comment-scope\""));
expect(freshPrompt.split("Append the same ledger entry.")).toHaveLength(3);
expect(freshPrompt.split(fixture.paperclipWake.issue.description)).toHaveLength(2);
expect(freshPrompt).not.toContain('"objective":"');
expect(freshPrompt).toContain("Untrusted continuation evidence");
expect(freshPrompt).toContain("receipt-1");
const resumed = await execute(buildContext(root, {
runtime: {
sessionId: fresh.sessionId ?? null,
sessionParams: fresh.sessionParams ?? null,
sessionDisplayId: fresh.sessionDisplayId ?? null,
taskKey: "PAP-1",
},
context,
}));
const resumedPrompt = String(runtimes[1]?.startInputs[0]?.text ?? "");
expect(resumed.exitCode).toBe(0);
expect(runtimes[1]?.ensureInputs[0]?.resumeSessionId).toBe("acp-1");
expect(resumedPrompt).toContain(context.paperclipTaskMarkdownAssignmentCompact);
expect(resumedPrompt).not.toContain(context.paperclipTaskCommunicationGuidance);
expect(resumedPrompt).not.toContain("\"id\":\"comment-first\"");
expect(resumedPrompt).toContain("\"id\":\"comment-second\"");
expect(resumedPrompt).toContain("\"id\":\"comment-scope\"");
expect(resumedPrompt.indexOf("\"id\":\"comment-second\"")).toBeLessThan(resumedPrompt.indexOf("\"id\":\"comment-scope\""));
});
it("restores the full assignment and current event history when a resume session is missing", async () => {
const root = await makeTempRoot("paperclip-claude-acp-missing-resume-context-");
const runtimes: MissingResumeRuntime[] = [];
const assignment = "## Owned assignment\n\nRebuild the launch card. Rebuild the launch card.";
const compact = "## Compact assignment";
const context = {
issueId: "issue-1",
paperclipTaskMarkdownAssignment: assignment,
paperclipTaskMarkdownAssignmentCompact: compact,
paperclipTaskCommunicationGuidance: "Explain the next step before starting work.",
paperclipWake: {
reason: "issue_commented",
issue: { id: "issue-1", identifier: "PAP-1", title: "Launch card", description: "Rebuild the launch card.", status: "in_progress" },
comments: [{ id: "comment-retry", body: "Preserve this retry request." }],
commentWindow: { requestedCount: 1, includedCount: 1, missingCount: 0 },
fallbackFetchNeeded: false,
},
paperclipWorkspace: { cwd: root, source: "project_workspace", workspaceId: "workspace-1" },
};
const execute = createClaudeAcpExecutor({
createRuntime: (options: FakeRuntimeOptions) => {
const runtime = new MissingResumeRuntime(options);
runtimes.push(runtime);
return runtime as never;
},
});
const first = await execute(buildContext(root, { context }));
const retry = await execute(buildContext(root, {
runtime: {
sessionId: first.sessionId ?? null,
sessionParams: first.sessionParams ?? null,
sessionDisplayId: first.sessionDisplayId ?? null,
taskKey: "PAP-1",
},
context,
}));
const retryPrompt = String(runtimes[1]?.startInputs[0]?.text ?? "");
expect(retry.exitCode).toBe(0);
expect(runtimes[1]?.ensureInputs.map(({ resumeSessionId }) => resumeSessionId)).toEqual(["acp-1", undefined]);
expect(retryPrompt).toContain(assignment);
expect(retryPrompt).not.toContain(compact);
expect(retryPrompt).toContain("Preserve this retry request.");
});
it("delivers the issue description exactly once per prompt and compacts non-assignment resume deltas", async () => {
const root = await makeTempRoot("paperclip-claude-acp-brief-");
const runtimes: FakeRuntime[] = [];
@@ -77,6 +77,7 @@ vi.mock("@paperclipai/adapter-utils/execution-target", async () => {
};
});
import { createPromptContextFixture } from "@paperclipai/adapter-utils/test-fixtures/prompt-context";
import { execute } from "./execute.js";
import { resetClaudeCliCapabilitiesCacheForTests } from "./cli-capabilities.js";
@@ -538,4 +539,80 @@ describe("claude remote execution", () => {
});
});
it("reselects the full assignment and bootstrap guidance after a failed resume", async () => {
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-claude-cli-fallback-context-"));
cleanupDirs.push(rootDir);
const workspaceDir = path.join(rootDir, "workspace");
await mkdir(workspaceDir, { recursive: true });
runChildProcess
.mockResolvedValueOnce({
exitCode: 1,
signal: null,
timedOut: false,
stdout: JSON.stringify({
type: "result",
session_id: "12345678-1234-4abc-9def-123456789012",
is_error: true,
subtype: "error_during_execution",
result: "No conversation found with session id 12345678-1234-4abc-9def-123456789012",
}),
stderr: "",
pid: 123,
startedAt: new Date().toISOString(),
})
.mockResolvedValueOnce({
exitCode: 0,
signal: null,
timedOut: false,
stdout: [
JSON.stringify({ type: "system", subtype: "init", session_id: "session-fresh", model: "claude-sonnet" }),
JSON.stringify({ type: "result", session_id: "session-fresh", subtype: "success", is_error: false, result: "Recovered" }),
].join("\n"),
stderr: "",
pid: 124,
startedAt: new Date().toISOString(),
});
const result = await execute({
runId: "run-claude-cli-fallback-context",
agent: {
id: "agent-1",
companyId: "company-1",
name: "Claude Coder",
adapterType: "claude_local",
adapterConfig: {},
},
runtime: {
sessionId: "12345678-1234-4abc-9def-123456789012",
sessionParams: { sessionId: "12345678-1234-4abc-9def-123456789012", cwd: workspaceDir },
sessionDisplayId: "12345678-1234-4abc-9def-123456789012",
taskKey: null,
},
config: {
engine: "cli",
command: "claude",
env: { ANTHROPIC_API_KEY: "fixture-anthropic-key" },
},
context: {
...createPromptContextFixture(),
paperclipWorkspace: { cwd: workspaceDir, source: "project_primary" },
},
onLog: async () => {},
});
expect(result.exitCode).toBe(0);
expect(runChildProcess).toHaveBeenCalledTimes(2);
const first = (runChildProcess.mock.calls[0] as unknown as [string, string, string[], { stdin?: string }])[3]?.stdin ?? "";
const retry = (runChildProcess.mock.calls[1] as unknown as [string, string, string[], { stdin?: string }])[3]?.stdin ?? "";
expect(first).toContain("## Compact assignment");
expect(first).not.toContain("Explain the next step before starting work.");
expect(retry).toContain("## Owned assignment");
expect(retry).toContain("Explain the next step before starting work.");
expect(retry).not.toContain("## Compact assignment");
expect(retry.indexOf("comment-first")).toBeLessThan(retry.indexOf("comment-second"));
expect(retry.split("Append the same ledger entry.")).toHaveLength(3);
});
});
@@ -44,9 +44,8 @@ import {
isPaperclipRuntimeEnvKey,
refreshPaperclipWorkspaceEnvForExecution,
renderTemplate,
renderPaperclipWakePrompt,
selectPaperclipPromptSections,
isPaperclipRecoveryWakePayload,
selectPaperclipTaskMarkdown,
rewriteWorkspaceCwdEnvVarsForExecution,
shapePaperclipWorkspaceEnvForExecution,
DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,
@@ -839,38 +838,6 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
run: { id: runId, source: "on_demand" },
context,
};
const renderedBootstrapPrompt =
!sessionId && bootstrapPromptTemplate.trim().length > 0
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
: "";
const taskContextNote = selectPaperclipTaskMarkdown(context, { resumedSession: Boolean(sessionId) });
const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, {
resumedSession: Boolean(sessionId),
conversationMode: context.conversationMode === true,
// The task-context markdown is the authoritative brief on this lane; keep
// the wake prompt's description copy out so the prompt carries it once.
suppressIssueDescription: taskContextNote.length > 0,
});
const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0;
const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
? ""
: renderTemplate(promptTemplate, templateData);
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
const prompt = joinPromptSections([
renderedBootstrapPrompt,
wakePrompt,
sessionHandoffNote,
taskContextNote,
renderedPrompt,
]);
const promptMetrics = {
promptChars: prompt.length,
bootstrapPromptChars: renderedBootstrapPrompt.length,
wakePromptChars: wakePrompt.length,
sessionHandoffChars: sessionHandoffNote.length,
taskContextChars: taskContextNote.length,
heartbeatPromptChars: renderedPrompt.length,
};
const passesConfiguredModel = Boolean(
model && (!isBedrockAuth(modelEnv) || isBedrockModelId(model)),
);
@@ -927,6 +894,33 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
};
const runAttempt = async (resumeSessionId: string | null) => {
const renderedBootstrapPrompt =
!resumeSessionId && bootstrapPromptTemplate.trim().length > 0
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
: "";
const { taskContextNote, wakePrompt } = selectPaperclipPromptSections(context, {
resumedSession: Boolean(resumeSessionId),
});
const shouldUseResumeDeltaPrompt = Boolean(resumeSessionId) && wakePrompt.length > 0;
const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
? ""
: renderTemplate(promptTemplate, templateData);
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
const prompt = joinPromptSections([
renderedBootstrapPrompt,
wakePrompt,
sessionHandoffNote,
taskContextNote,
renderedPrompt,
]);
const promptMetrics = {
promptChars: prompt.length,
bootstrapPromptChars: renderedBootstrapPrompt.length,
wakePromptChars: wakePrompt.length,
sessionHandoffChars: sessionHandoffNote.length,
taskContextChars: taskContextNote.length,
heartbeatPromptChars: renderedPrompt.length,
};
const attemptInstructionsFilePath = resumeSessionId ? undefined : effectiveInstructionsFilePath;
const args = buildClaudeArgs(resumeSessionId, attemptInstructionsFilePath);
const commandNotes: string[] = [];
@@ -788,6 +788,75 @@ describe("codex_local ACP lane", () => {
});
});
it("sends assignment-owned markdown and ordered distinct wake comments at the ACP boundary", async () => {
const root = await makeTempRoot("paperclip-codex-acp-context-owner-");
const runtimes: FakeRuntime[] = [];
const execute = createCodexAcpExecutor({
createRuntime: (options: FakeRuntimeOptions) => {
const runtime = new FakeRuntime(options);
runtimes.push(runtime);
return runtime as never;
},
});
const issue = {
id: "issue-1",
identifier: "PAP-901",
title: "Repeat phrase Repeat phrase",
description: "Repeat phrase Repeat phrase",
};
const comments = [
{ id: "comment-a", body: "Same event body." },
{ id: "comment-b", body: "Same event body." },
];
// The adapter receives server-rendered fields. Keep the server builder's
// own tests in the server package; adapter packages compile independently.
const assignmentMarkdown = [
"Paperclip task context:",
`- Issue: ${JSON.stringify(issue.identifier)}`,
`- Title: ${JSON.stringify(issue.title)}`,
"", "Issue description:", "```text", issue.description, "```",
].join("\n");
const historicalMarkdown = [
assignmentMarkdown,
...comments.map((comment) => `${comment.id}: ${comment.body}`),
].join("\n");
const result = await execute(buildContext(root, {
context: {
issueId: issue.id,
paperclipTaskMarkdown: historicalMarkdown,
paperclipTaskMarkdownAssignment: assignmentMarkdown,
paperclipWake: {
reason: "issue_commented",
issue: { ...issue, status: "in_progress" },
comments: comments.map((comment, index) => ({
...comment,
issueId: issue.id,
createdAt: `2026-09-21T00:0${index}: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" },
],
},
},
paperclipWorkspace: { cwd: root, source: "project_workspace", workspaceId: "workspace-1" },
},
}));
expect(result.exitCode).toBe(0);
const prompt = String(runtimes[0]?.startInputs[0]?.text ?? "");
expect(prompt.split("Same event body.")).toHaveLength(3);
expect(prompt.indexOf("comment comment-a")).toBeLessThan(prompt.indexOf("comment comment-b"));
expect(prompt).toContain("Repeat phrase Repeat phrase");
});
it("creates the ACP session on the in-sandbox workspace cwd for runner-backed remote runs", async () => {
const root = await makeTempRoot("paperclip-codex-acp-remote-cwd-");
const localCwd = path.join(root, "worktree");
@@ -73,6 +73,7 @@ vi.mock("@paperclipai/adapter-utils/execution-target", async () => {
};
});
import { createPromptContextFixture } from "@paperclipai/adapter-utils/test-fixtures/prompt-context";
import { execute } from "./execute.js";
describe("codex remote execution", () => {
@@ -625,4 +626,73 @@ describe("codex remote execution", () => {
expect(call?.[3].env.CODEX_HOME).toBe("/app/.paperclip-runtime/codex/home");
expect(call?.[3].remoteExecution?.remoteCwd).toBe("/app");
});
it("reselects the full assignment and bootstrap guidance after a failed resume", async () => {
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-codex-cli-fallback-context-"));
cleanupDirs.push(rootDir);
const workspaceDir = path.join(rootDir, "workspace");
await mkdir(workspaceDir, { recursive: true });
runChildProcess
.mockResolvedValueOnce({
exitCode: 1,
signal: null,
timedOut: false,
stdout: "",
stderr: "unknown thread id session-old",
pid: 123,
startedAt: new Date().toISOString(),
})
.mockResolvedValueOnce({
exitCode: 0,
signal: null,
timedOut: false,
stdout: [
JSON.stringify({ type: "thread.started", thread_id: "session-fresh" }),
JSON.stringify({ type: "turn.completed", usage: { input_tokens: 1, output_tokens: 1 } }),
].join("\\n"),
stderr: "",
pid: 124,
startedAt: new Date().toISOString(),
});
await execute({
runId: "run-codex-cli-fallback-context",
agent: {
id: "agent-1",
companyId: "company-1",
name: "Codex Coder",
adapterType: "codex_local",
adapterConfig: {},
},
runtime: {
sessionId: "session-old",
sessionParams: { sessionId: "session-old", cwd: workspaceDir },
sessionDisplayId: "session-old",
taskKey: null,
},
config: {
engine: "cli",
command: "codex",
env: { OPENAI_API_KEY: "fixture-openai-key" },
},
context: {
...createPromptContextFixture(),
paperclipWorkspace: { cwd: workspaceDir, source: "project_primary" },
},
onLog: async () => {},
});
expect(runChildProcess).toHaveBeenCalledTimes(2);
const first = (runChildProcess.mock.calls[0] as unknown as [string, string, string[], { stdin?: string }])[3]?.stdin ?? "";
const retry = (runChildProcess.mock.calls[1] as unknown as [string, string, string[], { stdin?: string }])[3]?.stdin ?? "";
expect(first).toContain("## Compact assignment");
expect(first).not.toContain("Explain the next step before starting work.");
expect(retry).toContain("## Owned assignment");
expect(retry).toContain("Explain the next step before starting work.");
expect(retry).not.toContain("## Compact assignment");
expect(retry.indexOf("comment-first")).toBeLessThan(retry.indexOf("comment-second"));
expect(retry.split("Append the same ledger entry.")).toHaveLength(3);
});
});
@@ -45,8 +45,7 @@ import {
readPaperclipRuntimeSkillEntries,
readPaperclipIssueWorkModeFromContext,
renderTemplate,
renderPaperclipWakePrompt,
selectPaperclipTaskMarkdown,
selectPaperclipPromptSections,
isPaperclipRecoveryWakePayload,
DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,
DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE,
@@ -1087,7 +1086,6 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
const instructionsFilePath = asString(config.instructionsFilePath, "").trim();
const instructionsDir = instructionsFilePath ? `${path.dirname(instructionsFilePath)}/` : "";
let instructionsPrefix = "";
let instructionsChars = 0;
if (instructionsFilePath) {
try {
const instructionsContents = await fs.readFile(instructionsFilePath, "utf8");
@@ -1095,7 +1093,6 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
`${instructionsContents}\n\n` +
`The above agent instructions were loaded from ${instructionsFilePath}. ` +
`Resolve any relative file references from ${instructionsDir}.\n\n`;
instructionsChars = instructionsPrefix.length;
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
await onLog(
@@ -1116,19 +1113,6 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
run: { id: runId, source: "on_demand" },
context,
};
const renderedBootstrapPrompt =
!sessionId && bootstrapPromptTemplate.trim().length > 0
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
: "";
const taskContextNote = selectPaperclipTaskMarkdown(context, { resumedSession: Boolean(sessionId) });
const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, {
resumedSession: Boolean(sessionId),
conversationMode: context.conversationMode === true,
suppressIssueDescription: taskContextNote.length > 0,
});
const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0;
const promptInstructionsPrefix = shouldUseResumeDeltaPrompt ? "" : instructionsPrefix;
instructionsChars = promptInstructionsPrefix.length;
const continuationSummary = parseObject(context.paperclipContinuationSummary);
const continuationSummaryBody = asString(continuationSummary.body, "").trim() || null;
const codexFallbackHandoffNote =
@@ -1139,22 +1123,45 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
continuationSummaryBody,
})
: "";
const commandNotes = (() => {
if (!instructionsFilePath) {
const notes = [repoAgentsNote];
if (forceSaferInvocation) {
notes.push("Codex transient fallback requested safer invocation settings for this retry.");
const runAttempt = async (resumeSessionId: string | null) => {
const renderedBootstrapPrompt =
!resumeSessionId && bootstrapPromptTemplate.trim().length > 0
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
: "";
const { taskContextNote, wakePrompt } = selectPaperclipPromptSections(context, {
resumedSession: Boolean(resumeSessionId),
});
const shouldUseResumeDeltaPrompt = Boolean(resumeSessionId) && wakePrompt.length > 0;
const promptInstructionsPrefix = shouldUseResumeDeltaPrompt ? "" : instructionsPrefix;
const commandNotes = (() => {
if (!instructionsFilePath) {
const notes = [repoAgentsNote];
if (forceSaferInvocation) {
notes.push("Codex transient fallback requested safer invocation settings for this retry.");
}
if (forceFreshSession) {
notes.push("Codex transient fallback forced a fresh session with a continuation handoff.");
}
return notes;
}
if (forceFreshSession) {
notes.push("Codex transient fallback forced a fresh session with a continuation handoff.");
}
return notes;
}
if (instructionsPrefix.length > 0) {
if (shouldUseResumeDeltaPrompt) {
if (instructionsPrefix.length > 0) {
if (shouldUseResumeDeltaPrompt) {
const notes = [
`Loaded agent instructions from ${instructionsFilePath}`,
"Skipped stdin instruction reinjection because an existing Codex session is being resumed with a wake delta.",
repoAgentsNote,
];
if (forceSaferInvocation) {
notes.push("Codex transient fallback requested safer invocation settings for this retry.");
}
if (forceFreshSession) {
notes.push("Codex transient fallback forced a fresh session with a continuation handoff.");
}
return notes;
}
const notes = [
`Loaded agent instructions from ${instructionsFilePath}`,
"Skipped stdin instruction reinjection because an existing Codex session is being resumed with a wake delta.",
`Prepended instructions + path directive to stdin prompt (relative references from ${instructionsDir}).`,
repoAgentsNote,
];
if (forceSaferInvocation) {
@@ -1166,8 +1173,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
return notes;
}
const notes = [
`Loaded agent instructions from ${instructionsFilePath}`,
`Prepended instructions + path directive to stdin prompt (relative references from ${instructionsDir}).`,
`Configured instructionsFilePath ${instructionsFilePath}, but file could not be read; continuing without injected instructions.`,
repoAgentsNote,
];
if (forceSaferInvocation) {
@@ -1177,51 +1183,37 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
notes.push("Codex transient fallback forced a fresh session with a continuation handoff.");
}
return notes;
})();
if (executionTargetIsSandbox) {
commandNotes.push(
"Added --skip-git-repo-check for sandbox execution because Codex requires an explicit trust bypass in headless remote workspaces.",
);
}
const notes = [
`Configured instructionsFilePath ${instructionsFilePath}, but file could not be read; continuing without injected instructions.`,
repoAgentsNote,
];
if (forceSaferInvocation) {
notes.push("Codex transient fallback requested safer invocation settings for this retry.");
if (preparedRuntimeConfig.notes.length > 0) {
commandNotes.unshift(...preparedRuntimeConfig.notes);
}
if (forceFreshSession) {
notes.push("Codex transient fallback forced a fresh session with a continuation handoff.");
}
return notes;
})();
if (executionTargetIsSandbox) {
commandNotes.push(
"Added --skip-git-repo-check for sandbox execution because Codex requires an explicit trust bypass in headless remote workspaces.",
);
}
if (preparedRuntimeConfig.notes.length > 0) {
commandNotes.unshift(...preparedRuntimeConfig.notes);
}
const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
? ""
: renderTemplate(promptTemplate, templateData);
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
const prompt = joinPromptSections([
promptInstructionsPrefix,
renderedBootstrapPrompt,
wakePrompt,
codexFallbackHandoffNote,
sessionHandoffNote,
taskContextNote,
renderedPrompt,
]);
const promptMetrics = {
promptChars: prompt.length,
instructionsChars,
bootstrapPromptChars: renderedBootstrapPrompt.length,
wakePromptChars: wakePrompt.length,
sessionHandoffChars: sessionHandoffNote.length,
taskContextChars: taskContextNote.length,
heartbeatPromptChars: renderedPrompt.length,
};
const runAttempt = async (resumeSessionId: string | null) => {
const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
? ""
: renderTemplate(promptTemplate, templateData);
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
const prompt = joinPromptSections([
promptInstructionsPrefix,
renderedBootstrapPrompt,
wakePrompt,
codexFallbackHandoffNote,
sessionHandoffNote,
taskContextNote,
renderedPrompt,
]);
const promptMetrics = {
promptChars: prompt.length,
instructionsChars: promptInstructionsPrefix.length,
bootstrapPromptChars: renderedBootstrapPrompt.length,
wakePromptChars: wakePrompt.length,
sessionHandoffChars: sessionHandoffNote.length,
taskContextChars: taskContextNote.length,
heartbeatPromptChars: renderedPrompt.length,
};
const execArgs = buildCodexExecArgs(
forceSaferInvocation ? { ...config, fastMode: false } : config,
{
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { AdapterExecutionContext } from "@paperclipai/adapter-utils";
import { createPromptContextFixture } from "@paperclipai/adapter-utils/test-fixtures/prompt-context";
import { execute } from "./execute.js";
type MockRunOptions = {
@@ -168,6 +169,19 @@ describe("cursor_cloud execute", () => {
expect(prompt).not.toContain("Create child issues");
});
it("sends assignment context on an ordinary cloud task turn", async () => {
const sdkAgent = createMockSdkAgent();
createMock.mockResolvedValue(sdkAgent);
const ctx = createContext({ context: createPromptContextFixture() });
delete ctx.config.promptTemplate;
const result = await execute(ctx);
expect(result.exitCode).toBe(0);
const prompt = String(sdkAgent.send.mock.calls[0]?.[0]);
expect(prompt).toContain("## Owned assignment");
expect(prompt.indexOf("Append the same ledger entry.")).toBeLessThan(prompt.indexOf("Change the final scope to the launch checklist."));
expect(prompt.split("Append the same ledger entry.")).toHaveLength(3);
});
it("delivers a large wake through the SDK prompt without a configured JSON env copy", async () => {
const sdkAgent = createMockSdkAgent();
createMock.mockResolvedValue(sdkAgent);
@@ -20,8 +20,7 @@ import {
joinPromptSections,
parseObject,
readPaperclipIssueWorkModeFromContext,
renderPaperclipWakePrompt,
selectPaperclipTaskMarkdown,
selectPaperclipPromptSections,
selectInitialCommunicationGuidance,
isPaperclipRecoveryWakePayload,
renderTemplate,
@@ -416,13 +415,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
context,
};
const instructions = await buildInstructionsPrefix(config, onLog);
const taskContextNote = context.conversationMode === true
? selectPaperclipTaskMarkdown(context, { resumedSession: canReuseSession, includeCommunicationGuidance: false })
: "";
const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, {
conversationMode: context.conversationMode === true,
const { taskContextNote, wakePrompt } = selectPaperclipPromptSections(context, {
resumedSession: canReuseSession,
suppressIssueDescription: taskContextNote.length > 0,
includeCommunicationGuidance: false,
});
const renderedBootstrapPrompt =
!canReuseSession && bootstrapPromptTemplate.trim().length > 0
@@ -444,6 +439,14 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
]);
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
const finalPrompt = joinPromptSections([prompt, sessionHandoffNote]);
const promptMetrics = {
promptChars: finalPrompt.length,
instructionsChars: instructions.chars,
bootstrapPromptChars: renderedBootstrapPrompt.length,
wakePromptChars: wakePrompt.length,
taskContextChars: taskContextNote.length,
heartbeatPromptChars: renderedPrompt.length,
};
const agentOptions = buildAgentOptions({
apiKey,
@@ -473,14 +476,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
command: "@cursor/sdk",
commandNotes,
prompt: finalPrompt,
promptMetrics: {
promptChars: finalPrompt.length,
instructionsChars: instructions.chars,
bootstrapPromptChars: renderedBootstrapPrompt.length,
wakePromptChars: wakePrompt.length,
taskContextChars: taskContextNote.length,
heartbeatPromptChars: renderedPrompt.length,
},
promptMetrics,
context: {
cursorCloud: {
envType,
@@ -6,6 +6,7 @@ import type { AdapterExecutionTarget } from "@paperclipai/adapter-utils/executio
import { runChildProcess } from "@paperclipai/adapter-utils/server-utils";
import { SANDBOX_INSTALL_COMMAND } from "../index.js";
import { execute } from "./execute.js";
import { createPromptContextFixture } from "@paperclipai/adapter-utils/test-fixtures/prompt-context";
type PrepareCursorSandboxCommandInput = {
runId: string;
@@ -190,7 +191,7 @@ describe("cursor execute", () => {
cwd: workspace,
promptTemplate: "Follow the paperclip heartbeat.",
},
context: {},
context: createPromptContextFixture(),
authToken: "run-jwt-token",
onLog: async () => {},
});
@@ -205,6 +206,7 @@ describe("cursor execute", () => {
expect(command).toBe(agentPath);
expect(runtimePath.split(path.delimiter)).toContain(path.join(homeDir, ".local", "bin"));
expect(prompt).toContain("Follow the paperclip heartbeat.");
expect(prompt).toContain("## Owned assignment");
} finally {
if (previousHome === undefined) delete process.env.HOME;
else process.env.HOME = previousHome;
@@ -268,6 +270,10 @@ printf '%s\\n' '{"type":"result","subtype":"success","session_id":"cursor-sessio
const runnerState = {
commands: [] as string[],
};
// The managed-runtime restore path probes the generated archive with
// `wc -c` before reading bounded `dd | base64` chunks. Keep this fixture's
// shell seam faithful to that protocol instead of returning empty stdout
// for every shell command.
const runner = {
execute: async (input: { command: string; args?: string[]; env?: Record<string, string> }) => {
runnerState.commands.push(input.command);
@@ -339,4 +345,54 @@ printf '%s\\n' '{"type":"result","subtype":"success","session_id":"cursor-sessio
await fs.rm(rootDir, { recursive: true, force: true });
}
});
it("rebuilds the full assignment after an unknown-session resume", async () => {
setPrepareCursorSandboxCommand.mockReset();
setPrepareCursorSandboxCommand.mockImplementation(async (input) => ({
command: input.command,
env: input.env,
remoteSystemHomeDir: null,
addedPathEntry: null,
preferredCommandPath: null,
}));
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-cursor-resume-"));
const workspace = path.join(root, "workspace");
const commandPath = path.join(root, "agent.sh");
const capturePath = path.join(root, "prompts.txt");
await fs.mkdir(workspace, { recursive: true });
await fs.writeFile(commandPath, `#!/bin/sh
count_file=${JSON.stringify(path.join(root, "count"))}
count=$(cat "$count_file" 2>/dev/null || printf '0')
count=$((count + 1))
printf '%s' "$count" > "$count_file"
printf '\\n--- prompt %s ---\\n' "$count" >> ${JSON.stringify(capturePath)}
cat >> ${JSON.stringify(capturePath)}
if [ "$count" -eq 1 ]; then
printf '%s\\n' '{"type":"error","message":"Unknown session"}'
exit 1
fi
printf '%s\\n' '{"type":"system","subtype":"init","session_id":"cursor-session-fresh-2","model":"auto"}'
printf '%s\\n' '{"type":"result","subtype":"success","session_id":"cursor-session-fresh-2","result":"ok"}'
`);
await fs.chmod(commandPath, 0o755);
try {
const result = await execute({
runId: "run-cursor-resume-fallback",
agent: { id: "agent-1", companyId: "company-1", name: "Cursor Coder", adapterType: "cursor", adapterConfig: {} },
runtime: { sessionId: "cursor-session-old", sessionParams: null, sessionDisplayId: null, taskKey: null },
config: { command: commandPath, cwd: workspace, promptTemplate: "Follow the paperclip heartbeat." },
context: createPromptContextFixture(),
authToken: "run-jwt-token",
onLog: async () => {},
});
expect(result.exitCode).toBe(0);
const prompts = await fs.readFile(capturePath, "utf8");
expect(prompts).toContain("## Compact assignment");
expect(prompts).toContain("## Owned assignment");
} finally {
await fs.rm(root, { recursive: true, force: true });
}
});
});
@@ -44,8 +44,7 @@ import {
resolveLegacyPaperclipDesiredSkillNames,
removeMaintainerOnlySkillSymlinks,
renderTemplate,
renderPaperclipWakePrompt,
selectPaperclipTaskMarkdown,
selectPaperclipPromptSections,
selectInitialCommunicationGuidance,
isPaperclipRecoveryWakePayload,
DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,
@@ -564,42 +563,43 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
run: { id: runId, source: "on_demand" },
context,
};
const renderedBootstrapPrompt =
!sessionId && bootstrapPromptTemplate.trim().length > 0
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
: "";
const taskContextNote = context.conversationMode === true
? selectPaperclipTaskMarkdown(context, { resumedSession: Boolean(sessionId), includeCommunicationGuidance: false })
: "";
const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, {
conversationMode: context.conversationMode === true,
resumedSession: Boolean(sessionId),
suppressIssueDescription: taskContextNote.length > 0,
});
const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0;
const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
? ""
: renderTemplate(promptTemplate, templateData);
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
const paperclipEnvNote = renderPaperclipEnvNote(env);
const basePrompt = joinPromptSections([
instructionsPrefix,
renderedBootstrapPrompt,
wakePrompt,
taskContextNote,
sessionHandoffNote,
paperclipEnvNote,
renderedPrompt,
]);
const promptMetrics = {
promptChars: basePrompt.length,
instructionsChars,
bootstrapPromptChars: renderedBootstrapPrompt.length,
wakePromptChars: wakePrompt.length,
taskContextChars: taskContextNote.length,
sessionHandoffChars: sessionHandoffNote.length,
runtimeNoteChars: paperclipEnvNote.length,
heartbeatPromptChars: renderedPrompt.length,
const buildPrompt = (resumedSession: boolean) => {
const renderedBootstrapPrompt =
!resumedSession && bootstrapPromptTemplate.trim().length > 0
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
: "";
const { taskContextNote, wakePrompt } = selectPaperclipPromptSections(context, {
resumedSession,
includeCommunicationGuidance: false,
});
const shouldUseResumeDeltaPrompt = resumedSession && wakePrompt.length > 0;
const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
? ""
: renderTemplate(promptTemplate, templateData);
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
const paperclipEnvNote = renderPaperclipEnvNote(env);
const basePrompt = joinPromptSections([
instructionsPrefix,
renderedBootstrapPrompt,
wakePrompt,
taskContextNote,
sessionHandoffNote,
paperclipEnvNote,
renderedPrompt,
]);
return {
basePrompt,
promptMetrics: {
promptChars: basePrompt.length,
instructionsChars,
bootstrapPromptChars: renderedBootstrapPrompt.length,
wakePromptChars: wakePrompt.length,
taskContextChars: taskContextNote.length,
sessionHandoffChars: sessionHandoffNote.length,
runtimeNoteChars: paperclipEnvNote.length,
heartbeatPromptChars: renderedPrompt.length,
},
};
};
const buildArgs = (resumeSessionId: string | null) => {
@@ -613,6 +613,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
};
const runAttempt = async (resumeSessionId: string | null) => {
const { basePrompt, promptMetrics } = buildPrompt(Boolean(resumeSessionId));
const prompt = joinPromptSections([
selectInitialCommunicationGuidance(context, { resumedSession: Boolean(resumeSessionId) }),
basePrompt,
@@ -71,6 +71,7 @@ vi.mock("@paperclipai/adapter-utils/server-utils", async () => {
});
import { execute } from "./execute.js";
import { createPromptContextFixture } from "@paperclipai/adapter-utils/test-fixtures/prompt-context";
function buildContext(config: Record<string, unknown> = {}) {
return {
@@ -150,4 +151,33 @@ describe("gemini_local ACP startup fallback", () => {
}
},
);
it("rebuilds the full assignment when a resume falls back to a fresh CLI attempt", async () => {
const cwd = await mkdtemp(path.join(tmpdir(), "gemini-context-fallback-"));
const prompts: string[] = [];
try {
runAdapterExecutionTargetProcess
.mockResolvedValueOnce({
exitCode: 1, signal: null, timedOut: false, stdout: "",
stderr: "Unknown session 'previous'", pid: 123, startedAt: new Date().toISOString(),
})
.mockResolvedValueOnce({
exitCode: 0, signal: null, timedOut: false,
stdout: JSON.stringify({ type: "message", role: "assistant", content: "done" }),
stderr: "", pid: 123, startedAt: new Date().toISOString(),
});
const ctx = buildContext({ engine: "cli", cwd });
await execute({
...ctx,
runtime: { ...ctx.runtime, sessionId: "previous" },
context: createPromptContextFixture(),
onMeta: async (meta) => { prompts.push(meta.prompt ?? ""); },
});
expect(prompts).toHaveLength(2);
expect(prompts[0]).toContain("## Compact assignment");
expect(prompts[1]).toContain("## Owned assignment");
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
});
@@ -47,8 +47,7 @@ import {
removeMaintainerOnlySkillSymlinks,
parseObject,
renderTemplate,
renderPaperclipWakePrompt,
selectPaperclipTaskMarkdown,
selectPaperclipPromptSections,
selectInitialCommunicationGuidance,
isPaperclipRecoveryWakePayload,
DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,
@@ -555,44 +554,45 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
run: { id: runId, source: "on_demand" },
context,
};
const renderedBootstrapPrompt =
!sessionId && bootstrapPromptTemplate.trim().length > 0
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
: "";
const taskContextNote = context.conversationMode === true
? selectPaperclipTaskMarkdown(context, { resumedSession: Boolean(sessionId), includeCommunicationGuidance: false })
: "";
const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, {
conversationMode: context.conversationMode === true,
resumedSession: Boolean(sessionId),
suppressIssueDescription: taskContextNote.length > 0,
});
const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0;
const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
? ""
: renderTemplate(promptTemplate, templateData);
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
const paperclipEnvNote = renderPaperclipEnvNote(env);
const apiAccessNote = renderApiAccessNote(env);
const basePrompt = joinPromptSections([
instructionsPrefix,
renderedBootstrapPrompt,
wakePrompt,
taskContextNote,
sessionHandoffNote,
paperclipEnvNote,
apiAccessNote,
renderedPrompt,
]);
const promptMetrics = {
promptChars: basePrompt.length,
instructionsChars: instructionsPrefix.length,
bootstrapPromptChars: renderedBootstrapPrompt.length,
wakePromptChars: wakePrompt.length,
taskContextChars: taskContextNote.length,
sessionHandoffChars: sessionHandoffNote.length,
runtimeNoteChars: paperclipEnvNote.length + apiAccessNote.length,
heartbeatPromptChars: renderedPrompt.length,
const buildPrompt = (resumedSession: boolean) => {
const renderedBootstrapPrompt =
!resumedSession && bootstrapPromptTemplate.trim().length > 0
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
: "";
const { taskContextNote, wakePrompt } = selectPaperclipPromptSections(context, {
resumedSession,
includeCommunicationGuidance: false,
});
const shouldUseResumeDeltaPrompt = resumedSession && wakePrompt.length > 0;
const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
? ""
: renderTemplate(promptTemplate, templateData);
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
const paperclipEnvNote = renderPaperclipEnvNote(env);
const apiAccessNote = renderApiAccessNote(env);
const basePrompt = joinPromptSections([
instructionsPrefix,
renderedBootstrapPrompt,
wakePrompt,
taskContextNote,
sessionHandoffNote,
paperclipEnvNote,
apiAccessNote,
renderedPrompt,
]);
return {
basePrompt,
promptMetrics: {
promptChars: basePrompt.length,
instructionsChars: instructionsPrefix.length,
bootstrapPromptChars: renderedBootstrapPrompt.length,
wakePromptChars: wakePrompt.length,
taskContextChars: taskContextNote.length,
sessionHandoffChars: sessionHandoffNote.length,
runtimeNoteChars: paperclipEnvNote.length + apiAccessNote.length,
heartbeatPromptChars: renderedPrompt.length,
},
};
};
const buildArgs = (resumeSessionId: string | null, prompt: string) => {
@@ -611,6 +611,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
};
const runAttempt = async (resumeSessionId: string | null) => {
const { basePrompt, promptMetrics } = buildPrompt(Boolean(resumeSessionId));
const prompt = joinPromptSections([
selectInitialCommunicationGuidance(context, { resumedSession: Boolean(resumeSessionId) }),
basePrompt,
@@ -4,6 +4,7 @@ import path from "node:path";
import { execFileSync } from "node:child_process";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AdapterExecutionContext } from "@paperclipai/adapter-utils";
import { createPromptContextFixture } from "@paperclipai/adapter-utils/test-fixtures/prompt-context";
// Bundles the remote-lane mock state and every mocked execution-target
// function behind one hoisted object, so the `vi.mock` factory below (which
@@ -1033,5 +1034,62 @@ describe("grok_local execute", () => {
grokAuth({ key: "host-key", expiresAt: OLDER_EXPIRY }),
);
});
it("delivers the owned assignment and ordered wake comments through --single", async () => {
const root = await makeTempRoot();
const fixture = createPromptContextFixture();
let deliveredPrompt = "";
runProcessMock.mockImplementation(async (_runId, _target, _command, args) => {
deliveredPrompt = String(args.at(-1) ?? "");
return makeSuccessfulRunResult();
});
const ctx = await makeCtx("run-context-ownership", root);
ctx.context = fixture;
await execute(ctx);
expect(deliveredPrompt).toContain(fixture.paperclipTaskMarkdownAssignment);
expect(deliveredPrompt.indexOf("Append the same ledger entry.")).toBeLessThan(
deliveredPrompt.lastIndexOf("Append the same ledger entry."),
);
expect(deliveredPrompt.indexOf("comment-first")).toBeLessThan(
deliveredPrompt.indexOf("comment-second"),
);
expect(deliveredPrompt.indexOf("comment-second")).toBeLessThan(
deliveredPrompt.indexOf("comment-scope"),
);
expect(deliveredPrompt).toContain("Change the final scope to the launch checklist.");
});
it("retries a stale session with the full assignment and wake context", async () => {
const root = await makeTempRoot();
const fixture = createPromptContextFixture();
const prompts: string[] = [];
runProcessMock.mockImplementation(async (_runId, _target, _command, args) => {
prompts.push(String(args.at(-1) ?? ""));
if (prompts.length === 1) {
return { exitCode: 1, signal: null, timedOut: false, stdout: "", stderr: "unknown session sess-stale" };
}
return makeSuccessfulRunResult();
});
const ctx = await makeCtx("run-grok-recovery-context", root);
ctx.runtime = {
sessionId: "sess-stale",
sessionParams: { sessionId: "sess-stale", cwd: root },
sessionDisplayId: "sess-stale",
taskKey: null,
};
ctx.context = fixture;
const result = await execute(ctx);
expect(result.exitCode).toBe(0);
expect(prompts).toHaveLength(2);
expect(prompts[0]).toContain(fixture.paperclipTaskMarkdownAssignmentCompact);
expect(prompts[1]).toContain(fixture.paperclipTaskMarkdownAssignment);
expect(prompts[1]).toContain("comment-first");
expect(prompts[1]).toContain("comment-scope");
});
});
});
@@ -36,8 +36,7 @@ import {
readPaperclipIssueWorkModeFromContext,
readPaperclipRuntimeSkillEntries,
renderTemplate,
renderPaperclipWakePrompt,
selectPaperclipTaskMarkdown,
selectPaperclipPromptSections,
selectInitialCommunicationGuidance,
isPaperclipRecoveryWakePayload,
resolveLegacyPaperclipDesiredSkillNames,
@@ -542,37 +541,9 @@ async function executeTurn(ctx: AdapterExecutionContext): Promise<AdapterExecuti
run: { id: runId, source: "on_demand" },
context,
};
const taskContextNote = context.conversationMode === true
? selectPaperclipTaskMarkdown(context, { resumedSession: Boolean(sessionId), includeCommunicationGuidance: false })
: "";
const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, {
conversationMode: context.conversationMode === true,
resumedSession: Boolean(sessionId),
suppressIssueDescription: taskContextNote.length > 0,
});
const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0;
const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
? ""
: renderTemplate(promptTemplate, templateData);
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
const paperclipEnvNote = renderPaperclipEnvNote(env);
const apiAccessNote = renderApiAccessNote(env);
const basePrompt = joinPromptSections([
wakePrompt,
taskContextNote,
sessionHandoffNote,
paperclipEnvNote,
apiAccessNote,
renderedPrompt,
]);
const promptMetrics = {
promptChars: basePrompt.length,
wakePromptChars: wakePrompt.length,
taskContextChars: taskContextNote.length,
sessionHandoffChars: sessionHandoffNote.length,
runtimeNoteChars: paperclipEnvNote.length + apiAccessNote.length,
heartbeatPromptChars: renderedPrompt.length,
};
const buildArgs = (resumeSessionId: string | null, prompt: string) => {
const args = ["--cwd", effectiveExecutionCwd, "--output-format", "streaming-json"];
@@ -596,10 +567,35 @@ async function executeTurn(ctx: AdapterExecutionContext): Promise<AdapterExecuti
const runAttempt = async (resumeSessionId: string | null) => {
ctx.signal?.throwIfAborted();
const attemptSections = selectPaperclipPromptSections(context, {
resumedSession: Boolean(resumeSessionId),
includeCommunicationGuidance: false,
});
const attemptWakePrompt = attemptSections.wakePrompt;
const attemptRenderedPrompt = Boolean(resumeSessionId) && attemptWakePrompt.length > 0
|| isPaperclipRecoveryWakePayload(context.paperclipWake)
? ""
: renderTemplate(promptTemplate, templateData);
const attemptBasePrompt = joinPromptSections([
attemptWakePrompt,
attemptSections.taskContextNote,
sessionHandoffNote,
paperclipEnvNote,
apiAccessNote,
attemptRenderedPrompt,
]);
const prompt = joinPromptSections([
selectInitialCommunicationGuidance(context, { resumedSession: Boolean(resumeSessionId) }),
basePrompt,
attemptBasePrompt,
]);
const promptMetrics = {
promptChars: prompt.length,
wakePromptChars: attemptWakePrompt.length,
taskContextChars: attemptSections.taskContextNote.length,
sessionHandoffChars: sessionHandoffNote.length,
runtimeNoteChars: paperclipEnvNote.length + apiAccessNote.length,
heartbeatPromptChars: attemptRenderedPrompt.length,
};
const args = buildArgs(resumeSessionId, prompt);
if (onMeta) {
await onMeta({
@@ -1,5 +1,6 @@
import { describe, expect, it, vi, afterEach } from "vitest";
import type { AdapterExecutionContext } from "@paperclipai/adapter-utils";
import { createPromptContextFixture } from "@paperclipai/adapter-utils/test-fixtures/prompt-context";
import { execute, mapFinalResultForTest, parseSseFramesForTest, resolveSessionKey } from "./execute.js";
import { testEnvironment } from "./test.js";
@@ -276,6 +277,57 @@ describe("execute", () => {
expect(runBodies[1]!.input).not.toContain(description);
});
it.each([false, true])("delivers the shared assignment and ordered comments at the HTTP boundary (resumed=%s)", async (resumed) => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.endsWith("/v1/runs")) {
return new Response(JSON.stringify({ run_id: "run-hermes-1", status: "completed", output: "done" }), { status: 200 });
}
return new Response(JSON.stringify({ status: "completed", output: "done" }), { status: 200 });
});
vi.stubGlobal("fetch", fetchMock);
const ctx = makeCtx({
apiBaseUrl: "http://127.0.0.1:8642",
apiKey: "secret-key",
timeoutSec: 5,
payloadTemplate: { input: "Custom gateway instruction." },
});
const promptContext = createPromptContextFixture();
ctx.context = { ...promptContext, conversationMode: true };
if (resumed) ctx.runtime.sessionId = "prior-session";
const result = await execute(ctx);
expect(result.exitCode).toBe(0);
const calls = fetchMock.mock.calls as Array<[RequestInfo | URL, RequestInit?]>;
const runCall = calls.find(([input]) => String(input).endsWith("/v1/runs"));
const input = JSON.parse(String(runCall?.[1]?.body)).input as string;
expect(input).toContain("Custom gateway instruction.");
expect(input.indexOf("Append the same ledger entry.")).toBeGreaterThanOrEqual(0);
expect(input.indexOf("Append the same ledger entry.")).toBeLessThan(input.indexOf("Change the final scope to the launch checklist."));
expect(input.split("Append the same ledger entry.")).toHaveLength(3);
expect(input).not.toContain("Structured wake payload JSON:");
expect(input.split("Keep this deliberate repetition. Keep this deliberate repetition.")).toHaveLength(2);
const continuationHeading = "## Current request and continuation context";
const continuationStart = input.indexOf(continuationHeading);
const fencedStart = input.indexOf("```text\n", continuationStart);
const fencedEnd = input.indexOf("\n```", fencedStart + "```text\n".length);
expect(continuationStart).toBeGreaterThanOrEqual(0);
expect(fencedStart).toBeGreaterThan(continuationStart);
expect(fencedEnd).toBeGreaterThan(fencedStart);
const continuation = JSON.parse(input.slice(
fencedStart + "```text\n".length,
fencedEnd,
)) as Record<string, unknown>;
expect(continuation.objectiveSource).toEqual(promptContext.executionContinuation.objectiveSource);
if (resumed) {
expect(input).toContain("## Compact assignment");
expect(continuation.objective).toBe("Keep this deliberate repetition. Keep this deliberate repetition.");
} else {
expect(continuation).not.toHaveProperty("objective");
}
});
it("routes a bare Hermes dashboard URL on port 9119 through the API prefix", async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
@@ -321,6 +373,45 @@ describe("execute", () => {
);
});
it("renders current wake comments once when the gateway task brief owns them", async () => {
const commentBody = "Keep this current comment exactly once.";
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.endsWith("/v1/runs")) {
return new Response(JSON.stringify({ run_id: "run-hermes-1", status: "started" }), { status: 200 });
}
return new Response(JSON.stringify({ status: "completed", output: "done" }), { status: 200 });
});
vi.stubGlobal("fetch", fetchMock);
const ctx = makeCtx({ apiBaseUrl: "http://127.0.0.1:8642", apiKey: "secret-key" });
ctx.context = {
issueId: "issue-1",
paperclipTaskMarkdown: [
"Paperclip task context:",
'- Issue: "PAP-1"',
].join("\n"),
paperclipTurnContext: {
version: 1,
assignment: { owner: "task_markdown" },
events: { owner: "wake_prompt", comments: [{ id: "comment-1", revision: "rev-1" }] },
},
paperclipWake: {
reason: "issue_commented",
issue: { id: "issue-1", identifier: "PAP-1", title: "Do the thing", status: "in_progress" },
commentWindow: { requestedCount: 1, includedCount: 1, missingCount: 0 },
comments: [{ id: "comment-1", body: commentBody }],
fallbackFetchNeeded: false,
},
};
await execute(ctx);
const calls = fetchMock.mock.calls as Array<[RequestInfo | URL, RequestInit?]>;
const runCall = calls.find(([input]) => String(input).endsWith("/v1/runs"));
const prompt = JSON.parse(String(runCall?.[1]?.body)).input as string;
expect(prompt.split(commentBody)).toHaveLength(2);
});
it("routes the default Hermes dashboard chat URL on port 9119 through the API prefix", async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
@@ -8,10 +8,10 @@ import {
asString,
parseObject,
readPaperclipIssueWorkModeFromContext,
renderPaperclipWakePrompt,
selectPaperclipPromptSections,
isPaperclipRecoveryWakePayload,
selectPaperclipTaskMarkdown,
stringifyPaperclipWakePayload,
paperclipWakeCommentsArePromptOwned,
} from "@paperclipai/adapter-utils/server-utils";
import {
ADAPTER_TYPE,
@@ -272,16 +272,17 @@ function buildInput(ctx: AdapterExecutionContext, paperclipApiUrl: string | null
const resumedSession =
(sessionKeyStrategy === "issue" || sessionKeyStrategy === "agent") &&
Boolean(nonEmpty(ctx.runtime?.sessionId));
const taskMarkdown = nonEmpty(selectPaperclipTaskMarkdown(ctx.context, { resumedSession }));
const wakePrompt = renderPaperclipWakePrompt(ctx.context.paperclipWake, {
conversationMode: ctx.context.conversationMode === true,
// The task-context markdown is the authoritative brief on this lane; keep
// the wake prompt's description copy out so the prompt carries it once.
suppressIssueDescription: Boolean(taskMarkdown),
});
const wakePayloadJson = stringifyPaperclipWakePayload(ctx.context.paperclipWake, {
omitIssueDescription: Boolean(taskMarkdown),
const { taskContextNote: taskMarkdown, wakePrompt } = selectPaperclipPromptSections(ctx.context, {
resumedSession,
// Hermes gateway owns the execution contract below; retain the old
// gateway prompt shape and avoid adding a second contract on resume.
includeExecutionContract: false,
});
const wakePayloadJson = paperclipWakeCommentsArePromptOwned(ctx.context)
? null
: stringifyPaperclipWakePayload(ctx.context.paperclipWake, {
omitIssueDescription: Boolean(taskMarkdown),
});
const sessionHandoff = nonEmpty(ctx.context.paperclipSessionHandoffMarkdown);
const issueWorkMode = readPaperclipIssueWorkModeFromContext(ctx.context);
const lines = [
+8 -11
View File
@@ -36,8 +36,7 @@ import {
DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,
DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE,
joinPromptSections,
renderPaperclipWakePrompt,
selectPaperclipTaskMarkdown,
selectPaperclipPromptSections,
stringifyPaperclipWakePayload,
isPaperclipRecoveryWakePayload,
} from "@paperclipai/adapter-utils/server-utils";
@@ -164,16 +163,13 @@ export function buildPrompt(
paperclipApiUrl = paperclipApiUrl.replace(/\/+$/, "") + "/api";
}
const paperclipTaskMarkdown = selectPaperclipTaskMarkdown(context, {
const { taskContextNote: taskContextMarkdown, wakePrompt } = selectPaperclipPromptSections(context, {
resumedSession: options.resumedSession === true,
includeCommunicationGuidance: true,
});
const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, {
conversationMode: context.conversationMode === true,
resumedSession: options.resumedSession === true,
// The task-context markdown is the authoritative brief on this lane; keep
// the wake prompt's description copy out so the prompt carries it once.
suppressIssueDescription: paperclipTaskMarkdown.length > 0,
});
// Keep the historical variable available to custom templates. Automatic
// assembly uses the ownership-aware assignment variant below.
const paperclipTaskMarkdown = cfgString(context.paperclipTaskMarkdown)?.trim() || "";
const sessionHandoffMarkdown = cfgString(context.paperclipSessionHandoffMarkdown)?.trim() || "";
const wakePayloadJson = stringifyPaperclipWakePayload(context.paperclipWake) || "";
@@ -197,6 +193,7 @@ export function buildPrompt(
paperclipWakePrompt: wakePrompt,
paperclipTaskMarkdown,
taskContext: paperclipTaskMarkdown,
taskContextMarkdown,
paperclipWakeJson: wakePayloadJson,
wakePayloadJson,
paperclipApiKeyEnv: "PAPERCLIP_API_KEY",
@@ -209,7 +206,7 @@ export function buildPrompt(
return joinPromptSections([
wakePrompt,
sessionHandoffMarkdown,
paperclipTaskMarkdown,
taskContextMarkdown,
rendered,
]);
}
@@ -87,6 +87,38 @@ test("renders standard assignment wake with task authority and no backlog discov
expect(prompt).not.toContain("status=backlog");
});
test("keeps current wake comments in the wake owner and preserves assignment markdown inputs", () => {
const commentBody = "Please preserve the exact current comment once.";
const prompt = buildPrompt(baseContext({
paperclipWake: {
reason: "issue_commented",
issue: {
id: "issue-1",
identifier: "PAP-11751",
title: "Keep the current comment once",
status: "in_progress",
priority: "medium",
workMode: "standard",
},
commentWindow: { requestedCount: 1, includedCount: 1, missingCount: 0 },
comments: [{ id: "comment-1", body: commentBody }],
fallbackFetchNeeded: false,
},
paperclipTaskMarkdown: [
"Paperclip task context:",
'- Issue: "PAP-11751"',
].join("\n"),
paperclipTurnContext: {
version: 1,
assignment: { owner: "task_markdown" },
events: { owner: "wake_prompt", comments: [{ id: "comment-1", revision: "rev-1" }] },
},
}), {});
expect(prompt.split(commentBody)).toHaveLength(2);
expect(prompt).toContain('Paperclip task context:\n- Issue: "PAP-11751"');
});
test("renders scoped planning wake authority before the Hermes default workflow", () => {
const prompt = buildPrompt(baseContext(), {
paperclipApiUrl: "http://127.0.0.1:3101/api",
@@ -247,6 +279,36 @@ test("preserves custom prompt templates while exposing runtime and wake variable
expect(prompt).not.toContain("Paperclip runtime identity:");
});
test("keeps historical task markdown available to custom templates while automatic context uses assignment markdown", () => {
const historical = "Historical task with current comment.";
const assignment = "Assignment task without current comment.";
const prompt = buildPrompt(baseContext({
paperclipTaskMarkdown: historical,
paperclipTaskMarkdownAssignment: assignment,
paperclipWake: {
reason: "issue_commented",
issue: { id: "issue-1", identifier: "PAP-1", title: "Task", status: "in_progress" },
comments: [{ id: "comment-1", body: "Current comment." }],
commentWindow: { requestedCount: 1, includedCount: 1, missingCount: 0 },
fallbackFetchNeeded: false,
},
}), { promptTemplate: "custom={{paperclipTaskMarkdown}}" });
expect(prompt).toContain(`custom=${historical}`);
expect(prompt).toContain(assignment);
expect(prompt).toContain("Current comment.");
});
test("keeps legacy task markdown when ownership fields are absent", () => {
const legacyTask = "Legacy task context from an older Paperclip caller.";
const prompt = buildPrompt(baseContext({
paperclipTaskMarkdown: legacyTask,
paperclipTaskMarkdownAssignment: undefined,
paperclipTaskMarkdownCompact: undefined,
}), {});
expect(prompt).toContain(legacyTask);
});
test.each([false, true])("conversation prompts preserve the handoff policy (resumed=%s)", (resumedSession) => {
const directive = "Chat directive: clarify goals and hand the plan off to project tasks.";
@@ -3,6 +3,7 @@ import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AdapterExecutionContext } from "@paperclipai/adapter-utils";
import { createPromptContextFixture } from "@paperclipai/adapter-utils/test-fixtures/prompt-context";
const ensureRuntimeInstalledMock = vi.hoisted(() => vi.fn(async () => {}));
const ensureCommandMock = vi.hoisted(() => vi.fn(async () => {}));
@@ -129,6 +130,38 @@ describe("kimi_local execute", () => {
});
});
it("delivers the owned assignment and ordered wake comments through the CLI prompt", async () => {
const root = await makeTempRoot();
const fixture = createPromptContextFixture();
let deliveredPrompt = "";
runProcessMock.mockImplementation(async (_runId, _target, _command, args) => {
deliveredPrompt = String(args.at(-1) ?? "");
return {
exitCode: 0,
signal: null,
timedOut: false,
stdout: KIMI_STDOUT,
stderr: "",
};
});
await execute(makeContext(root, {
context: fixture,
}));
expect(deliveredPrompt).toContain(fixture.paperclipTaskMarkdownAssignment);
expect(deliveredPrompt.indexOf("Append the same ledger entry.")).toBeLessThan(
deliveredPrompt.lastIndexOf("Append the same ledger entry."),
);
expect(deliveredPrompt.indexOf("comment-first")).toBeLessThan(
deliveredPrompt.indexOf("comment-second"),
);
expect(deliveredPrompt.indexOf("comment-second")).toBeLessThan(
deliveredPrompt.indexOf("comment-scope"),
);
expect(deliveredPrompt).toContain("Change the final scope to the launch checklist.");
});
it("forwards streamed stdout lines to onEvent as assistant + tool_call runtime events", async () => {
const root = await makeTempRoot();
const events: Array<{ eventType: string; message?: string; payload?: Record<string, unknown> }> = [];
@@ -233,6 +266,7 @@ describe("kimi_local execute", () => {
it("retries fresh when the resume session is unrecoverable", async () => {
const root = await makeTempRoot();
const fixture = createPromptContextFixture();
const seenArgLists: string[][] = [];
runProcessMock.mockImplementation(async (_runId, _target, _command, args) => {
seenArgLists.push(args);
@@ -249,11 +283,16 @@ describe("kimi_local execute", () => {
sessionDisplayId: "session_stale",
taskKey: null,
},
config: { cwd: root, bootstrapPromptTemplate: "BOOTSTRAP {{run.id}}" },
context: fixture,
}));
expect(runProcessMock).toHaveBeenCalledTimes(2);
expect(seenArgLists[0]).toContain("-r");
expect(seenArgLists[1]).not.toContain("-r");
expect(seenArgLists[1].at(-1)).toContain(fixture.paperclipTaskMarkdownAssignment);
expect(seenArgLists[1].at(-1)).toContain("BOOTSTRAP run-1");
expect(seenArgLists[1].at(-1)).toContain("comment-first");
expect(result).toMatchObject({ exitCode: 0, sessionId: "session_abc-123" });
});
@@ -39,8 +39,7 @@ import {
resolveLegacyPaperclipDesiredSkillNames,
parseObject,
renderTemplate,
renderPaperclipWakePrompt,
selectPaperclipTaskMarkdown,
selectPaperclipPromptSections,
selectInitialCommunicationGuidance,
isPaperclipRecoveryWakePayload,
DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,
@@ -512,45 +511,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
run: { id: runId, source: "on_demand" },
context,
};
const renderedBootstrapPrompt =
!sessionId && bootstrapPromptTemplate.trim().length > 0
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
: "";
const taskContextNote = context.conversationMode === true
? selectPaperclipTaskMarkdown(context, { resumedSession: Boolean(sessionId), includeCommunicationGuidance: false })
: "";
const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, {
conversationMode: context.conversationMode === true,
resumedSession: Boolean(sessionId),
suppressIssueDescription: taskContextNote.length > 0,
});
const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0;
const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
? ""
: renderTemplate(promptTemplate, templateData);
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
const paperclipEnvNote = renderPaperclipEnvNote(env);
const apiAccessNote = renderApiAccessNote(env);
const basePrompt = joinPromptSections([
instructionsPrefix,
renderedBootstrapPrompt,
wakePrompt,
taskContextNote,
sessionHandoffNote,
paperclipEnvNote,
apiAccessNote,
renderedPrompt,
]);
const promptMetrics = {
promptChars: basePrompt.length,
instructionsChars: instructionsPrefix.length,
bootstrapPromptChars: renderedBootstrapPrompt.length,
wakePromptChars: wakePrompt.length,
taskContextChars: taskContextNote.length,
sessionHandoffChars: sessionHandoffNote.length,
runtimeNoteChars: paperclipEnvNote.length + apiAccessNote.length,
heartbeatPromptChars: renderedPrompt.length,
};
const buildArgs = (resumeSessionId: string | null, prompt: string) => {
const args = ["--output-format", "stream-json"];
@@ -577,10 +540,42 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
};
const runAttempt = async (resumeSessionId: string | null) => {
const attemptSections = selectPaperclipPromptSections(context, {
resumedSession: Boolean(resumeSessionId),
includeCommunicationGuidance: false,
});
const attemptBootstrapPrompt = !resumeSessionId && bootstrapPromptTemplate.trim().length > 0
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
: "";
const attemptWakePrompt = attemptSections.wakePrompt;
const attemptRenderedPrompt = Boolean(resumeSessionId) && attemptWakePrompt.length > 0
|| isPaperclipRecoveryWakePayload(context.paperclipWake)
? ""
: renderTemplate(promptTemplate, templateData);
const attemptBasePrompt = joinPromptSections([
instructionsPrefix,
attemptBootstrapPrompt,
attemptWakePrompt,
attemptSections.taskContextNote,
sessionHandoffNote,
paperclipEnvNote,
apiAccessNote,
attemptRenderedPrompt,
]);
const prompt = joinPromptSections([
selectInitialCommunicationGuidance(context, { resumedSession: Boolean(resumeSessionId) }),
basePrompt,
attemptBasePrompt,
]);
const promptMetrics = {
promptChars: prompt.length,
instructionsChars: instructionsPrefix.length,
bootstrapPromptChars: attemptBootstrapPrompt.length,
wakePromptChars: attemptWakePrompt.length,
taskContextChars: attemptSections.taskContextNote.length,
sessionHandoffChars: sessionHandoffNote.length,
runtimeNoteChars: paperclipEnvNote.length + apiAccessNote.length,
heartbeatPromptChars: attemptRenderedPrompt.length,
};
const args = buildArgs(resumeSessionId, prompt);
const invocationEnv = buildKimiHeadlessEnv(env);
const invocationRuntimeEnv = buildKimiRuntimeEnv(env);
@@ -1,4 +1,5 @@
import type { AdapterExecutionContext } from "@paperclipai/adapter-utils";
import { createPromptContextFixture } from "@paperclipai/adapter-utils/test-fixtures/prompt-context";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const websocketState = vi.hoisted(() => ({
@@ -142,6 +143,19 @@ describe("openclaw_gateway execute dispatch boundary", () => {
expect(prompt).not.toContain("GET /api/issues/{issueId}/comments");
});
it("sends assignment context on an ordinary gateway task turn", async () => {
const ctx = createContext();
ctx.context = createPromptContextFixture();
const result = await execute(ctx);
expect(result.exitCode).toBe(0);
expect(websocketState.messages).toHaveLength(1);
const prompt = websocketState.messages[0]!;
expect(prompt).toContain("## Owned assignment");
expect(prompt.indexOf("Append the same ledger entry.")).toBeLessThan(prompt.indexOf("Change the final scope to the launch checklist."));
expect(prompt.split("Append the same ledger entry.")).toHaveLength(3);
expect(prompt).not.toContain("Structured wake payload JSON:");
});
it("reports dispatch after transport setup and before the remote agent request", async () => {
const onDispatch = vi.fn(() => {
websocketState.events.push("dispatch");
@@ -10,11 +10,11 @@ import {
buildRuntimeToolsEnv,
parseObject,
readPaperclipIssueWorkModeFromContext,
renderPaperclipWakePrompt,
selectPaperclipTaskMarkdown,
selectPaperclipPromptSections,
selectInitialCommunicationGuidance,
joinPromptSections,
stringifyPaperclipWakePayload,
paperclipWakeCommentsArePromptOwned,
} from "@paperclipai/adapter-utils/server-utils";
import crypto, { randomUUID } from "node:crypto";
import { WebSocket } from "ws";
@@ -1106,11 +1106,16 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
const paperclipEnv = buildPaperclipEnvForWake(ctx, wakePayload);
// No heartbeat prompt template is sent over the gateway, so the wake prompt
// must carry the execution contract itself.
const structuredWakePrompt = renderPaperclipWakePrompt(ctx.context.paperclipWake, {
const { taskContextNote, wakePrompt: structuredWakePrompt } = selectPaperclipPromptSections(ctx.context, {
resumedSession: Boolean(ctx.runtime?.sessionId),
includeExecutionContract: true,
conversationMode: ctx.context.conversationMode === true,
includeCommunicationGuidance: false,
});
const structuredWakeJson = stringifyPaperclipWakePayload(ctx.context.paperclipWake);
const structuredWakeJson = paperclipWakeCommentsArePromptOwned(ctx.context)
? null
: stringifyPaperclipWakePayload(ctx.context.paperclipWake, {
omitIssueDescription: Boolean(taskContextNote),
});
const wakeText = buildWakeText(
wakePayload,
paperclipEnv,
@@ -1118,9 +1123,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
? joinWakePayloadSections(structuredWakePrompt, structuredWakeJson)
: structuredWakePrompt,
resolveClaimedApiKeyPath(ctx.config.claimedApiKeyPath),
ctx.context.conversationMode === true
? selectPaperclipTaskMarkdown(ctx.context, { resumedSession: Boolean(ctx.runtime?.sessionId), includeCommunicationGuidance: false })
: undefined,
taskContextNote || undefined,
);
const sessionKeyStrategy = normalizeSessionKeyStrategy(ctx.config.sessionKeyStrategy);
@@ -10,6 +10,7 @@ vi.mock("@paperclipai/adapter-utils/execution-target", async (importOriginal) =>
import { ensureRemoteOpenCodeModelConfiguredAndAvailable, execute } from "./execute.js";
import { runAdapterExecutionTargetProcess } from "@paperclipai/adapter-utils/execution-target";
import { createPromptContextFixture } from "@paperclipai/adapter-utils/test-fixtures/prompt-context";
const runProcessMock = vi.mocked(runAdapterExecutionTargetProcess);
@@ -81,6 +82,28 @@ describe("OpenCode local skill injection", () => {
expect(prompt).not.toContain("Create child issues");
});
it("delivers assignment context on an ordinary task turn and rebuilds it after resume fallback", async () => {
const commandPath = path.join(configHome, "fake-opencode-context");
await fs.writeFile(commandPath, "#!/bin/sh\nexit 0\n", { mode: 0o755 });
const prompts: string[] = [];
runProcessMock
.mockReset()
.mockResolvedValueOnce(probeResult({ stdout: JSON.stringify({ type: "error", error: "unknown session" }) }))
.mockResolvedValueOnce(probeResult({ stdout: JSON.stringify({ type: "text", sessionID: "fresh", part: { text: "done" } }) }));
await execute({
runId: "run-context-fallback",
agent: { id: "agent-1", companyId: "company-1", name: "OpenCode", adapterType: "opencode_local", adapterConfig: {} },
runtime: { sessionId: "previous", sessionParams: null, sessionDisplayId: null, taskKey: null },
config: { command: commandPath, cwd: configHome, model: "openai/gpt-5", env: { OPENCODE_ALLOW_ALL_MODELS: "1" } },
context: createPromptContextFixture(),
onLog: async () => {},
onMeta: async (meta) => { prompts.push(String(meta.prompt ?? "")); },
});
expect(prompts).toHaveLength(2);
expect(prompts[0]).toContain("## Compact assignment");
expect(prompts[1]).toContain("## Owned assignment");
});
it("injects runtime skills into the configured child HOME", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-opencode-configured-home-"));
const processHome = path.join(root, "process-home");
@@ -40,8 +40,7 @@ import {
ensurePathInEnv,
refreshPaperclipWorkspaceEnvForExecution,
renderTemplate,
renderPaperclipWakePrompt,
selectPaperclipTaskMarkdown,
selectPaperclipPromptSections,
selectInitialCommunicationGuidance,
isPaperclipRecoveryWakePayload,
DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,
@@ -569,39 +568,40 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
run: { id: runId, source: "on_demand" },
context,
};
const renderedBootstrapPrompt =
!sessionId && bootstrapPromptTemplate.trim().length > 0
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
: "";
const taskContextNote = context.conversationMode === true
? selectPaperclipTaskMarkdown(context, { resumedSession: Boolean(sessionId), includeCommunicationGuidance: false })
: "";
const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, {
conversationMode: context.conversationMode === true,
resumedSession: Boolean(sessionId),
suppressIssueDescription: taskContextNote.length > 0,
});
const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0;
const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
? ""
: renderTemplate(promptTemplate, templateData);
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
const basePrompt = joinPromptSections([
instructionsPrefix,
renderedBootstrapPrompt,
wakePrompt,
taskContextNote,
sessionHandoffNote,
renderedPrompt,
]);
const promptMetrics = {
promptChars: basePrompt.length,
instructionsChars: instructionsPrefix.length,
bootstrapPromptChars: renderedBootstrapPrompt.length,
wakePromptChars: wakePrompt.length,
taskContextChars: taskContextNote.length,
sessionHandoffChars: sessionHandoffNote.length,
heartbeatPromptChars: renderedPrompt.length,
const buildPrompt = (resumedSession: boolean) => {
const renderedBootstrapPrompt =
!resumedSession && bootstrapPromptTemplate.trim().length > 0
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
: "";
const { taskContextNote, wakePrompt } = selectPaperclipPromptSections(context, {
resumedSession,
includeCommunicationGuidance: false,
});
const shouldUseResumeDeltaPrompt = resumedSession && wakePrompt.length > 0;
const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
? ""
: renderTemplate(promptTemplate, templateData);
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
const basePrompt = joinPromptSections([
instructionsPrefix,
renderedBootstrapPrompt,
wakePrompt,
taskContextNote,
sessionHandoffNote,
renderedPrompt,
]);
return {
basePrompt,
promptMetrics: {
promptChars: basePrompt.length,
instructionsChars: instructionsPrefix.length,
bootstrapPromptChars: renderedBootstrapPrompt.length,
wakePromptChars: wakePrompt.length,
taskContextChars: taskContextNote.length,
sessionHandoffChars: sessionHandoffNote.length,
heartbeatPromptChars: renderedPrompt.length,
},
};
};
// Optional diagnostic: surface OpenCode's own logs on stderr (captured into the
@@ -623,6 +623,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
};
const runAttempt = async (resumeSessionId: string | null) => {
const { basePrompt, promptMetrics } = buildPrompt(Boolean(resumeSessionId));
const prompt = joinPromptSections([
selectInitialCommunicationGuidance(context, { resumedSession: Boolean(resumeSessionId) }),
basePrompt,
@@ -1,7 +1,8 @@
import { mkdir, mkdtemp, rm } from "node:fs/promises";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createPromptContextFixture } from "@paperclipai/adapter-utils/test-fixtures/prompt-context";
const {
runChildProcess,
@@ -90,6 +91,16 @@ vi.mock("@paperclipai/adapter-utils/execution-target", async () => {
};
});
vi.mock("./models.js", async () => {
const actual = await vi.importActual<typeof import("./models.js")>("./models.js");
return {
...actual,
ensurePiModelConfiguredAndAvailable: vi.fn(async () => [
{ id: "openai/gpt-5.4-mini", label: "openai/gpt-5.4-mini" },
]),
};
});
import { execute } from "./execute.js";
describe("pi remote execution", () => {
@@ -558,8 +569,9 @@ describe("pi remote execution", () => {
sessionDisplayId: "session-123",
taskKey: null,
},
config: { command: "pi", model: "openai/gpt-5.4-mini" },
config: { command: "pi", model: "openai/gpt-5.4-mini", bootstrapPromptTemplate: "BOOTSTRAP {{run.id}}" },
context: {
...createPromptContextFixture(),
paperclipWorkspace: { cwd: workspaceDir, source: "project_primary" },
},
executionTransport: {
@@ -582,5 +594,183 @@ describe("pi remote execution", () => {
expect(sessionIndex).toBeGreaterThanOrEqual(0);
const usedSession = sessionIndex >= 0 ? call?.[2][sessionIndex + 1] : null;
expect(usedSession).not.toBe("/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl");
const prompt = String(call?.[2].at(-1) ?? "");
expect(prompt).toContain("## Owned assignment");
expect(prompt).toContain("BOOTSTRAP run-ssh-head-failure");
expect(prompt).toContain("comment-scope");
});
it("delivers the owned assignment and ordered wake comments through Pi's prompt", async () => {
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-context-ownership-"));
cleanupDirs.push(rootDir);
await mkdir(rootDir, { recursive: true });
const fixture = createPromptContextFixture();
let deliveredPrompt = "";
await execute({
runId: "run-context-ownership",
agent: {
id: "agent-1",
companyId: "company-1",
name: "Pi Builder",
adapterType: "pi_local",
adapterConfig: {},
},
runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
config: { command: "pi", model: "openai/gpt-5.4-mini", cwd: rootDir },
context: { ...fixture, paperclipWorkspace: { cwd: rootDir, source: "project_primary" } },
onLog: async () => {},
} as never);
const call = runChildProcess.mock.calls.at(-1) as unknown as [string, string, string[]] | undefined;
deliveredPrompt = String(call?.[2].at(-1) ?? "");
expect(deliveredPrompt).toContain(fixture.paperclipTaskMarkdownAssignment);
expect(deliveredPrompt.indexOf("Append the same ledger entry.")).toBeLessThan(
deliveredPrompt.lastIndexOf("Append the same ledger entry."),
);
expect(deliveredPrompt.indexOf("comment-first")).toBeLessThan(
deliveredPrompt.indexOf("comment-second"),
);
expect(deliveredPrompt.indexOf("comment-second")).toBeLessThan(
deliveredPrompt.indexOf("comment-scope"),
);
expect(deliveredPrompt).toContain("Change the final scope to the launch checklist.");
});
it("keeps the default Paperclip policy in the system carrier without duplicating it in user input", async () => {
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-default-policy-"));
cleanupDirs.push(rootDir);
await execute({
runId: "run-default-policy",
agent: {
id: "agent-1",
companyId: "company-1",
name: "Pi Builder",
adapterType: "pi_local",
adapterConfig: {},
},
runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
config: { command: "pi", model: "openai/gpt-5.4-mini", cwd: rootDir },
context: {},
onLog: async () => {},
} as never);
const call = runChildProcess.mock.calls.at(-1) as unknown as [string, string, string[]] | undefined;
const args = call?.[2] ?? [];
const systemPrompt = args[args.indexOf("--append-system-prompt") + 1] ?? "";
const userPrompt = args.at(-1) ?? "";
expect(systemPrompt).toContain("You are agent agent-1 (Pi Builder).");
expect(userPrompt).not.toContain("You are agent agent-1 (Pi Builder).");
});
it("preserves custom prompt templates in both configured carriers", async () => {
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-custom-policy-"));
cleanupDirs.push(rootDir);
await execute({
runId: "run-custom-policy",
agent: {
id: "agent-1",
companyId: "company-1",
name: "Pi Builder",
adapterType: "pi_local",
adapterConfig: {},
},
runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
config: {
command: "pi",
model: "openai/gpt-5.4-mini",
cwd: rootDir,
promptTemplate: "CUSTOM POLICY {{run.id}}",
},
context: {},
onLog: async () => {},
} as never);
const call = runChildProcess.mock.calls.at(-1) as unknown as [string, string, string[]] | undefined;
const args = call?.[2] ?? [];
const systemPrompt = args[args.indexOf("--append-system-prompt") + 1] ?? "";
const userPrompt = args.at(-1) ?? "";
expect(systemPrompt).toBe("CUSTOM POLICY run-custom-policy");
expect(userPrompt).toBe("CUSTOM POLICY run-custom-policy");
});
it("keeps the resumed default execution contract in the system carrier only", async () => {
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-resumed-policy-"));
cleanupDirs.push(rootDir);
const sessionPath = path.join(rootDir, "session.jsonl");
await writeFile(sessionPath, `${JSON.stringify({ type: "session", cwd: rootDir })}\n`, "utf8");
await execute({
runId: "run-resumed-policy",
agent: {
id: "agent-1",
companyId: "company-1",
name: "Pi Builder",
adapterType: "pi_local",
adapterConfig: {},
},
runtime: {
sessionId: sessionPath,
sessionParams: { sessionId: sessionPath, cwd: rootDir },
sessionDisplayId: "session-resumed-policy",
taskKey: null,
},
config: { command: "pi", model: "openai/gpt-5.4-mini", cwd: rootDir },
context: createPromptContextFixture(),
onLog: async () => {},
} as never);
const call = runChildProcess.mock.calls.at(-1) as unknown as [string, string, string[]] | undefined;
const args = call?.[2] ?? [];
const systemPrompt = args[args.indexOf("--append-system-prompt") + 1] ?? "";
const userPrompt = args.at(-1) ?? "";
expect(systemPrompt).toContain("Execution contract:");
expect(userPrompt).not.toContain("Execution contract:");
});
it("keeps the default contract in system input when custom prompt uses loaded instructions", async () => {
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-instructions-policy-"));
cleanupDirs.push(rootDir);
const sessionPath = path.join(rootDir, "session.jsonl");
const instructionsPath = path.join(rootDir, "AGENTS.md");
await writeFile(sessionPath, `${JSON.stringify({ type: "session", cwd: rootDir })}\n`, "utf8");
await writeFile(instructionsPath, "Loaded instructions for this run.\n", "utf8");
await execute({
runId: "run-instructions-policy",
agent: {
id: "agent-1",
companyId: "company-1",
name: "Pi Builder",
adapterType: "pi_local",
adapterConfig: {},
},
runtime: {
sessionId: sessionPath,
sessionParams: { sessionId: sessionPath, cwd: rootDir },
sessionDisplayId: "session-instructions-policy",
taskKey: null,
},
config: {
command: "pi",
model: "openai/gpt-5.4-mini",
cwd: rootDir,
instructionsFilePath: "AGENTS.md",
promptTemplate: "CUSTOM POLICY {{run.id}}",
},
context: createPromptContextFixture(),
onLog: async () => {},
} as never);
const call = runChildProcess.mock.calls.at(-1) as unknown as [string, string, string[]] | undefined;
const args = call?.[2] ?? [];
const systemPrompt = args[args.indexOf("--append-system-prompt") + 1] ?? "";
const userPrompt = args.at(-1) ?? "";
expect(systemPrompt).toContain("Loaded instructions for this run.");
expect(systemPrompt).toContain("Execution contract:");
expect(userPrompt).not.toContain("CUSTOM POLICY run-instructions-policy");
expect(userPrompt).not.toContain("Execution contract:");
});
});
@@ -45,8 +45,7 @@ import {
resolveLegacyPaperclipDesiredSkillNames,
removeMaintainerOnlySkillSymlinks,
renderTemplate,
renderPaperclipWakePrompt,
selectPaperclipTaskMarkdown,
selectPaperclipPromptSections,
selectInitialCommunicationGuidance,
isPaperclipRecoveryWakePayload,
DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,
@@ -236,6 +235,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
? DEFAULT_PAPERCLIP_CONVERSATION_PROMPT_TEMPLATE
: DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,
);
const hasCustomPromptTemplate = asString(config.promptTemplate, "").trim().length > 0;
const command = asString(config.command, "pi");
const model = asString(config.model, "").trim();
const thinking = asString(config.thinking, "").trim();
@@ -615,39 +615,8 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
context,
};
const renderedSystemPromptExtension = renderTemplate(systemPromptExtension, templateData);
const renderedBootstrapPrompt =
!canResumeSession && bootstrapPromptTemplate.trim().length > 0
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
: "";
const taskContextNote = context.conversationMode === true
? selectPaperclipTaskMarkdown(context, { resumedSession: canResumeSession, includeCommunicationGuidance: false })
: "";
const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, {
conversationMode: context.conversationMode === true,
resumedSession: canResumeSession,
suppressIssueDescription: taskContextNote.length > 0,
});
const shouldUseResumeDeltaPrompt = canResumeSession && wakePrompt.length > 0;
const renderedHeartbeatPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)
? ""
: renderTemplate(promptTemplate, templateData);
const systemOwnsDefaultPolicy = !hasCustomPromptTemplate || Boolean(resolvedInstructionsFilePath && !instructionsReadFailed);
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
const baseUserPrompt = joinPromptSections([
renderedBootstrapPrompt,
wakePrompt,
taskContextNote,
sessionHandoffNote,
renderedHeartbeatPrompt,
]);
const promptMetrics = {
systemPromptChars: renderedSystemPromptExtension.length,
promptChars: baseUserPrompt.length,
bootstrapPromptChars: renderedBootstrapPrompt.length,
wakePromptChars: wakePrompt.length,
taskContextChars: taskContextNote.length,
sessionHandoffChars: sessionHandoffNote.length,
heartbeatPromptChars: renderedHeartbeatPrompt.length,
};
const commandNotes = (() => {
const notes = [...preparedRuntimeConfig.notes];
@@ -692,10 +661,41 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
};
const runAttempt = async (sessionFile: string) => {
const userPrompt = joinPromptSections([
selectInitialCommunicationGuidance(context, { resumedSession: canResumeSession && sessionFile === sessionPath }),
baseUserPrompt,
const attemptResumedSession = canResumeSession && sessionFile === sessionPath;
const attemptSections = selectPaperclipPromptSections(context, {
resumedSession: attemptResumedSession,
includeCommunicationGuidance: false,
includeExecutionContract: systemOwnsDefaultPolicy ? false : undefined,
});
const attemptBootstrapPrompt = !attemptResumedSession && bootstrapPromptTemplate.trim().length > 0
? renderTemplate(bootstrapPromptTemplate, templateData).trim()
: "";
const attemptWakePrompt = attemptSections.wakePrompt;
const attemptRenderedHeartbeatPrompt = attemptResumedSession && attemptWakePrompt.length > 0
|| isPaperclipRecoveryWakePayload(context.paperclipWake)
|| !hasCustomPromptTemplate
? ""
: renderTemplate(promptTemplate, templateData);
const attemptBaseUserPrompt = joinPromptSections([
attemptBootstrapPrompt,
attemptWakePrompt,
attemptSections.taskContextNote,
sessionHandoffNote,
attemptRenderedHeartbeatPrompt,
]);
const userPrompt = joinPromptSections([
selectInitialCommunicationGuidance(context, { resumedSession: attemptResumedSession }),
attemptBaseUserPrompt,
]);
const promptMetrics = {
systemPromptChars: renderedSystemPromptExtension.length,
promptChars: userPrompt.length,
bootstrapPromptChars: attemptBootstrapPrompt.length,
wakePromptChars: attemptWakePrompt.length,
taskContextChars: attemptSections.taskContextNote.length,
sessionHandoffChars: sessionHandoffNote.length,
heartbeatPromptChars: attemptRenderedHeartbeatPrompt.length,
};
const args = buildArgs(sessionFile, userPrompt);
if (onMeta) {
await onMeta({