Files
PaperClipAI/server/src/__tests__/heartbeat-runtime-state.test.ts
T
DottaandPaperclip 4b6de5327e Remove cheap model profiles (#12683)
## Thinking Path

> - Paperclip manages agents that use different model providers and
adapters.
> - Paperclip must keep agent execution rules clear and predictable.
> - The cheap-model profile added a second execution mode across
adapters, task recovery, APIs, and the UI.
> - That mode increased configuration and recovery complexity.
> - This pull request removes the cheap-model profile as a product
feature.
> - The benefit is one model-selection path for normal work and recovery
work.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

This change simplifies model selection across agent configuration, task
execution, recovery, and adapter capabilities.

**Current behavior**

Paperclip exposes cheap-model profiles in adapter metadata, agent
runtime configuration, task overrides, recovery rules, APIs, and the
board UI. Recovery work can select a different model profile from the
agent's configured model.

**Proposed behavior**

Paperclip uses the agent's configured model for normal work and recovery
work. Status-only recovery stays limited to coordination work. The API
rejects legacy model-profile configuration. A migration removes stored
model-profile values from existing agent, issue, and historical revision
records.

**Reason and benefit**

One model path reduces configuration, API, UI, and recovery complexity.
It also prevents status recovery from becoming a separate product-level
model-routing feature.

**Breaking changes**

This change removes model-profile fields and adapter capability
metadata. Existing stored model-profile values are removed by an
idempotent migration. The validators reject new legacy profile values
with clear errors.

## What Changed

- Removed model-profile types, adapter capabilities, API fields, and
model selection logic.
- Removed cheap-model controls from agent and task UI surfaces.
- Kept status-only recovery limited to coordination context while normal
continuations use the configured agent model.
- Added an idempotent migration that removes stored model-profile values
from agents, issues, and configuration revisions without changing issue
update timestamps.
- Updated tests and product documentation for the single-model behavior.

## Verification

- `pnpm check:token-gates` passes.
- `pnpm -r typecheck` passes.
- `pnpm build` passes.
- `pnpm test:run` completed with 5,607 passing tests and 8
environment-sensitive failures in unrelated fixed-port and
database-deadlock suites. The same failures repeated in an isolated
rerun. CI is the final clean-room result.

## Risks

- This is an intentional breaking change for clients that send
model-profile fields.
- The migration changes legacy agent, issue, and configuration-revision
JSON. It is idempotent and preserves unrelated fields and issue update
timestamps.
- The change is cross-cutting because the removed feature existed in
adapters, shared contracts, the server, plugins, and the UI.

> 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 Codex with `gpt-5`. Reasoning and tool use were enabled. The
runtime did not expose the context-window size.

## 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)
- [ ] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [ ] 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-09-01 14:57:38 -05:00

281 lines
8.3 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { eq } from "drizzle-orm";
import {
agents,
agentRuntimeState,
agentWakeupRequests,
companies,
createDb,
heartbeatRunEvents,
heartbeatRuns,
} from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { subscribeCompanyLiveEvents } from "../services/live-events.ts";
import {
clearAllHeartbeatRunRuntimeStatuses,
getHeartbeatRunRuntimeStatus,
} from "../services/heartbeat-run-runtime-status.ts";
vi.doMock("../adapters/index.js", () => ({
getServerAdapter: vi.fn(() => ({
type: "process",
execute: vi.fn(),
testEnvironment: vi.fn(),
})),
runningProcesses: new Map(),
}));
const { heartbeatService } = await import("../services/heartbeat.ts");
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
if (!embeddedPostgresSupport.supported) {
console.warn(
`Skipping embedded Postgres heartbeat runtime-state tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
);
}
describeEmbeddedPostgres("heartbeat runtime state deduplication", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("heartbeat-runtime-state-");
db = createDb(tempDb.connectionString);
}, 20_000);
afterEach(async () => {
clearAllHeartbeatRunRuntimeStatuses();
await db.delete(heartbeatRunEvents);
await db.delete(heartbeatRuns);
await db.delete(agentWakeupRequests);
await db.delete(agentRuntimeState);
await db.delete(agents);
await db.delete(companies);
});
afterAll(async () => {
await tempDb?.cleanup();
});
it("deduplicates concurrent runtime-state creation", async () => {
const companyId = randomUUID();
const agentId = randomUUID();
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
await db.insert(companies).values({
id: companyId,
name: "Paperclip",
issuePrefix,
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values({
id: agentId,
companyId,
name: "CodexCoder",
role: "engineer",
status: "idle",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
});
const heartbeat = heartbeatService(db);
const results = await Promise.all(Array.from({ length: 12 }, () => heartbeat.getRuntimeState(agentId)));
expect(results.every((row) => row?.agentId === agentId)).toBe(true);
const rows = await db.select().from(agentRuntimeState).where(eq(agentRuntimeState.agentId, agentId));
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({
agentId,
companyId,
adapterType: "codex_local",
stateJson: {},
});
});
it("publishes runtime progress without persisting heartbeat run events", async () => {
const companyId = randomUUID();
const agentId = randomUUID();
const runId = randomUUID();
const issueId = randomUUID();
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
await db.insert(companies).values({
id: companyId,
name: "Paperclip",
issuePrefix,
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values({
id: agentId,
companyId,
name: "CodexCoder",
role: "engineer",
status: "running",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
});
const [insertedRun] = await db.insert(heartbeatRuns).values({
id: runId,
companyId,
agentId,
invocationSource: "assignment",
status: "running",
contextSnapshot: { issueId },
}).returning();
const run = insertedRun!;
const liveEvents: unknown[] = [];
const unsubscribe = subscribeCompanyLiveEvents(companyId, (event) => {
liveEvents.push(event);
});
try {
const heartbeat = heartbeatService(db);
const status = await heartbeat.recordRuntimeProgress(run, {
phase: "config_sync",
message: "Syncing workspace to environment",
currentToolName: "bash",
lastAssistantSnippet: "Inspecting the repository",
lastEventAt: "2026-06-24T00:00:05.000Z",
}, issueId);
expect(status).toMatchObject({
companyId,
issueId,
agentId,
runId,
phase: "config_sync",
message: "Syncing workspace to environment",
currentToolName: "bash",
lastAssistantSnippet: "Inspecting the repository",
lastEventAt: new Date("2026-06-24T00:00:05.000Z"),
});
expect(heartbeat.decorateActiveRunStatus({
id: runId,
companyId,
agentId,
issueId,
status: "running",
})).toMatchObject({
currentStatusMessage: "Syncing workspace to environment",
currentToolName: "bash",
lastAssistantSnippet: "Inspecting the repository",
lastEventAt: new Date("2026-06-24T00:00:05.000Z"),
});
expect(liveEvents).toContainEqual(expect.objectContaining({
companyId,
type: "heartbeat.run.progress",
payload: expect.objectContaining({
runId,
agentId,
issueId,
phase: "config_sync",
message: "Syncing workspace to environment",
currentToolName: "bash",
lastAssistantSnippet: "Inspecting the repository",
lastEventAt: "2026-06-24T00:00:05.000Z",
}),
}));
const persistedEvents = await db.select().from(heartbeatRunEvents);
expect(persistedEvents).toHaveLength(0);
await heartbeat.cancelRun(runId, "test cleanup");
expect(getHeartbeatRunRuntimeStatus(runId)).toBeNull();
} finally {
unsubscribe();
}
});
it("ignores late runtime progress after the persisted run is terminal", async () => {
const companyId = randomUUID();
const agentId = randomUUID();
const runId = randomUUID();
const issueId = randomUUID();
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
await db.insert(companies).values({
id: companyId,
name: "Paperclip",
issuePrefix,
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values({
id: agentId,
companyId,
name: "CodexCoder",
role: "engineer",
status: "running",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
});
const [insertedRun] = await db.insert(heartbeatRuns).values({
id: runId,
companyId,
agentId,
invocationSource: "assignment",
status: "running",
contextSnapshot: { issueId },
}).returning();
const staleRunningRun = insertedRun!;
const liveEvents: unknown[] = [];
const unsubscribe = subscribeCompanyLiveEvents(companyId, (event) => {
liveEvents.push(event);
});
try {
const heartbeat = heartbeatService(db);
await heartbeat.recordRuntimeProgress(staleRunningRun, {
phase: "config_sync",
message: "Syncing workspace to environment",
}, issueId);
expect(getHeartbeatRunRuntimeStatus(runId)).toMatchObject({
runId,
phase: "config_sync",
});
liveEvents.length = 0;
await db
.update(heartbeatRuns)
.set({
status: "succeeded",
finishedAt: new Date("2026-06-24T00:01:00.000Z"),
updatedAt: new Date("2026-06-24T00:01:00.000Z"),
})
.where(eq(heartbeatRuns.id, runId));
const lateStatus = await heartbeat.recordRuntimeProgress(staleRunningRun, {
phase: "finalize",
message: "Finalizing workspace",
}, issueId);
expect(lateStatus).toBeNull();
expect(getHeartbeatRunRuntimeStatus(runId)).toBeNull();
expect(liveEvents).not.toContainEqual(expect.objectContaining({
type: "heartbeat.run.progress",
}));
expect(await db.select().from(heartbeatRunEvents)).toHaveLength(0);
} finally {
unsubscribe();
}
});
});