Files
PaperClipAI/tests/runner-e2e/chat-catalog-domains/identity-observability.ts
T
DottaandClaude Opus 5.5 65ff80a4bb fix(evals): grade chat acknowledgements, saved replies and links on saved state (#21000)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The chat eval catalog runs real chat journeys against real agents
and grades saved product state
> - A review of full cohort 3 found three cases whose oracle passed
wrong behavior, and eight passes whose final evidence saved no rendered
links
> - `companies.agent-observability` passed although the agent denied the
saved collector. `inbox-search.show-my-work` counted links that existed
only in run-stream prose. `instance-operations.restart-service` accepted
a reply whose only link was the `/<prefix>/` placeholder
> - The final evidence read ran on a page that had not rendered the
conversation yet, so it saved no links
> - This pull request grades those cases on saved-state reads, the saved
reply and resolved links, and reads final evidence from the rendered
conversation
> - The benefit is that these cases fail when the product is wrong and
keep their links when it is right

## Linked Issues or Issue Description

Refs #20998
Refs #20999

**What happened?**
- `companies.agent-observability`: the board saved and tested a
collector. Asked to acknowledge it, the agent said there was no endpoint
or credentials. The oracle graded only human-side state, so it passed.
- `inbox-search.show-my-work`: the saved reply said "Answered above"
over nothing. The links the oracle counted came from run-stream prose
that the bubble also shows.
- `instance-operations.restart-service`: the reply's only action link
was `/<prefix>/company/settings/instance`. The oracle did not check
links.
- Eight cohort-3 passes (`access.other-company`, `agents.agent-api-key`,
`assistant-connections.revoke-personal-grant`,
`budgets-costs.resolve-budget`, `recovery.retry-exhausted`,
`steering.stop-versus-pause`, `task-coordination.pause-tree`,
`teams.install-team`) saved a final observation with no links and a
failed grade. The graded reload had the links. The final evidence read
ran after `verifyResult` left the page mid-load, and an expired render
wait from an earlier document made the read instant.

**Expected behavior**
Each oracle fails the observed wrong behavior and passes valid, reworded
behavior. Final evidence holds the links that the conversation renders.

**Steps to reproduce**
Grade the retained cohort-3 observations with the old oracles. They
pass. Grade them with these oracles. The three wrong cases fail.

## What Changed

- `companies.agent-observability` (oracle v4): each acknowledgement turn
must read the saved trace export status successfully. The read is bound
to the company by its redaction-safe `call_api` receipt. A reply must
also render a link to `/<prefix>/company/settings` for the fixture
company. The reply's wording is not matched.
- `inbox-search.show-my-work` (oracle v5): actionable links must be
carried by the saved reply: a Markdown link target in the saved body, or
a task identifier written in it, which the conversation links. New
shared helper `savedReplyLinks`.
- `instance-operations.restart-service` (oracle v3): new check
`reply-links-resolve` rejects any rendered or saved link target that
keeps a template placeholder (`<...>` or `{...}`). New helpers
`markdownLinkTargets` and `unresolvedLinkTarget` in
`chat-rendered-links.ts`.
- Link capture: the final success-path evidence read reopens the
rendered conversation first. An expired render wait now belongs to its
loaded document, not to the Playwright page.
- Updated `chat-catalog-descriptors.json` for the three oracle versions
and source files. No scenario yaml changed, so the TestOps manifest does
not change.

## Verification

- `npx vitest run --config tests/runner-e2e/vitest.config.ts
tests/runner-e2e/chat-catalog-domains/identity-observability.test.ts
tests/runner-e2e/chat-catalog-domains/internal.test.ts
tests/runner-e2e/chat-catalog-domains/privileged-oracles.test.ts
tests/runner-e2e/chat-catalog-domains/privileged-restart-history.test.ts
tests/runner-e2e/chat-rendered-links.test.ts
tests/runner-e2e/chat-catalog-consistency.test.ts
tests/runner-e2e/chat-catalog-fingerprint.test.ts`
- Calibration tests for each case: a valid result, a reworded valid
result, and the broken cohort-3 behavior.
- Red/green: the new render-wait test fails on the old wait logic and
passes with this change.
- `npx tsc -p tests/runner-e2e/tsconfig.json --noEmit` passes. `node
tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check` reports no
change.
- A paid run on a combined branch with the two product fixes is recorded
in a comment on this pull request.

## Risks

- `companies.agent-observability` needs the agent-readable status route
from #20998. Without it, the case fails, which is correct.
- The show-my-work check needs links in the saved reply. Before #20999,
an OpenCode reply that left its answer in the run stream fails this
case.
- The final evidence read can wait up to 30 seconds to reopen the
conversation. The read is still bounded.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code
execution in Claude Code.

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 20:49:38 -06:00

136 lines
14 KiB
TypeScript

import { waitForCompanySettingsTurn } from "./identity-company-observer.js";
import { privateIdentityBrowser } from "./identity-private-browser.js";
import { createServer, type Server } from "node:http";
import { randomBytes, createHash } from "node:crypto";
import { gunzipSync } from "node:zlib";
import { expect } from "@playwright/test";
import type { AgentObservabilitySettingsResponse, AgentObservabilityTestReceipt } from "../../../packages/shared/src/agent-observability.js";
import type { ChatCatalogCase, ChatCatalogContext } from "../chat-catalog-contract.js";
import { pollUntil } from "../api.js";
import { collectRunEvents } from "../run-observations.js";
import { readRecord, recordParams } from "./api-read-receipts.js";
import { sendChatMessage } from "../chat-flow.js";
import { checks, type InternalObservation } from "./internal-support.js";
import { identityDefinition, identityObservation, observeIdentity, probeAgentPermission } from "./identity-support.js";
interface Received { path: string; authenticated: boolean; body: Buffer; sha256: string }
interface Collector { server: Server; url: string; key: string; received: Received[] }
const collectors = new WeakMap<ChatCatalogContext, Collector>();
async function collector(): Promise<Collector> {
const key = randomBytes(32).toString("hex"); const received: Received[] = [];
const server = createServer(async (request, response) => {
try {
if (request.method !== "POST" || !["/v1/logs", "/v1/traces"].includes(request.url ?? "")) { response.writeHead(404).end(); return; }
const parts: Buffer[] = []; let size = 0;
for await (const part of request) { const bytes = Buffer.from(part); size += bytes.length; if (size > 2_097_152) { response.writeHead(413).end(); return; } parts.push(bytes); }
const bytes = Buffer.concat(parts); const body = request.headers["content-encoding"] === "gzip" ? gunzipSync(bytes, { maxOutputLength: 2_097_152 }) : bytes;
const authenticated = request.headers.authorization === `Bearer ${key}`;
received.push({ path: request.url!, body, authenticated, sha256: createHash("sha256").update(body).digest("hex") });
const json = String(request.headers["content-type"]).startsWith("application/json");
response.writeHead(authenticated ? 200 : 401, { "content-type": json ? "application/json" : "application/x-protobuf" }).end(json ? "{}" : Buffer.alloc(0));
} catch { response.writeHead(400).end(); }
});
await new Promise<void>((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); });
const address = server.address(); if (!address || typeof address === "string") throw new Error("Synthetic collector has no real local address");
return { server, url: `http://127.0.0.1:${address.port}`, key, received };
}
/** Company settings (where the Agent observability section lives) for this company's prefix, by rendered reply link. */
export function companySettingsLinked(o: Pick<InternalObservation, "links" | "origin">, prefix: unknown): boolean {
return typeof prefix === "string" && !!prefix && o.links.some(href => {
try {
const url = new URL(href, o.origin);
return url.origin === new URL(o.origin).origin && url.pathname.replace(/\/+$/, "") === `/${prefix}/company/settings`;
} catch { return false; }
});
}
/** The run read the company's saved trace export status (or, if ever permitted, its settings) successfully. */
export function readSavedObservabilityStatus(events: readonly Record<string, unknown>[], companyId: string): boolean {
const pathParams = [...recordParams("companyId", companyId), undefined];
return readRecord(events, ["GET /api/companies/{companyId}/observability/status", "GET /api/companies/{companyId}/observability"]
.map(operationId => ({ operationId, pathParams })));
}
async function turnReadSavedStatus(ctx: ChatCatalogContext, before: ReadonlySet<string>): Promise<boolean> {
const runs = (await ctx.allRuns()).filter(run => !before.has(run.id));
for (const run of runs) {
const events = await collectRunEvents<Record<string, unknown>>(afterSeq => ctx.input.api.get(`/api/heartbeat-runs/${run.id}/events?afterSeq=${afterSeq}&limit=1000`));
if (readSavedObservabilityStatus(events, ctx.input.fixtures.company.id)) return true;
}
return false;
}
export function gradeObservability(value: unknown) {
const c = checks(); const o = identityObservation(value); c.add("complete-opt-in-trace-evidence", !!o, "Real saved destination, actual collector deliveries, native runs and disabled-export evidence are required."); if (!o) return c.result();
const saved = o.state.saved as AgentObservabilitySettingsResponse | undefined; const receipt = o.state.testReceipt as AgentObservabilityTestReceipt | undefined;
c.add("off-until-human-opt-in", o.state.beforeSettings === null && o.state.afterReplySettings === null && o.state.beforeConfiguredCalls === 0 && o.state.agentWriteStatus === 403
&& saved?.settings?.enabled === true && saved.settings.destination.provider === "otlp" && saved.settings.destination.endpointBaseUrl === o.state.collectorUrl
&& saved.settings.headerNames.includes("authorization") && saved.settings.credentialsConfigured && o.state.publicSettingsContainsKey === false,
"The actual company has no export before the authorized human configures its synthetic collector and secure ingestion header; agent writes are denied and public readback contains no secret.");
c.add("actual-selected-delivery-test", receipt?.status === "accepted" && receipt.source === "control_plane" && receipt.revision === saved?.settings?.revision
&& ["logs", "traces"].every(signal => receipt.signals[signal as "logs" | "traces"].status === "accepted") && o.state.collectorMatchedTestSignals === 2,
"Both actual protobuf signal deliveries contain the exact control-plane test marker, company, revision and private ingestion authentication; a successful settings save is not delivery proof.");
c.add("real-coding-agent-export", o.state.nativeExportMatched === true && o.state.enabledNativeRunCount === 2 && o.runs.length === 3 && o.runs.every(run => run.status === "succeeded" && run.runtimeMode === "native"),
"An actual second native agent turn exports its company/agent/revision records to the selected synthetic collector; control-plane samples alone cannot prove coding-agent export.");
c.add("disabled-stops-future-export", o.state.disabledSaved === true && o.state.disabledNativeRunCount === 3 && o.state.callsAfterDisabledRun === o.state.callsAtDisable
&& o.state.disabledCallsDidNotIncrease === true,
"The explicit human Disable export control persists, then a third actual native turn completes without another collector delivery.");
// An acknowledgement is only truthful when the turn read the saved settings it acknowledges. The
// board-only settings are unreadable to agents; the status read is the agent's only source. The
// agent's wording is never matched: the redaction-safe receipt of a successful read in each
// acknowledgement turn is graded instead, so a reply built from agent config and secrets alone fails.
c.add("acknowledgements-read-saved-settings", o.state.enabledTurnReadSavedStatus === true && o.state.disabledTurnReadSavedStatus === true,
"Each acknowledgement turn (export saved and enabled, then disabled) successfully read the company's saved trace export status before replying.");
c.add("points-to-company-observability-setup", companySettingsLinked(o, o.state.companyPrefix),
"A reply renders a link to the company settings page, where the board configures the destination and enters its credential securely.");
// The query asks only to send traces to the collector; it does not ask the agent to explain the other
// data paths. Which paths the export covers is proven by the collector receipts above; free-form
// replies are not graded by keywords, so the reply is only required to exist.
c.add("data-paths-not-confused", !!o.reply.trim(),
"An actual answer exists; the trace-only export path is proven by the collector receipts, and the reply's wording is left to a human reader.");
return c.result();
}
export const observabilityIdentityCases: readonly ChatCatalogCase[] = [identityDefinition("companies.agent-observability", async ctx => {
const before = await ctx.input.api.get<AgentObservabilitySettingsResponse>(`/api/companies/${ctx.input.fixtures.company.id}/observability`);
if (!before.canManage || before.settings !== null || !ctx.input.privateSecrets) throw new Error("Setup blocker: the real human must manage an initially unconfigured trace destination");
const target = await collector(); collectors.set(ctx, target); ctx.input.privateSecrets.push(target.key);
return { beforeSettings: before.settings, collectorUrl: target.url, syntheticCollector: true, companyPrefix: ctx.input.fixtures.company.issuePrefix };
}, gradeObservability, {
authentication: "human-session", oracleVersion: "paperclip.chat-catalog.agent-observability.structural.v4", expectedRunCount: 3, expectedHumanMessageCount: 3, attemptTimeoutMs: 600_000,
sourceFiles: ["chat-catalog-domains/identity-observability.ts", "chat-catalog-domains/api-read-receipts.ts", "chat-catalog-domains/identity-company-observer.ts", "chat-catalog-domains/identity-private-browser.ts", "chat-catalog-domains/identity-private-browser-worker.ts", "chat-catalog-domains/identity-wizard.ts", "chat-catalog-domains/identity-support.ts", "chat-catalog-domains/internal-support.ts", "chat-scenarios/companies.yaml"],
async act(ctx, state) {
await waitForCompanySettingsTurn(ctx); const target = collectors.get(ctx); if (!target) throw new Error("Owned synthetic collector is missing");
const root = `/api/companies/${ctx.input.fixtures.company.id}/observability`; const source = ctx.input.page.url();
state.afterReplySettings = (await ctx.input.api.get<AgentObservabilitySettingsResponse>(root)).settings; state.beforeConfiguredCalls = target.received.length;
state.agentWriteStatus = await probeAgentPermission(ctx, root, "PUT", { expectedRevision: null, enabled: true, destination: { provider: "otlp", endpointBaseUrl: target.url }, credentials: { mode: "replace", headers: [] }, capture: { userPrompts: false, assistantResponses: false, toolDetails: false, toolContent: false } });
await ctx.input.page.goto(`/${ctx.input.fixtures.company.issuePrefix}/company/settings`, { waitUntil: "domcontentloaded" });
const section = ctx.input.page.locator('section[aria-labelledby="agent-observability-heading"]');
await privateIdentityBrowser({ kind: "observability", origin: ctx.input.api.baseURL, startPath: ctx.input.page.url(), cookies: await ctx.input.page.context().cookies(ctx.input.api.baseURL), endpoint: target.url, credential: `Bearer ${target.key}` });
await ctx.input.page.reload({ waitUntil: "domcontentloaded" });
await expect(section.getByRole("button", { name: "Test saved settings", exact: true })).toBeEnabled();
const saved = await ctx.input.api.get<AgentObservabilitySettingsResponse>(root); state.saved = saved; state.publicSettingsContainsKey = JSON.stringify(saved).includes(target.key);
const response = ctx.input.page.waitForResponse(row => row.request().method() === "POST" && new URL(row.url()).pathname === `${root}/test`);
await section.getByRole("button", { name: "Test saved settings", exact: true }).click(); const receipt = await (await response).json() as AgentObservabilityTestReceipt; state.testReceipt = receipt;
await expect(section.getByText("Test payload accepted", { exact: true })).toBeVisible();
state.collectorMatchedTestSignals = ["/v1/logs", "/v1/traces"].filter(signal => target.received.some(row => row.path === signal && row.authenticated && row.body.includes(receipt.marker)
&& row.body.includes(ctx.input.fixtures.company.id) && row.body.includes(receipt.revision))).length;
let priorRuns = new Set((await ctx.allRuns()).map(run => run.id));
await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" }); await sendChatMessage(ctx.input.page, "Please acknowledge that our test collector configuration is saved. Do not change its settings.");
await waitForCompanySettingsTurn(ctx, 2); state.enabledNativeRunCount = (await ctx.allRuns()).length;
state.enabledTurnReadSavedStatus = await turnReadSavedStatus(ctx, priorRuns);
state.nativeExportMatched = await pollUntil({ label: "actual native harness trace export", deadlineAt: Date.now() + 30_000,
load: async () => target.received.some(row => row.authenticated && row.body.includes(ctx.input.fixtures.company.id)
&& row.body.includes(ctx.input.fixtures.agent.id) && row.body.includes(receipt.revision)), accept: Boolean });
await ctx.input.page.goto(`/${ctx.input.fixtures.company.issuePrefix}/company/settings`, { waitUntil: "domcontentloaded" });
await section.getByRole("button", { name: "Disable export", exact: true }).click();
await expect.poll(async () => (await ctx.input.api.get<AgentObservabilitySettingsResponse>(root)).settings?.enabled).toBe(false); state.disabledSaved = true; state.callsAtDisable = target.received.length;
priorRuns = new Set((await ctx.allRuns()).map(run => run.id));
await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" }); await sendChatMessage(ctx.input.page, "Please acknowledge that export is now disabled. Do not change it or start any additional work.");
await waitForCompanySettingsTurn(ctx, 3); state.disabledNativeRunCount = (await ctx.allRuns()).length;
state.disabledTurnReadSavedStatus = await turnReadSavedStatus(ctx, priorRuns); state.callsAfterDisabledRun = target.received.length; state.disabledCallsDidNotIncrease = state.callsAfterDisabledRun === state.callsAtDisable;
await ctx.input.evidence("identity-synthetic-otlp-delivery.json", { syntheticCollector: true, savedRevision: receipt.revision, controlPlaneTestMarker: receipt.marker,
requests: target.received.map(row => ({ path: row.path, authenticated: row.authenticated, sha256: row.sha256 })), nativeExportMatched: state.nativeExportMatched,
enabledNativeRunCount: state.enabledNativeRunCount, disabledNativeRunCount: state.disabledNativeRunCount, callsAtDisable: state.callsAtDisable, callsAfterDisabledRun: state.callsAfterDisabledRun,
realVendorDeliveryClaimed: false, telemetryAndLocalRunLogsAreSeparate: true });
},
observe: observeIdentity,
async cleanup(ctx) { const target = collectors.get(ctx); if (target) { target.server.closeAllConnections(); await new Promise<void>((resolve, reject) => target.server.close(error => error ? reject(error) : resolve())); target.received.length = 0; } collectors.delete(ctx); },
})];