Files
PaperClipAI/packages/paperclip-runner/src/drivers/opencode/company-observability-runtime.test.ts
T
DottaandPaperclip ee68098584 fix(runner): keep current task requests readable in OpenCode traces (#21584)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Company traces let operators compare each request with its reply.
> - OpenCode limits each text field to 8 KiB.
> - A fresh session can put old history before the current request.
> - The limit can remove the current request from the trace.
> - This change selects the current task text first and links the
retained submission.

## Linked Issues or Issue Description

Refs #18098 and #18699. Neither merged change selects the current task
request.

**What existing behavior does this improve?**

OpenCode company traces can contain only part of the old session
history.

**Current behavior**

The exporter clips the full model envelope from its start. A sampled
trace has a useful HOLD reply but a request that ends inside old
history. A truncation flag is not proof that the task failed.

**Proposed behavior**

Select the task prompt before the text limit. Remove a valid leading
generated handoff packet from the excerpt. Link the full retained run
event through the existing API.

[Source
pattern](https://www.braintrust.dev/app/Paperclip/p/Paperclip%20Staging/patterns/e6d8da04-ca3e-4bd9-bd90-737f7717a9e1).

### Hypothesis and thesis for a fix

The baseline exporter spends its text budget on the envelope and old
history. The new regression confirms this cause: the received OTLP input
loses a short current request after a long handoff. Select the current
request in the OpenCode projection before redaction and clipping. Keep
storage and access checks with their existing owners.

## What Changed

- Select task identity and prompt for known native envelopes. Put
pending user messages first in continuation excerpts.
- Omit only a valid leading generated handoff packet. Keep plain text
and unknown formats on the existing path.
- Add a relative run-events reference under the prompt capture switch.
Readers must sign in to the source instance and page to the matching
turn.
- Keep raw tool argument values excluded. Keep redaction, opt-in,
capture switches, company access and size limits.
- Add exporter, proxy, installed-runtime and private-run retrieval
tests. Fix the proxy test's session-directory lookup so it skips the
output-custody directory.
- Document the excerpt and full-event retrieval path.

## Verification

- Baseline `6b6c94a4ea8f3d1b58767d67a7a2fc4ceaecda9c`: the new
long-handoff regression failed because OTLP input did not contain the
current request.
- Same regression passes after the fix. Exporter, redaction and bundled
proxy suites: 39 tests passed.
- `PAPERCLIP_OPENCODE_QUALIFY=1 pnpm --dir packages/paperclip-runner
exec vitest run
src/drivers/opencode/company-observability-runtime.test.ts`: 2 passed.
Real installed OpenCode 1.18.34 and real HTTP OTLP receiver; local SSE
model fixture. Both capture settings pass. The model receives the full
original submission.
- Private-run API suite: 31 tests passed on base
`340157d1d6ec01ad0fa55970e148c6cd332bbcb1` with these changes.
Authorized readers retrieve a complete request over 8 KiB through
pagination. Other readers receive 404.
- Runner TypeScript source and test checks and TypeScript build passed.
`git diff --check` passed.
- `pnpm verify --explain` returned exit 2 and required broader CI. No
full local-suite pass is claimed.
- Initial harness attempts used the wrong Vitest working directory,
lacked built plugin-sdk, selected the wrong proxy fixture directory, or
expected 403 instead of the API's 404. These are not red regression
results. The corrected checks above pass.
- Review follow-up `dfe995a77f3eb3280a6b081b4df9428fac85f540` removes
added code comments required by CONTRIBUTING.md. Exporter + installed
OpenCode runtime suites reran: 30 tests passed, with the local SSE model
and real HTTP OTLP receiver. `git diff --check` passed. The review
thread is resolved. Greptile passed on this exact revision with
confidence 5/5 and no actionable findings. Final-head typecheck, build,
Runner and E2E checks passed; server test shards and the amd64 Runner
image build remain in progress. No hosted model call or deployed
recovery is claimed.

## Risks

Known envelope excerpts change shape from serialized envelope text to
readable task text. The handoff selector depends on the current
generated packet format; unknown framing falls back to the full prompt
excerpt. Long current requests still clip. Full-event access depends on
source-instance permission and retention. Export remains best effort.
The new reference grants no access and includes no credential. This PR
is unmerged and not deployed.

## Model Used

OpenAI GPT-6 through Codex, with reasoning, tool use and code execution.
The exact serving variant and context size are not exposed to this
session.

## 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 either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

Final verification (2026-11-14): exact head
`dfe995a77f3eb3280a6b081b4df9428fac85f540` has 60 successful checks, one
neutral security scan, and five conditional skips (cache write,
publication/attestation, incremental selection, Storybook paths).
Applicable typecheck, build, general and serialized tests, Runner tests,
E2E and both Runner image architectures passed.
[CI](https://github.com/paperclipai/paperclip/actions/runs/43572758306),
[Runner
images](https://github.com/paperclipai/paperclip/actions/runs/43572758233),
[Greptile](https://github.com/paperclipai/paperclip/runs/132380487679).
Greptile 5/5, no unresolved actionable findings. Unmerged and not
deployed.

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-18 15:08:04 -06:00

82 lines
4.9 KiB
TypeScript

import { createServer, type Server } from "node:http";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, it } from "vitest";
import { OpenCodeServerDriver } from "./opencode-server-driver.js";
const enabled = process.env.PAPERCLIP_OPENCODE_QUALIFY === "1";
async function listen(server: Server) {
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("receiver did not bind");
return `http://127.0.0.1:${address.port}`;
}
async function close(server: Server) {
server.closeAllConnections();
await new Promise<void>(resolve => server.close(() => resolve()));
}
it.skipIf(!enabled).each([true, false])("exports the current request through installed OpenCode with prompt capture %s", async capture => {
const root = await mkdtemp(join(tmpdir(), "opencode-observability-real-"));
const modelRequests: string[] = [];
const exports: any[] = [];
const model = createServer(async (request, response) => {
const chunks: Buffer[] = [];
for await (const chunk of request) chunks.push(Buffer.from(chunk));
modelRequests.push(Buffer.concat(chunks).toString());
response.writeHead(200, { "Content-Type": "text/event-stream" });
for (const [delta, finish_reason] of [[{ role: "assistant", content: "observability-runtime-answer" }, null], [{}, "stop"]]) {
response.write(`data: ${JSON.stringify({ id: "chatcmpl-local", object: "chat.completion.chunk", created: 1, model: "qualification", choices: [{ index: 0, delta, finish_reason }] })}\n\n`);
}
response.end("data: [DONE]\n\n");
});
const receiver = createServer(async (request, response) => {
const chunks: Buffer[] = [];
for await (const chunk of request) chunks.push(Buffer.from(chunk));
exports.push(JSON.parse(Buffer.concat(chunks).toString()));
response.end("{}");
});
let session: Awaited<ReturnType<OpenCodeServerDriver["openSession"]>> | undefined;
try {
const modelUrl = await listen(model), receiverUrl = await listen(receiver);
const driver = new OpenCodeServerDriver({
command: process.env.PAPERCLIP_TEST_OPENCODE_BINARY ?? "opencode", model: "paperclip/qualification",
runtimeDirectory: root, conversationMode: "prepared", permissionMode: "deny",
environment: { PATH: process.env.PATH, PAPERCLIP_AI_PROVIDER_URL: `${modelUrl}/v1`, PAPERCLIP_AI_PROVIDER_KEY: "local-fixture-only",
PAPERCLIP_OBSERVABILITY_OPENCODE: "1", OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: `${receiverUrl}/v1/traces`,
OTEL_LOG_USER_PROMPTS: capture ? "1" : "0", OTEL_LOG_ASSISTANT_RESPONSES: "1",
OTEL_RESOURCE_ATTRIBUTES: "paperclip.company.id=disposable-company" },
});
session = await driver.openSession({ runId: "disposable-run", normalizedSessionId: "disposable-session", workingDirectory: root });
const history = ["## Fresh session handoff", "History guidance.", JSON.stringify({ schema: "paperclip.native-session-handoff.v1", entries: [{ body: "old history ".repeat(1800) }] })].join("\n");
const text = JSON.stringify({ schema: "paperclip.native-model-envelope.v3", task: { identifier: "TEST-1", title: "Current task", prompt: `${history}\n\ncurrent-runtime-request-canary` } });
await session.startTurn({ message: { role: "user", text } });
const events = [];
for await (const event of session.events()) {
events.push(event);
if (["turn.completed", "turn.failed", "turn.interrupted", "turn.cancelled"].includes(event.eventType)) break;
}
expect(events.at(-1)?.eventType).toBe("turn.completed");
await session.close({ reason: "test" });
session = undefined;
expect(modelRequests.some(body => body.includes("current-runtime-request-canary") && body.includes("old history"))).toBe(true);
expect(events.find(event => event.eventType === "turn.submitted")?.payload.text).toBe(text);
expect(exports).toHaveLength(1);
const attrs = Object.fromEntries(exports[0].resourceSpans[0].scopeSpans[0].spans[0].attributes.map((a: any) => [a.key, a.value.stringValue ?? a.value.boolValue]));
expect(attrs["braintrust.output"]).toBe("observability-runtime-answer");
if (capture) {
expect(attrs["braintrust.input"]).toContain("current-runtime-request-canary");
expect(attrs["braintrust.input"]).not.toContain("old history");
expect(attrs["paperclip.observability.input.events"]).toBe("/api/heartbeat-runs/disposable-run/events");
} else {
expect(attrs).not.toHaveProperty("braintrust.input");
expect(attrs).not.toHaveProperty("paperclip.observability.input.events");
expect(JSON.stringify(exports)).not.toContain("current-runtime-request-canary");
}
} finally {
await session?.close({ reason: "test" });
await Promise.all([close(model), close(receiver)]);
await rm(root, { recursive: true, force: true });
}
}, 60_000);