Files
PaperClipAI/server/src/__tests__/issue-display-status.test.ts
T
DottaandClaude Opus 5.5 397f163c7f fix(issues): show tasks held by a resolved no-replay hold as Blocked (#22215)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for work
> - Agents can schedule a follow-up check (a monitor) on a task. The task then shows as "Monitoring" until the check is due.
> - A failed run can leave a recovery record that blocks replay of its work. The record can have the status `resolved` and still block, because its evidence keeps `automaticRecovery.replay = "blocked"`.
> - Wake admission treats that record as a hold. It refuses every wake for the task, including the due monitor check, and records the skip with `execution_reconciliation_required`.
> - The task display status counts only `active` and `escalated` recovery records. Thus the task shows "Monitoring" with an overdue check, not "Blocked". The board does not see that a person must act. Agents re-arm the check, and the check stays overdue for days.
> - This pull request makes the display status show these held tasks as "Blocked". It uses the part of the wake-admission hold predicate that is always effective and cheap to query.
> - The benefit is that a task whose wakes are held shows as "Blocked" in the list, in search, in counts and in summaries, and the person who must act can find it.

## Linked Issues or Issue Description

(B) No issue exists. Bug report:

**What happened?**
Scheduled follow-up checks on agent tasks stayed overdue for many days. Each due check was skipped with the reason `execution_reconciliation_required`. One skip record had more than 25,000 merged attempts. The tasks did not show as "Blocked". They showed as "Monitoring" (or as in progress) with an overdue check. Agents re-armed the check, but the check never started.

**What did you expect to happen?**
When wake admission holds a task, the task shows as "Blocked", so a person can see it and use the recovery controls.

**Steps to reproduce**
1. Give an agent an `in_progress` task with a monitor.
2. Add a recovery record for the task with status `resolved`, a reconciliation cause (for example `provider_failure_meaning_unverified`) and evidence `automaticRecovery.replay = "blocked"`.
3. Read the task. `getExecutionBlocker` returns the hold and wake admission refuses the monitor wake.
4. See that `displayStatus` is `monitoring`, not `blocked`.

**Paperclip version or commit**
`master` at 8282d386da.

Related open PRs: #14590 and #14156 change how no-replay holds are released. This PR does not change hold release. It only makes the held task visible.

## What Changed

- `server/src/services/issue-display-status.ts`: An agent task with lifecycle status `in_progress` now shows `blocked` when it has a recovery record with these properties:
  - The cause is a reconciliation cause other than `legacy_execution_requires_reconciliation`.
  - The evidence has `automaticRecovery.replay = "blocked"`.
  - The evidence does not have the legacy workspace-restore schema.
  - The task is not a conversation.
- For these records, `executionBlockerPredicate` is always true and `restoreHoldReleasedForCurrentOwnerPredicate` is always false. Thus "Blocked" never shows for a task that wake admission would wake. The exceptions of the full predicate apply only to legacy holds, legacy workspace-restore holds and conversation boundaries. Those keep their current display.
- The full admission predicate is not used in the projection. I tried it first, and list queries became 3 to 4 times slower, because every list, search and count query includes this projection.
- `server/src/__tests__/issue-display-status.test.ts`: New regression test. It also checks that `getExecutionBlocker` agrees with the display status before and after the hold allows replay.

## Verification

- Failing before the fix: `pnpm --dir server exec vitest run src/__tests__/issue-display-status.test.ts`. The new test "shows an overdue monitor behind a resolved no-replay execution hold as Blocked, not Monitoring" failed with `AssertionError: expected 'monitoring' to be 'blocked'`.
- Passing after the fix: the same command. 21 of 21 tests pass.
- Affected suites: `vitest run` on `issue-display-status`, `issue-summaries-routes`, `blocked-inbox-review-wait-scope`, `company-search-service`, `issues-service`, `issue-list-assignee-filter-routes`, `status-cards` and `heartbeat-issue-liveness-escalation`. 8 files, 361 tests pass.
- List cost: a local probe (40 `issueService.list` calls) measured about the same time per call as `master`.
- Typecheck: `pnpm --dir server typecheck` (all layers) passes.
- Not run locally: the full `pnpm verify` selection (2,923 files). CI runs it.

## Risks

- Behavior change: more agent tasks can show as "Blocked". This occurs only when wake admission already refuses their wakes. The task lifecycle status, locks and recovery records do not change. This change does not write data.
- Query cost: the display status adds one small `EXISTS` subquery on `issue_recovery_actions` by company and source task. It runs only for agent tasks that are `in_progress` with no queued or running run and no active recovery record.
- Coverage: tasks held by a resolved legacy reconciliation hold, or by a legacy workspace-restore hold, still show their current status. Their release rules need run-level checks that are too costly for this projection.
- `in_review` and other lifecycle statuses keep their current display.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), with tool use (shell, file edit, test runs).

## 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
- [ ] 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-18 15:27:05 -06:00

212 lines
17 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { eq, sql } from "drizzle-orm";
import { expect, it } from "vitest";
import request from "supertest";
import { agents, heartbeatRuns, issueComments, issueRecoveryActions, issueRelations, issueThreadInteractions, issues, statusCards } from "@paperclipai/db";
import { companySearchQuerySchema, createIssueSchema, defaultStatusCardRefreshPolicy, PROVIDER_QUOTA_MONITOR_SERVICE_NAME, type Issue } from "@paperclipai/shared";
import { issueDisplayStatusSql } from "../services/issue-display-status.js";
import { getExecutionBlocker } from "../services/execution-blocker.js";
import { issueService } from "../services/issues.js";
import { companySearchService } from "../services/company-search.js";
import { statusCardService } from "../services/status-cards.js";
import { issueRoutes } from "../routes/issues.js";
import {
describeEmbeddedPostgres, routeApp,
seedCompanyWithBoardAccess, useEmbeddedPostgres,
} from "./helpers/route-test-harness.js";
describeEmbeddedPostgres("Execution-backed task presentation", () => {
const ctx = useEmbeddedPostgres("paperclip-monitoring-status-", {
resetEach: async (db) => { await db.execute(sql`SET client_min_messages = warning`); await db.execute(sql`TRUNCATE TABLE companies CASCADE`); },
});
async function fixture() {
const company = await seedCompanyWithBoardAccess(ctx.db, "Monitoring");
const agentId = randomUUID();
await ctx.db.insert(agents).values({ id: agentId, companyId: company.companyId, name: "Monitor owner", role: "engineer", status: "paused", adapterType: "process", adapterConfig: {} });
const nextCheckAt = new Date(Date.now() + 60 * 60_000);
const issueId = randomUUID();
await ctx.db.insert(issues).values({
id: issueId, companyId: company.companyId, title: "Check deployment", status: "in_progress",
assigneeAgentId: agentId, createdByUserId: company.actor.userId,
monitorNextCheckAt: nextCheckAt,
executionPolicy: { mode: "normal", stages: [], commentRequired: false, monitor: { nextCheckAt: nextCheckAt.toISOString(), notes: "Check deployment" } },
});
return { ...company, agentId, issueId };
}
async function displayStatus(id: string) {
const [row] = await ctx.db.select({ status: issues.status, displayStatus: issueDisplayStatusSql() }).from(issues).where(eq(issues.id, id));
return row;
}
it.each(["failed", "cancelled", "timed_out", "succeeded", "scheduled_retry"])("does not show In Progress after a run becomes %s, even with stale locks", async (status) => {
const f = await fixture();
await ctx.db.update(issues).set({ monitorNextCheckAt: null, executionPolicy: null }).where(eq(issues.id, f.issueId));
const [run] = await ctx.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, issueId: f.issueId, status }).returning();
await ctx.db.update(issues).set({ executionRunId: run!.id, checkoutRunId: run!.id }).where(eq(issues.id, f.issueId));
expect(await displayStatus(f.issueId)).toEqual({ status: "in_progress", displayStatus: "todo" });
const svc = issueService(ctx.db);
expect(await svc.count(f.companyId, { displayStatus: "in_progress" })).toBe(0);
expect(await svc.list(f.companyId, { displayStatus: "todo", limit: 1 })).toEqual([expect.objectContaining({ id: f.issueId })]);
// Presentation must not clear ownership or change recovery/admission inputs.
expect((await ctx.db.select().from(issues).where(eq(issues.id, f.issueId)))[0]).toMatchObject({ status: "in_progress", executionRunId: run!.id, checkoutRunId: run!.id });
});
it("shows a stopped task waiting for a human as In Review across API reads and search", async () => {
const f = await fixture();
await ctx.db.update(issues).set({ monitorNextCheckAt: null, executionPolicy: null }).where(eq(issues.id, f.issueId));
await ctx.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, issueId: f.issueId, status: "failed", errorCode: "authentication_failed" });
const [interaction] = await ctx.db.insert(issueThreadInteractions).values({ companyId: f.companyId, issueId: f.issueId, kind: "request_confirmation", addresseeUserId: f.actor.userId,
payload: { version: 1, prompt: "Authorize the connection" } }).returning();
const app = routeApp(ctx.db, f.actor, issueRoutes);
expect((await request(app).get(`/api/issues/${f.issueId}`).expect(200)).body).toMatchObject({ status: "in_progress", displayStatus: "in_review" });
const summary = await request(app).get(`/api/companies/${f.companyId}/issues/summaries?ids=${f.issueId}`).expect(200);
expect(summary.body[0]).toMatchObject({ displayStatus: "in_review" });
const result = await companySearchService(ctx.db).search(f.companyId, companySearchQuerySchema.parse({ q: "deployment", displayStatus: "in_review" }));
expect(result.results[0]?.issue).toMatchObject({ id: f.issueId, displayStatus: "in_review" });
await ctx.db.update(issueThreadInteractions).set({ status: "answered" }).where(eq(issueThreadInteractions.id, interaction!.id));
expect((await displayStatus(f.issueId)).displayStatus).toBe("todo");
});
it.each(["dismissed", "historical"])("does not turn a monitor into review for a %s request", async (kind) => {
const f = await fixture();
const createdAt = new Date(Date.now() - 60_000);
await ctx.db.insert(issueThreadInteractions).values({ companyId: f.companyId, issueId: f.issueId,
kind: kind === "dismissed" ? "request_confirmation" : "ask_user_questions", status: "pending", createdAt,
dismissedAt: kind === "dismissed" ? new Date() : null, effectiveResolverPolicySource: "requested",
payload: { version: 1, prompt: "Earlier request" } });
if (kind === "historical") await ctx.db.insert(issueComments).values({ companyId: f.companyId, issueId: f.issueId,
authorUserId: f.actor.userId, body: "Continue with the current instructions", createdAt: new Date() });
expect((await displayStatus(f.issueId)).displayStatus).toBe("monitoring");
expect(await issueService(ctx.db).count(f.companyId, { displayStatus: "in_review" })).toBe(0);
});
it("does not treat a retained reviewer as pending after changes are requested", async () => {
const f = await fixture();
await ctx.db.update(issues).set({ executionState: { status: "changes_requested", currentStageId: "review",
currentStageType: "review", currentParticipant: { type: "user", userId: "reviewer" }, lastDecisionOutcome: "changes_requested" } }).where(eq(issues.id, f.issueId));
expect((await displayStatus(f.issueId)).displayStatus).toBe("monitoring");
await ctx.db.update(issues).set({ monitorNextCheckAt: null }).where(eq(issues.id, f.issueId));
expect((await displayStatus(f.issueId)).displayStatus).toBe("todo");
});
it("requires task-scoped active execution and preserves human ownership", async () => {
const f = await fixture();
await ctx.db.update(issues).set({ monitorNextCheckAt: null, executionPolicy: null }).where(eq(issues.id, f.issueId));
await ctx.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running" });
expect((await displayStatus(f.issueId)).displayStatus).toBe("todo");
const foreign = await fixture();
await ctx.db.insert(heartbeatRuns).values({ companyId: foreign.companyId, agentId: foreign.agentId, issueId: f.issueId, status: "running" });
expect((await displayStatus(f.issueId)).displayStatus).toBe("todo");
await ctx.db.update(issues).set({ assigneeAgentId: null, assigneeUserId: f.actor.userId }).where(eq(issues.id, f.issueId));
expect((await displayStatus(f.issueId)).displayStatus).toBe("in_progress");
});
it("projects a scheduled wait consistently across detail, compact rows, summaries, search and counts", async () => {
const f = await fixture();
const svc = issueService(ctx.db);
expect(await svc.getById(f.issueId)).toMatchObject({ status: "in_progress", displayStatus: "monitoring" });
expect(await svc.list(f.companyId, { displayStatus: "monitoring", listProjection: "index" })).toEqual([expect.objectContaining({ id: f.issueId, status: "in_progress", displayStatus: "monitoring" })]);
expect(await svc.count(f.companyId, { displayStatus: "monitoring" })).toBe(1);
const app = routeApp(ctx.db, f.actor, issueRoutes);
const summary = await request(app).get(`/api/companies/${f.companyId}/issues/summaries?ids=${f.issueId}`).expect(200);
expect(summary.body[0]).toMatchObject({ status: "in_progress", displayStatus: "monitoring" });
const result = await companySearchService(ctx.db).search(f.companyId, companySearchQuerySchema.parse({ q: "deployment", displayStatus: "monitoring" }));
expect(result.results[0]?.issue).toMatchObject({ id: f.issueId, status: "in_progress", displayStatus: "monitoring" });
expect(result.filterOptionCounts.displayStatus?.monitoring).toBe(1);
expect(result.filterOptionCounts.status.in_progress).toBe(1);
const [card] = await ctx.db.insert(statusCards).values({ companyId: f.companyId, interestPrompt: "Watch deployment", mentionedIssueIds: [f.issueId], refreshPolicy: defaultStatusCardRefreshPolicy }).returning();
expect(await statusCardService(ctx.db).listMentionedIssues(card!)).toEqual([expect.objectContaining({ id: f.issueId, status: "in_progress", displayStatus: "monitoring" })]);
// Existing agent/API lifecycle filters keep their original meaning.
expect(await svc.count(f.companyId, { status: "in_progress" })).toBe(1);
expect(createIssueSchema.safeParse({ title: "Manual monitoring", status: "monitoring" }).success).toBe(false);
});
it("filters before pagination and keeps In Progress separate from Monitoring", async () => {
const f = await fixture();
const [active] = await ctx.db.insert(issues).values({ companyId: f.companyId, title: "Ordinary work", status: "in_progress", assigneeAgentId: f.agentId }).returning();
await ctx.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, issueId: active!.id, status: "running" });
const svc = issueService(ctx.db);
expect(await svc.list(f.companyId, { displayStatus: "monitoring", limit: 1, offset: 0 })).toEqual([expect.objectContaining({ id: f.issueId })]);
expect(await svc.list(f.companyId, { displayStatus: "monitoring", limit: 1, offset: 1 })).toEqual([]);
expect(await svc.count(f.companyId, { displayStatus: "in_progress" })).toBe(1);
expect(await svc.count(f.companyId, { status: "in_progress" })).toBe(2);
});
it("shows the same wait indicator in list blocker summaries and task detail relations", async () => {
const f = await fixture();
const [dependent] = await ctx.db.insert(issues).values({ companyId: f.companyId, title: "Ship after deployment", status: "blocked" }).returning();
await ctx.db.insert(issueRelations).values({ companyId: f.companyId, issueId: f.issueId, relatedIssueId: dependent!.id, type: "blocks" });
const svc = issueService(ctx.db);
const list = await svc.list(f.companyId, { includeBlockedBy: true }) as Array<Awaited<ReturnType<typeof svc.list>>[number] & Pick<Issue, "blockedBy">>;
expect(list.find(row => row.id === dependent!.id)?.blockedBy).toEqual([expect.objectContaining({ id: f.issueId, displayStatus: "monitoring" })]);
const detail = await request(routeApp(ctx.db, f.actor, issueRoutes)).get(`/api/issues/${dependent!.id}`).expect(200);
expect(detail.body.blockedBy).toEqual([expect.objectContaining({ id: f.issueId, displayStatus: "monitoring" })]);
});
it("returns to In Progress during the check and Monitoring after another yield, then Done", async () => {
const f = await fixture();
const runId = randomUUID();
await ctx.db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, issueId: f.issueId, status: "queued" });
expect((await displayStatus(f.issueId)).displayStatus).toBe("in_progress");
await ctx.db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, runId));
await ctx.db.update(issues).set({ executionRunId: runId, checkoutRunId: runId }).where(eq(issues.id, f.issueId));
expect((await displayStatus(f.issueId)).displayStatus).toBe("in_progress");
await ctx.db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, runId));
await ctx.db.update(issues).set({ executionRunId: null, checkoutRunId: null }).where(eq(issues.id, f.issueId));
expect((await displayStatus(f.issueId)).displayStatus).toBe("monitoring");
await ctx.db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issueId));
expect(await displayStatus(f.issueId)).toEqual({ status: "done", displayStatus: "done" });
});
it.each(["blocked", "in_review", "todo", "cancelled"])("preserves %s even with a retained monitor", async (status) => {
const f = await fixture();
await ctx.db.update(issues).set({ status }).where(eq(issues.id, f.issueId));
expect((await displayStatus(f.issueId)).displayStatus).toBe(status);
});
it("does not label cleared, consumed, orphaned or quota-recovery schedules Monitoring", async () => {
const f = await fixture();
await ctx.db.update(issues).set({ executionState: { monitor: { status: "cleared" } } }).where(eq(issues.id, f.issueId));
expect((await displayStatus(f.issueId)).displayStatus).toBe("todo");
await ctx.db.update(issues).set({ executionState: null, monitorNextCheckAt: null }).where(eq(issues.id, f.issueId));
expect((await displayStatus(f.issueId)).displayStatus).toBe("todo");
await ctx.db.update(issues).set({ monitorNextCheckAt: new Date(), executionPolicy: { monitor: { serviceName: PROVIDER_QUOTA_MONITOR_SERVICE_NAME } } }).where(eq(issues.id, f.issueId));
expect((await displayStatus(f.issueId)).displayStatus).toBe("todo");
await ctx.db.update(issues).set({ executionPolicy: null }).where(eq(issues.id, f.issueId));
expect((await displayStatus(f.issueId)).displayStatus).toBe("todo");
});
it("keeps recovery and review holds visible and never writes a new lifecycle state", async () => {
const f = await fixture();
await ctx.db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: f.issueId, kind: "source", ownerType: "board", cause: "process_lost", fingerprint: randomUUID(), nextAction: "Inspect stopped run" });
expect((await displayStatus(f.issueId)).displayStatus).toBe("blocked");
await ctx.db.execute(sql`UPDATE issue_recovery_actions SET status = 'escalated' WHERE source_issue_id = ${f.issueId}`);
expect((await displayStatus(f.issueId)).displayStatus).toBe("blocked");
await ctx.db.execute(sql`UPDATE issue_recovery_actions SET status = 'resolved' WHERE source_issue_id = ${f.issueId}`);
expect((await displayStatus(f.issueId)).displayStatus).toBe("monitoring");
await ctx.db.update(issues).set({ executionState: { status: "pending", currentStageId: "review", currentStageType: "review", currentParticipant: { type: "user", userId: "reviewer" } } }).where(eq(issues.id, f.issueId));
expect((await displayStatus(f.issueId)).displayStatus).toBe("in_review");
});
it("shows an overdue monitor behind a resolved no-replay execution hold as Blocked, not Monitoring", async () => {
const f = await fixture();
await ctx.db.update(issues).set({ monitorNextCheckAt: new Date(Date.now() - 60 * 60_000) }).where(eq(issues.id, f.issueId));
const [hold] = await ctx.db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: f.issueId,
kind: "active_run_watchdog", status: "resolved", ownerType: "board", returnOwnerAgentId: f.agentId,
cause: "provider_failure_meaning_unverified", fingerprint: randomUUID(), outcome: "blocked",
evidence: { runId: randomUUID(), automaticRecovery: { policy: "preserve_without_replay_v1", replay: "blocked" } },
nextAction: "Verify safe staging or repair before continuing." }).returning();
expect(await getExecutionBlocker(ctx.db, f.companyId, f.issueId)).toMatchObject({ recoveryActionId: hold!.id });
expect((await displayStatus(f.issueId)).displayStatus).toBe("blocked");
expect(await issueService(ctx.db).count(f.companyId, { displayStatus: "blocked" })).toBe(1);
await ctx.db.update(issueRecoveryActions).set({ status: "cancelled" }).where(eq(issueRecoveryActions.id, hold!.id));
expect(await getExecutionBlocker(ctx.db, f.companyId, f.issueId)).toMatchObject({ recoveryActionId: hold!.id });
expect((await displayStatus(f.issueId)).displayStatus).toBe("blocked");
await ctx.db.update(issueRecoveryActions).set({ evidence: { automaticRecovery: { replay: "allowed" } } }).where(eq(issueRecoveryActions.id, hold!.id));
expect(await getExecutionBlocker(ctx.db, f.companyId, f.issueId)).toBeNull();
expect((await displayStatus(f.issueId)).displayStatus).toBe("monitoring");
});
});