Files
PaperClipAI/packages/adapter-utils/src/agent-observability.test.ts
T
DottaandPaperclip b81b870732 Add QA smoke journeys and OpenCode run traces (#18098)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Product E2E journeys verify saved application behavior across
deployments.
> - Task creation and questions need reusable smoke selections and exact
run attribution.
> - Operators also need to inspect the OpenCode execution behind a
measured question.
> - Company observability does not currently support native OpenCode.
> - This change adds the journeys and a bounded projection of normalized
OpenCode run events.
> - The projection follows the configured capture policy and retains the
current run identity across warm reuse.

## Linked Issues or Issue Description

Related foundation: #17262. Related alternative: #17989 exports metadata
from OpenCode's native OTLP stream. This change uses normalized run
events to support the existing content switches and per-run linkage. It
does not forward the native stream. The two PRs overlap in launch
registration and must be reconciled before both land.

**What existing behavior does this improve?**

Reusable Product E2E smoke selections and company observability for
native OpenCode.

**Current behavior**

The journey catalog lacks reusable task creation and attached-agent
question checks. Native OpenCode is marked unsupported for company
observability, so a successful destination connection test does not
prove that agent traces will appear.

**Proposed behavior**

Add explicit task-create and ask-question selections. Verify saved state
and exact company, issue, agent, model, environment and successful run
attribution. Export normalized OpenCode turns, tools and usage to the
configured OTLP destination. Honor each capture switch and redact known
secrets.

**Reason and benefit**

CI can run a small measured smoke selection, retain its screenshots and
checks, and link results to traces belonging to the same run.

**Breaking changes**

Existing selectors remain unchanged. OpenCode export is opt-in through
existing company settings. Legacy OpenCode stays unsupported.

## What Changed

- Add reusable task creation and question journeys, configured-agent
capability, owned-fixture checkpoints and strict evidence validation.
- Add an OpenCode-owned projection of normalized run events. No provider
SDK or raw payload schema enters heartbeat coordination.
- Extend the private launch union and reserved environment allowlist for
native OpenCode. With export disabled, no receiver request runs.
- Keep destination headers in the parent wrapper and out of the actual
provider child environment and configuration.
- Bound each turn to 64 tool and 64 usage entries, 8 KiB per text field
and a 1 MiB request. Use a three-second request deadline, four
concurrent exports, and no retries or idle worker.
- Pass the rotated runner authority to each proxy turn. A retained
process no longer attributes later turns to its original launch run.
- Update settings copy, observability documentation and capability maps.

## Verification

- `pnpm -r typecheck` and `pnpm build` passed after the implementation
changes.
- Adapter launch/redaction: 9 tests passed. Projection and actual proxy:
12 tests passed before the review fix; the expanded projection suite
passed all 12 cases after the fix. The proxy test exercises two runs in
one process against a real local HTTP receiver and a fake provider.
- Full OpenCode driver/projection suite: 72 passed, one existing
response_wake test timed out at five seconds. A focused check then
passed both existing omitted-continuation cases and the new trace export
case. The timeout cause remains unconfirmed.
- Runner package TypeScript and Rust `cargo check` passed. Map and UI
token checks passed.
- Prior journey validation: 273 tests across 12 files and the journey
TypeScript check passed.
- Broad local `pnpm test:run` encountered native-runtime integration
failures with repeated embedded PostgreSQL initialization failures and
was stopped. All 16 failing cases passed in an isolated run outside the
filesystem sandbox (961 unrelated cases unselected). The broad local run
is not a clean acceptance result. A later focused database-backed
chat/heartbeat run passed all six selected observability cases,
including native OpenCode launch and successful allocation (1,809
unrelated cases were unselected).
- All CI gates passed for `21085f880d8babc9efeb22d0623db99613d33093`,
including packaged-runner, clean-install, browser and build checks:
https://github.com/paperclipai/paperclip/actions/runs/40884658995 .
Greptile reviewed the same commit at 5/5 with no unresolved findings.
- Verified OTLP JSON acceptance and indexing with an explicitly
synthetic transport marker. No live OpenCode model trace or deployed
smoke acceptance is claimed yet.

## Risks

Export is best effort. Abrupt termination, recovered in-flight turns
without a new submitted event, limits or receiver failure can lose
traces. Export failure does not change task success. The projection
represents observed normalized events, not raw native model spans or
hidden reasoning. Known-secret redaction is not an OS isolation
boundary. UI changes can break journey locators. Deployment adapters
retain credential, ownership and cleanup responsibility. Both the
controller and native runner bundle must be updated before live
qualification.

## Model Used

OpenAI Codex, GPT-6, with reasoning, code execution and browser tools.
The exact serving model ID 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 (targeted suites; broad
local limitation documented above)
- [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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-29 08:57:12 -05:00

126 lines
9.5 KiB
TypeScript

import { afterEach, expect, it } from "vitest";
import { lstat, mkdtemp, readFile, readlink, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { parse } from "smol-toml";
import { DEFAULT_AGENT_OBSERVABILITY_CAPTURE } from "@paperclipai/shared";
import { buildProviderObservabilityLaunch, applyObservabilityEnvironment, observabilitySecretValues } from "./agent-observability.js";
import { prepareCodexObservabilityProfile, replaceCodexProfileArgs, selectedCodexProfile, disableCodexObservabilityArgs } from "./codex-observability-profile.js";
import { buildInvocationEnvForLogs } from "./server-utils.js";
import { prepareAcpxCodexObservabilityHome } from "./codex-observability-home.js";
const roots: string[] = [];
afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); });
const input = { companyId: "company", agentId: "agent", revision: "revision", compatibilityKey: "version", enabled: true,
capture: { ...DEFAULT_AGENT_OBSERVABILITY_CAPTURE }, logsEndpoint: "https://collector.example/v1/logs", tracesEndpoint: "https://collector.example/v1/traces", headers: { authorization: "Bearer a,b=c% d" } };
it("encodes headers losslessly and clears ambient exporter conflicts without changing host state", () => {
const launch = buildProviderObservabilityLaunch({ ...input, kind: "claude" });
const env = { OTEL_EXPORTER_OTLP_HEADERS: "ambient", OTEL_EXPORTER_OTLP_ENDPOINT: "https://wrong", KEEP: "ok" };
applyObservabilityEnvironment(env, launch);
expect(env).not.toHaveProperty("OTEL_EXPORTER_OTLP_HEADERS");
expect(env).toHaveProperty("KEEP", "ok");
const encoded = launch.environment.OTEL_EXPORTER_OTLP_LOGS_HEADERS;
expect(decodeURIComponent(encoded.slice(encoded.indexOf("=") + 1))).toBe(input.headers.authorization);
expect(observabilitySecretValues(launch)).toContain(input.headers.authorization);
expect(JSON.stringify(buildInvocationEnvForLogs({ ...launch.environment }))).not.toContain("a%2Cb");
});
it("keeps Codex headers in the launch environment and preserves literal percent sequences", () => {
const original = "Bearer a,b=%26 c%";
const launch = buildProviderObservabilityLaunch({ ...input, kind: "codex", headers: { authorization: original } });
const exporter = launch.otelConfig!.exporter as { "otlp-http": { headers: Record<string, string> } };
expect(exporter["otlp-http"].headers).toEqual({});
for (const key of ["OTEL_EXPORTER_OTLP_LOGS_HEADERS", "OTEL_EXPORTER_OTLP_TRACES_HEADERS"]) {
expect(launch.environment[key]).toBe(`authorization=${encodeURIComponent(original)}`);
}
expect(JSON.stringify(launch.otelConfig)).not.toContain(original);
expect(JSON.stringify(launch.otelConfig)).not.toContain(encodeURIComponent(original));
expect(observabilitySecretValues(launch)).toContain(original);
expect(observabilitySecretValues(launch)).toContain(encodeURIComponent(original));
expect(observabilitySecretValues(launch)).toContain(original.slice(7));
expect(JSON.stringify(buildInvocationEnvForLogs({ ...launch.environment }))).not.toContain("a%2Cb");
const disabled = buildProviderObservabilityLaunch({ ...input, kind: "codex", enabled: false });
expect(disabled.environment).not.toHaveProperty("OTEL_EXPORTER_OTLP_LOGS_HEADERS");
expect(disabled.environment).not.toHaveProperty("OTEL_EXPORTER_OTLP_TRACES_HEADERS");
});
it("replaces a compact explicit profile without leaving competing profile flags", () => {
const args = ["exec", "-preview", "-"];
expect(selectedCodexProfile(args)).toBe("review");
replaceCodexProfileArgs(args, "generated");
expect(args).toEqual(["--profile", "generated", "exec", "-"]);
});
it("keeps an explicit source profile while disabling export after preparation fails", () => {
const args = ["--profile", "review", "exec", "-"];
disableCodexObservabilityArgs(args);
expect(selectedCodexProfile(args)).toBe("review");
expect(args).toContain('otel.exporter="none"');
expect(args).toContain('otel.trace_exporter="none"');
expect(args).toContain('otel.metrics_exporter="none"');
});
it("creates invocation-owned profiles, preserves selected profile settings, and restores by deleting only its own file", async () => {
const root = await mkdtemp(join(tmpdir(), "paperclip-otel-profile-")); roots.push(root);
await writeFile(join(root, "review.config.toml"), 'model = "chosen-model"\n[otel]\nexporter = "none"\n');
const launch = buildProviderObservabilityLaunch({ ...input, kind: "codex" });
const a = await prepareCodexObservabilityProfile({ home: root, runId: "run-a", sourceProfile: "review", launch });
const b = await prepareCodexObservabilityProfile({ home: root, runId: "run-b", launch });
const parsed = parse(await readFile(join(root, a.filename), "utf8"));
expect(JSON.stringify(parsed)).not.toContain(input.headers.authorization);
expect(JSON.stringify(parsed)).not.toContain(encodeURIComponent(input.headers.authorization));
expect(parsed.model).toBe("chosen-model");
expect(parsed.otel).toMatchObject({ log_agent_responses: true, tool_result: { max_bytes: 65536 } });
expect((await stat(join(root, a.filename))).mode & 0o777).toBe(0o600);
const args = ["exec", "--profile=review", "resume", "session", "-"];
replaceCodexProfileArgs(args, a.name);
expect(args).toEqual(["--profile", a.name, "exec", "resume", "session", "-"]);
await a.cleanup();
expect(await readFile(join(root, b.filename), "utf8")).toContain("otel");
expect(await readFile(join(root, "review.config.toml"), "utf8")).toContain('exporter = "none"');
});
it("isolates overlapping ACPX export settings while sharing the saved provider conversation", async () => {
const home = await mkdtemp(join(tmpdir(), "paperclip-acpx-otel-")); roots.push(home);
await writeFile(join(home, "config.toml"), 'model = "retained-model"\n');
const first = buildProviderObservabilityLaunch({ ...input, kind: "codex", compatibilityKey: "first" });
const second = buildProviderObservabilityLaunch({ ...input, kind: "codex", compatibilityKey: "second", enabled: false });
const otherAgent = buildProviderObservabilityLaunch({ ...input, kind: "codex", compatibilityKey: "first", agentId: "other-agent" });
const [a, b, c] = await Promise.all([
prepareAcpxCodexObservabilityHome(home, first, input.agentId),
prepareAcpxCodexObservabilityHome(home, second, input.agentId),
prepareAcpxCodexObservabilityHome(home, otherAgent, "other-agent"),
]);
expect(a).not.toBe(c);
expect(parse(await readFile(join(a, "config.toml"), "utf8")).otel).toMatchObject({ span_attributes: { "paperclip.agent.id": input.agentId } });
expect(parse(await readFile(join(c, "config.toml"), "utf8")).otel).toMatchObject({ span_attributes: { "paperclip.agent.id": "other-agent" } });
await writeFile(join(a, "sessions", "saved-conversation.jsonl"), "conversation checkpoint");
expect(await readFile(join(b, "sessions", "saved-conversation.jsonl"), "utf8")).toBe("conversation checkpoint");
expect(parse(await readFile(join(a, "config.toml"), "utf8")).otel).toMatchObject({ log_agent_responses: true });
expect(parse(await readFile(join(b, "config.toml"), "utf8")).otel).toMatchObject({ exporter: "none" });
expect(parse(await readFile(join(a, "config.toml"), "utf8")).model).toBe("retained-model");
expect(await readFile(join(home, "config.toml"), "utf8")).toBe('model = "retained-model"\n');
expect((await stat(a)).mode & 0o777).toBe(0o700);
expect((await stat(join(a, "config.toml"))).mode & 0o777).toBe(0o600);
});
it.each([true, false])("preserves refreshed Codex credentials across repeated and replacement preparations with export %s", async enabled => {
const home = await mkdtemp(join(tmpdir(), "paperclip-acpx-auth-")); roots.push(home);
await writeFile(join(home, "auth.json"), JSON.stringify({ tokens: { refresh_token: "old-fixture-token" } }), { mode: 0o600 });
const launch = buildProviderObservabilityLaunch({ ...input, enabled, kind: "codex" });
const first = await prepareAcpxCodexObservabilityHome(home, launch, input.agentId);
expect((await lstat(join(first, "auth.json"))).isSymbolicLink()).toBe(true);
expect(await readlink(join(first, "auth.json"))).toBe(join(home, "auth.json"));
await writeFile(join(first, "auth.json"), JSON.stringify({ tokens: { refresh_token: "refreshed-fixture-token" } }));
expect(JSON.parse(await readFile(join(home, "auth.json"), "utf8")).tokens.refresh_token).toBe("refreshed-fixture-token");
const repeated = await prepareAcpxCodexObservabilityHome(home, launch, input.agentId);
const replacement = await prepareAcpxCodexObservabilityHome(home, { ...launch, compatibilityKey: "replacement" }, input.agentId);
for (const prepared of [repeated, replacement]) {
expect(JSON.parse(await readFile(join(prepared, "auth.json"), "utf8")).tokens.refresh_token).toBe("refreshed-fixture-token");
}
});
it("keeps OpenCode export opt-in and credentials out of ordinary task environment projections", () => {
const launch = buildProviderObservabilityLaunch({ ...input, kind: "opencode" });
expect(launch.environment).toMatchObject({ PAPERCLIP_OBSERVABILITY_OPENCODE: "1", OTEL_LOG_USER_PROMPTS: "1", OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: input.tracesEndpoint });
expect(observabilitySecretValues(launch)).toContain(input.headers.authorization);
expect(JSON.stringify(buildInvocationEnvForLogs({ ...launch.environment }))).not.toContain("a%2Cb");
const disabled = buildProviderObservabilityLaunch({ ...input, kind: "opencode", enabled: false });
expect(disabled.environment).toMatchObject({ PAPERCLIP_OBSERVABILITY_OPENCODE: "0" });
expect(disabled.environment).not.toHaveProperty("OTEL_EXPORTER_OTLP_TRACES_HEADERS");
});