Files
PaperClipAI/server/src/services/heartbeat/task-markdown.test.ts
T
DottaandClaude Opus 5.5 601babe322 fix(chat): let agents read saved trace export status and give chat real company page paths (#20998)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - People talk to their agents in chat, and agents answer from the
company's saved settings
> - A board member can save a company trace export (an OTLP collector or
Braintrust) in Company settings
> - The settings route is for board connection managers only, so an
agent cannot read it
> - In a chat eval, the board saved and tested a collector. The agent
checked only its own config and secrets, and then told the person that
nothing was configured
> - Chat guidance also names company pages as `/<prefix>/...`. In
another eval, the agent copied that placeholder into a link, and the
link opened nothing
> - This pull request gives agents a read-only status of the trace
export, and gives chat the real company prefix in page paths
> - The benefit is that agents answer from saved settings, and the links
they write open real pages

## Linked Issues or Issue Description

**What happened?**
1. A board member saved and tested a trace export destination. The chat
agent was asked to acknowledge the saved configuration. The agent said
that no collector endpoint or credentials existed. Agents get 403 from
`GET /api/companies/{companyId}/observability`, and no other route
reports the saved state.
2. An agent reply linked `/<prefix>/company/settings/instance`. The chat
rendered it as `/%3Cprefix%3E/...`, which is not a real page. The
placeholder came from the chat directive, which names pages such as
`/<prefix>/company/settings/instance/profile`.

**Expected behavior**
1. An agent can read whether the company's trace export is configured,
enabled and credentialed, and the result of its latest test. The agent
cannot read the destination or any credential.
2. The chat directive and API search results that an agent reads give
real company paths, such as `/COM/company/settings/instance/profile`.

**Steps to reproduce**
1. As a board member, save and test an agent observability destination
in Company settings.
2. In chat, ask the CEO agent to acknowledge that the test collector
configuration is saved.
3. See that the agent cannot read the saved settings and denies them.

**Paperclip version or commit**
master at 9dfdeaad86.

## What Changed

- Added `GET /api/companies/{companyId}/observability/status`. Agents of
the company and all members can read it. It returns `configured`,
`enabled`, `provider`, `credentialsConfigured`, `updatedAt` and the
latest test status. It never returns the destination or a credential.
- Added the shared `AgentObservabilityStatus` type and
`agentObservabilityStatus()` mapper, and registered the route in the
OpenAPI catalog so that `search_api` finds it.
- The chat task markdown now fills the conversation's own company prefix
(from its identifier, for example `COM-1` gives `COM`) into the chat
directives in place of `/<prefix>/`.
- `search_api` results now get the same substitution for the caller's
company. The shared catalog is not changed.
- Pinned the changed shared source in
`tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `cd server && npx vitest run src/__tests__/agent-observability.test.ts
src/__tests__/agent-observability-status-guidance.test.ts
src/services/heartbeat/task-markdown.test.ts
src/__tests__/openapi-routes.test.ts
src/services/native-runtime/paperclip-runner-tool-authority.test.ts`
- Red/green: with the product change removed, 10 of the new or updated
tests fail (the agent status read gets 403, search does not find the
route, and the chat markdown still contains `/<prefix>/`). With the
change, all pass.
- `npx tsc -p server/tsconfig.json --noEmit` passes.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check`
reports no change.

## Risks

- Low risk. The new route is read-only and returns no destination and no
credential. The existing settings route keeps its board-only rule.
- The chat prompt text changes for chats with an identifier. The text is
constant for each company, so prompt caching is not affected inside a
conversation.

## 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:55:21 -06:00

231 lines
13 KiB
TypeScript

import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { buildPaperclipTaskMarkdown } from "./task-markdown.js";
const issue = {
id: "task-1",
identifier: "TEST-1",
title: "Inspect the evidence",
};
describe("heartbeat task markdown rendering", () => {
it.each([true, false])("keeps native task clarification in the current task on full and resumed assignments (description=%s)", (includeDescription) => {
const markdown = buildPaperclipTaskMarkdown({
issue: { ...issue, description: "Write a blog post about our launch." },
nativeRunner: true,
includeDescription,
});
expect(markdown).toContain("Task clarification directive:");
expect(markdown).toContain("Inspect the available task description, plan, conversation, prior answers, and relevant references before asking");
expect(markdown).toContain("ask one focused question at a time in this task");
expect(markdown).toContain('interactionKind: "questions", payload.questions');
expect(markdown).toContain('resolverPolicy: "human_only", continuationPolicy: "wake_assignee"');
expect(markdown).toContain("stable idempotencyKey");
expect(markdown).toContain("do not send the user to a separate chat or create a replacement task");
expect(markdown).toContain("Reuse an existing relevant pending question");
expect(markdown).toContain("an unanswered question is not consent");
expect(markdown).toContain("A human-dismissed request is deferred to history");
expect(markdown).toContain("Do not invent material user intent or success criteria");
});
it("preserves execution of a clear accepted plan without imposing clarification", () => {
const markdown = buildPaperclipTaskMarkdown({
issue: { ...issue, workMode: "planning" },
nativeRunner: true,
acceptedPlanContinuation: true,
taskPlan: { documentId: "plan", revisionId: "revision", revisionNumber: 1, body: "Write a 300-word launch post for customers using the supplied brief." },
});
expect(markdown).toContain("If the outcome and success criteria are clear enough to act, proceed without a setup checklist or ritual questions");
expect(markdown).toContain("When a missing decision materially changes the outcome");
expect(markdown).toContain("Implement the accepted plan on this issue");
expect(markdown).toContain("Write a 300-word launch post for customers using the supplied brief.");
});
it.each([
{ nativeRunner: false, coordinatorWorkspace: true, conversationAgentId: null },
{ nativeRunner: undefined, coordinatorWorkspace: false, conversationAgentId: null },
{ nativeRunner: true, coordinatorWorkspace: false, conversationAgentId: "coordinator" },
{ nativeRunner: true, coordinatorWorkspace: true, conversationAgentId: "coordinator" },
])("does not add native task clarification to adapter or standing-chat assignments: %j", ({ conversationAgentId, ...input }) => {
expect(buildPaperclipTaskMarkdown({ issue: { ...issue, conversationAgentId }, ...input }))
.not.toContain("Task clarification directive:");
});
it("tells a chat agent the person's time zone only when it is known", () => {
const chat = { id: "chat", identifier: null, title: "Chat", conversationAgentId: "coordinator" };
const line = "The person's time zone is America/Chicago (from their browser). Read times and dates they give";
expect(buildPaperclipTaskMarkdown({ issue: chat, personTimeZone: "America/Chicago" })).toContain(line);
expect(buildPaperclipTaskMarkdown({ issue: chat, personTimeZone: "America/Chicago" })).toContain("save schedules such as routine triggers with that timezone; say the zone when you report a schedule.");
expect(buildPaperclipTaskMarkdown({ issue: chat, personTimeZone: null })).not.toContain("The person's time zone is");
expect(buildPaperclipTaskMarkdown({ issue: chat })).not.toContain("The person's time zone is");
expect(buildPaperclipTaskMarkdown({ issue, personTimeZone: "America/Chicago" })).not.toContain("The person's time zone is");
});
it("shows inferred task proposals only for opted-in native conversations while preserving explicit creation", () => {
const issue = { id: "chat", identifier: null, title: "Chat", conversationAgentId: "coordinator" };
const classic = buildPaperclipTaskMarkdown({ issue, nativeRunner: true });
expect(classic).not.toContain("Coordinator task proposals:");
const optedIn = buildPaperclipTaskMarkdown({ issue, nativeRunner: true, coordinatorWorkspace: true });
expect(optedIn).toContain('interactionKind: "suggest_tasks"');
expect(optedIn).toContain("acceptance creates the task atomically");
expect(optedIn).toContain("If the user explicitly authorized task creation, use create_task directly");
expect(buildPaperclipTaskMarkdown({ issue, nativeRunner: false, coordinatorWorkspace: true }))
.not.toContain("Coordinator task proposals:");
});
it("gives a standing chat real company page paths instead of a /<prefix>/ placeholder it could copy into a link", () => {
const chat = { id: "chat", identifier: "COM-12", title: "Chat", conversationAgentId: "ceo" };
const markdown = buildPaperclipTaskMarkdown({ issue: chat, nativeRunner: true, conferenceRoomEnabled: true, statusCardsEnabled: true, casesEnabled: true, coordinatorWorkspace: true })!;
expect(markdown).not.toContain("/<prefix>/");
expect(markdown).toContain("profile settings at /COM/company/settings/instance/profile");
expect(markdown).toContain("/COM/issues/<identifier>");
// Without an identifier the prefix is unknown, so the documented placeholder stays.
expect(buildPaperclipTaskMarkdown({ issue: { ...chat, identifier: null } })).toContain("/<prefix>/issues/<identifier>");
});
it("tells a standing chat about the Conference Room only while the experiment is enabled", () => {
const chat = { id: "chat", identifier: "RUN-1", title: "Chat", conversationAgentId: "ceo" };
const enabled = buildPaperclipTaskMarkdown({ issue: chat, nativeRunner: true, conferenceRoomEnabled: true });
expect(enabled).toContain("Conference Room:");
expect(enabled).toContain("[Open the Conference Room](/RUN/board-chat)");
expect(enabled).toContain("does not carry over this conversation's history");
expect(buildPaperclipTaskMarkdown({ issue: chat, nativeRunner: true })).not.toContain("board-chat");
expect(buildPaperclipTaskMarkdown({ issue: { ...chat, conversationAgentId: null }, nativeRunner: true, conferenceRoomEnabled: true }))
.not.toContain("board-chat");
});
it("tells a standing chat what a status card is, how to create and refresh one, and to reply now with its link, only while the experiment is enabled", () => {
const chat = { id: "chat", identifier: "RUN-1", title: "Chat", conversationAgentId: "ceo" };
const enabled = buildPaperclipTaskMarkdown({ issue: chat, nativeRunner: true, statusCardsEnabled: true })!;
expect(enabled).toContain("Status Cards:");
expect(enabled).toContain("A status card is a saved Paperclip feature, not a document or comment");
expect(enabled).toContain("POST /api/companies/{companyId}/status-cards");
expect(enabled).toContain("POST /api/status-cards/{id}/refresh");
expect(enabled).toContain("Do not sleep or poll the card. Report the outcome the response gives");
expect(enabled).toContain("enqueued false otherwise means no run started, so say why from card.state");
expect(enabled).toContain("[Launch blockers](/RUN/status/<cardId>)");
// The named pages are the board's real routes.
const app = readFileSync(new URL("../../../../ui/src/App.tsx", import.meta.url), "utf8");
expect(enabled).toContain("Status page at /RUN/status (");
expect(app).toMatch(/path="status"\s+element=\{<StatusCardsExperimentalGate>/);
expect(app).toMatch(/path="status\/:cardId"\s+element=\{<StatusCardsExperimentalGate>/);
expect(buildPaperclipTaskMarkdown({ issue: chat, nativeRunner: true })).not.toContain("Status Cards:");
expect(buildPaperclipTaskMarkdown({ issue: { ...chat, conversationAgentId: null }, nativeRunner: true, statusCardsEnabled: true }))
.not.toContain("Status Cards:");
});
it("tells a standing chat to link a case's page by its identifier, only while the Cases experiment is enabled", () => {
const chat = { id: "chat", identifier: "RUN-1", title: "Chat", conversationAgentId: "ceo" };
const enabled = buildPaperclipTaskMarkdown({ issue: chat, nativeRunner: true, casesEnabled: true })!;
expect(enabled).toContain("Cases:");
expect(enabled).toContain("/RUN/cases/<case identifier>");
expect(enabled).toContain("[RUN-C1](/RUN/cases/RUN-C1)");
// The named page is the board's real route.
const app = readFileSync(new URL("../../../../ui/src/App.tsx", import.meta.url), "utf8");
expect(app).toMatch(/path="cases\/:caseIdentifier"/);
expect(buildPaperclipTaskMarkdown({ issue: chat, nativeRunner: true })).not.toContain("Cases:");
expect(buildPaperclipTaskMarkdown({ issue: { ...chat, conversationAgentId: null }, nativeRunner: true, casesEnabled: true }))
.not.toContain("Cases:");
});
it("returns null without a task or a nonempty wake comment", () => {
expect(buildPaperclipTaskMarkdown({ issue: null })).toBeNull();
expect(buildPaperclipTaskMarkdown({
issue: null,
wakeComments: [{ id: "empty", body: " \n " }],
})).toBeNull();
});
it("renders comment-only context in order without changing the input", () => {
const input = {
issue: null,
wakeComments: [
Object.freeze({ id: "first", body: " First request. " }),
Object.freeze({ id: "empty", body: " " }),
Object.freeze({ id: "last", body: "\nLatest request.\n" }),
],
};
const before = structuredClone(input);
const markdown = buildPaperclipTaskMarkdown(input)!;
expect(markdown).toContain("Pending wake comments (oldest to newest):");
expect(markdown.indexOf('("first")')).toBeLessThan(markdown.indexOf('("last")'));
expect(markdown).toContain("\nFirst request.\n");
expect(markdown).toContain("\nLatest request.\n");
expect(markdown).not.toContain('("empty")');
expect(input).toEqual(before);
expect(buildPaperclipTaskMarkdown(input)).toBe(markdown);
});
it("quotes task scalars and keeps embedded code fences inside the description", () => {
const description = "First line.\n````text\nQuoted instruction.\n````\nLast line.";
const title = 'A "quoted" title\nwith a second line';
const markdown = buildPaperclipTaskMarkdown({
issue: { ...issue, title, description },
});
expect(markdown).toContain(`- Title: ${JSON.stringify(title)}`);
expect(markdown).toContain(`Issue description:\n\`\`\`\`\`text\n${description}\n\`\`\`\`\``);
});
it("keeps the nearest six ancestors and reports omitted ancestor context", () => {
const markdown = buildPaperclipTaskMarkdown({
issue,
ancestors: Array.from({ length: 7 }, (_, index) => ({
id: `ancestor-${index + 1}`,
title: `Ancestor title ${index + 1}`,
})),
});
expect(markdown).toContain("- Parent: ancestor-1 Ancestor title 1");
expect(markdown).toContain("- Ancestor 6: ancestor-6 Ancestor title 6");
expect(markdown).not.toContain("ancestor-7");
expect(markdown).toContain("[ancestor context truncated after 6 entries]");
});
it.each([true, false])("retains attachment-only wakes with hidden comment bodies (native=%s)", (nativeRunner) => {
const contentPath = "/api/attachments/attachment-1/content";
const markdown = buildPaperclipTaskMarkdown({
issue: null,
nativeRunner,
includeWakeComments: false,
wakeComments: [{
id: "comment-file",
body: " ",
attachments: [{
id: "attachment-1",
filename: "evidence.txt",
contentType: "text/plain",
byteSize: 42,
contentPath,
}],
}],
});
expect(markdown).toContain('Attachments on wake comment "comment-file":');
expect(markdown).toContain('"filename":"evidence.txt"');
expect(markdown).toContain("Attachment directive:");
if (nativeRunner) {
expect(markdown).not.toContain(contentPath);
expect(markdown).toContain("read_task_attachment");
} else {
expect(markdown).toContain(contentPath);
expect(markdown).toContain("PAPERCLIP_API_KEY");
}
});
it("keeps a rejected plan from granting execution through an older acceptance", () => {
const markdown = buildPaperclipTaskMarkdown({
issue: { ...issue, workMode: "planning" },
acceptedPlanContinuation: true,
interaction: { kind: "request_confirmation", status: "accepted" },
acceptedPlan: { revisionId: "old-approved-revision", revisionNumber: 1 },
planReview: { status: "rejected", reason: "Revise the scope.\n```\nQuoted feedback.\n```" },
});
expect(markdown).toContain("Rejected plan review directive:");
expect(markdown).toContain("Make the plan only. Do not write code or perform implementation work.");
expect(markdown).toContain("This is not approval to implement or hand off execution tasks.");
expect(markdown).toContain("````text\nRevise the scope.");
expect(markdown).not.toContain("Implement the accepted plan");
expect(markdown).not.toContain("old-approved-revision");
});
});