Files
PaperClipAI/server/src/services/heartbeat/task-markdown.test.ts
T
DottaandPaperclip 51653becc2 refactor(server): extract heartbeat task markdown rendering (#15568)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Heartbeat orchestration supplies each run with task context.
> - The task Markdown renderer is inside a service with more than 31,000
lines.
> - The renderer formats task data and does not write run state.
> - It is a small first step toward a more manageable heartbeat service.
> - This PR moves the renderer without changing its function body or
public export.
> - Direct tests and existing caller tests check the output before and
after the move.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

This improves the structure and test coverage of heartbeat task context
rendering.

**Subsystem affected**

server/ — orchestration services.

**Current behavior**

`buildPaperclipTaskMarkdown` occupies 352 lines inside `heartbeat.ts`.
The service also owns run execution, scheduling, recovery, and
cancellation.

**Proposed behavior**

Move the renderer to `heartbeat/task-markdown.ts`.
Keep its function body and the existing `heartbeat.ts` export unchanged.
Leave orchestration in place for this first PR.

**Reason and benefit**

Prompt formatting has its own small source file and direct regression
tests.
Reviewers can check this one extraction before a later refactor.

**Breaking changes**

None. The input type, rendered output, and existing import path stay the
same.

Related renderer changes: Refs: #4732, Refs: #14030.
These PRs change prompt behavior. This PR only moves the current
renderer.

## What Changed

- Move the 352-line renderer to
`server/src/services/heartbeat/task-markdown.ts`.
- Import and re-export it from `heartbeat.ts`. Remove imports used only
by the renderer.
- Add seven direct regression cases. Cover empty context, ordered
comment-only wakes, input preservation, nested code fences, ancestor
limits, attachment-only wakes, and rejected plans.
- Keep the renderer and its direct tests in
`server/src/services/heartbeat/`. Document this folder as the home for
relevant later extractions in `doc/DEVELOPING.md`.

## Verification

- The focused suite passed before and after extraction, and after moving
to the heartbeat folder: four files, 85 tests.
- Run `pnpm exec vitest run
server/src/services/heartbeat/task-markdown.test.ts
server/src/__tests__/heartbeat-context-summary.test.ts
server/src/__tests__/heartbeat-chat-task-link.test.ts
server/src/__tests__/codex-local-execute.test.ts`.
- The extracted function matches the original function byte for byte.
The folder move only adjusts imports.
- `node scripts/check-module-boundaries.mjs` passed.
- `git diff --check` passed.
- The initial extraction passed local `pnpm -r typecheck` and `pnpm
build`.
- The folder update passed `pnpm --filter @paperclipai/server exec tsc
--noEmit` and `pnpm --filter @paperclipai/server build`.
- The initial extraction passed the full CI suite. Its duplicate local
`pnpm test:run` was stopped after CI passed; it did not complete
locally.
- The folder update passed all CI gates on commit
`e21e589b379d7ca2fae16c1dcd91cf2f604fd03f`: 54 passing checks, two
skipped Storybook checks. Three test shards passed after one retry
following simultaneous runner shutdowns; those failures had no failed
test assertions.
- Fresh Greptile review of commit
`e21e589b379d7ca2fae16c1dcd91cf2f604fd03f`: 5/5, no actionable or inline
findings.

## Risks

- Low risk. A moved module can change import resolution or expose an
import cycle.
- Existing caller tests still load the compatibility export from
`heartbeat.ts`.
- The same guidance constants and public task URL resolver remain in
use.
- No run-state writes, transactions, locks, shared process state, or
cleanup paths moved.
- No database, API, telemetry, or UI contracts changed.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

OpenAI GPT-6 via Codex. The exact serving model ID and context window
were not exposed in this session. Used reasoning, repository inspection,
shell tools, and code execution.

## 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-08 09:06:04 -05:00

114 lines
4.4 KiB
TypeScript

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("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");
});
});