Files
PaperClipAI/server/src/__tests__/task-watchdogs-scheduler.test.ts
T
a71c4b6782 [codex] feat(watchdog): add task watchdog control plane (#8339)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The task lifecycle and recovery subsystems decide when agent work is
still productive, stalled, or ready for review.
> - Existing recovery paths can observe stopped or incomplete work, but
there was no first-class per-task watchdog model with scoped review
permissions.
> - Watchdog follow-ups also need strict boundaries so
recovery/status-only runs cannot mutate approvals or perform deliverable
work.
> - This pull request adds the task watchdog data model, API/service
layer, scheduler/review flow, adapter wake context, UI configuration
surfaces, and docs.
> - The branch has been rebased onto current `paperclipai/paperclip`
`master`; the watchdog migration is now ordered after master's latest
migrations as `0104_issue_watchdogs`.
> - The benefit is a more explicit task-review loop that preserves
Paperclip's single-assignee and governance invariants while making
stalled work easier to route.

## Linked Issues or Issue Description

No linked GitHub issue. Paperclip task:
[PAP-11275](/PAP/issues/PAP-11275).

## Problem or motivation

Task recovery needs a first-class watchdog path that can inspect stopped
work and create scoped follow-ups without bypassing normal task
ownership. Board/UI users need a way to configure watchdogs on tasks and
see watchdog-related live work. Recovery/status-only runs must remain
limited to status reporting and must not create approvals, link
approvals, or submit approval comments.

## Proposed solution

Add a task-watchdog data model, scheduler/classifier, scoped mutation
guard, adapter wake context, API/UI configuration surfaces, and
documentation so watchdog agents can review stopped task subtrees under
explicit boundaries.

## Alternatives considered

Reuse the existing recovery-action flow only. That would keep
stopped-work detection implicit, make per-task watchdog assignment
harder to expose in the UI, and would not provide a durable
scoped-review issue for stalled task trees.

## Roadmap alignment

This is Paperclip control-plane lifecycle infrastructure for task
execution and recovery. I checked `ROADMAP.md`; this PR does not
duplicate an existing planned core item.

## What Changed

- Added issue watchdog schema, migration, shared contracts, validators,
CRUD API, and service support.
- Added task watchdog scheduler/classifier behavior, scoped mutation
enforcement, adapter wake context, and default watchdog mandate
guidance.
- Added UI surfaces for configuring watchdogs on new/existing tasks,
viewing watchdog activity, and exposing the experimental setting.
- Added docs for the user-facing task watchdog workflow and
implementation semantics.
- Gated new-task watchdog setup behind `enableTaskWatchdogs` and blocked
cheap status-only recovery runs from approval mutations.
- Rebased onto current `master` and renumbered the idempotent watchdog
migration from the branch-local `0102_issue_watchdogs` slot to
`0104_issue_watchdogs`.
- Addressed Greptile feedback by loading watchdog classifier input with
a recursive subtree query and centralizing the watchdog origin-kind
constant.
- Added and updated focused server/UI tests for watchdog routes,
scheduler/classifier behavior, scope boundaries, live task visibility,
settings, and new issue dialog behavior.

## Verification

- `pnpm vitest run server/src/__tests__/task-watchdogs-scheduler.test.ts
server/src/__tests__/task-watchdogs-classifier.test.ts`
- `pnpm vitest run
server/src/__tests__/approval-routes-idempotency.test.ts
server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts`
- `pnpm vitest run ui/src/components/NewIssueDialog.test.tsx`
- `pnpm --filter @paperclipai/server typecheck`
- `git diff --check`
- Verified the PR diff does not include `pnpm-lock.yaml` or
`.github/workflows`.

## Risks

- Medium risk: this introduces a new task lifecycle surface touching DB
schema, server routes/services, adapter wake context, and UI task
configuration.
- Watchdog scheduling behavior depends on the new experimental setting
and runtime context checks behaving consistently across local and
production agents.
- The watchdog migration is idempotent (`IF NOT EXISTS` /
duplicate-object guards) so users who tried the previous branch-local
migration number should not get duplicate-object failures.
- CI and the second Greptile pass are pending after the latest
review-fix push.

> 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, GPT-5-class coding agent in the Paperclip workspace. Exact
runtime model id and context window were not exposed to the agent; tool
use and local command execution were enabled.

## 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 run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots — N/A per Paperclip task instruction: do not add
screenshots/images to this PR unless they are specifically part of the
work.
- [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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 15:38:52 -05:00

593 lines
24 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import {
activityLog,
agentWakeupRequests,
agents,
companies,
createDb,
documents,
heartbeatRuns,
issueComments,
issueDocuments,
issueWorkProducts,
issues,
issueWatchdogs,
} from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
import { taskWatchdogService } from "../services/task-watchdogs.ts";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
if (!embeddedPostgresSupport.supported) {
console.warn(
`Skipping embedded Postgres task watchdog scheduler tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
);
}
describeEmbeddedPostgres("task watchdog scheduler", () => {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-task-watchdogs-scheduler-");
db = createDb(tempDb.connectionString);
}, 20_000);
afterEach(async () => {
await db.delete(activityLog);
await db.delete(issueWorkProducts);
await db.delete(issueDocuments);
await db.delete(documents);
await db.delete(issueComments);
await db.delete(heartbeatRuns);
await db.delete(agentWakeupRequests);
await db.delete(issueWatchdogs);
await db.delete(issues);
await db.delete(agents);
await db.delete(companies);
});
afterAll(async () => {
await tempDb?.cleanup();
});
async function seedCompany() {
const companyId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Watchdog Co",
issuePrefix: `WD${randomUUID().replace(/-/g, "").slice(0, 4).toUpperCase()}`,
issueCounter: 0,
requireBoardApprovalForNewAgents: false,
});
return companyId;
}
async function seedAgent(companyId: string, overrides: Partial<typeof agents.$inferInsert> = {}) {
const id = overrides.id ?? randomUUID();
await db.insert(agents).values({
id,
companyId,
name: overrides.name ?? "Watchdog Agent",
role: overrides.role ?? "engineer",
status: overrides.status ?? "active",
adapterType: overrides.adapterType ?? "codex_local",
adapterConfig: overrides.adapterConfig ?? {},
runtimeConfig: overrides.runtimeConfig ?? {},
permissions: overrides.permissions ?? {},
reportsTo: overrides.reportsTo,
});
return id;
}
async function seedIssue(companyId: string, overrides: Partial<typeof issues.$inferInsert> = {}) {
const id = overrides.id ?? randomUUID();
await db.insert(issues).values({
id,
companyId,
title: overrides.title ?? "Watched issue",
status: overrides.status ?? "done",
priority: overrides.priority ?? "medium",
identifier: overrides.identifier ?? `WDOG-${Math.floor(Math.random() * 10_000)}`,
issueNumber: overrides.issueNumber ?? Math.floor(Math.random() * 10_000),
parentId: overrides.parentId,
assigneeAgentId: overrides.assigneeAgentId,
originKind: overrides.originKind,
originId: overrides.originId,
originFingerprint: overrides.originFingerprint,
updatedAt: overrides.updatedAt,
// Default to an "established" issue (created well before the first-run
// grace window) so the pending-first-run guard does not defer it. Tests
// exercising the create-race pass an explicit recent `createdAt`.
createdAt: overrides.createdAt ?? new Date(Date.now() - 60 * 60 * 1000),
});
return id;
}
async function seedIssueDocument(companyId: string, issueId: string, updatedAt: Date) {
const [document] = await db.insert(documents).values({
companyId,
title: "Plan",
latestBody: "Plan body",
updatedAt,
}).returning();
await db.insert(issueDocuments).values({
companyId,
issueId,
documentId: document!.id,
key: "plan",
updatedAt,
});
}
async function seedIssueWorkProduct(companyId: string, issueId: string, updatedAt: Date) {
await db.insert(issueWorkProducts).values({
companyId,
issueId,
type: "artifact",
provider: "test",
title: "Report",
status: "ready",
updatedAt,
});
}
async function seedWatchdog(companyId: string, issueId: string, agentId: string) {
const [row] = await db.insert(issueWatchdogs).values({
companyId,
issueId,
watchdogAgentId: agentId,
instructions: "Verify stopped work.",
status: "active",
}).returning();
return row;
}
function createService() {
const wakes: Array<{ agentId: string; opts: Record<string, unknown> | undefined }> = [];
const service = taskWatchdogService(db, {
enqueueWakeup: async (agentId, opts) => {
wakes.push({ agentId, opts });
return { id: randomUUID() };
},
});
return { service, wakes };
}
it("creates one reusable watchdog issue and wakes the watchdog on the initial stopped state", async () => {
const companyId = await seedCompany();
const sourceId = await seedIssue(companyId, { identifier: "WDOG-1", status: "done" });
const agentId = await seedAgent(companyId);
await seedWatchdog(companyId, sourceId, agentId);
const { service, wakes } = createService();
const result = await service.reconcileTaskWatchdogs({ companyId });
expect(result).toMatchObject({ checked: 1, triggered: 1 });
expect(wakes).toHaveLength(1);
expect(wakes[0]?.agentId).toBe(agentId);
expect(wakes[0]?.opts?.reason).toBe("task_watchdog_stopped_subtree");
expect(wakes[0]?.opts?.contextSnapshot).toMatchObject({
taskWatchdog: {
watchedIssueId: sourceId,
watchedIssueIdentifier: "WDOG-1",
capabilities: {
targetScope: {
watchedIssueId: sourceId,
includeNonWatchdogDescendants: true,
excludedOriginKinds: ["task_watchdog"],
},
operations: expect.arrayContaining([
"comment_on_watched_subtree_issues",
"create_child_issues_under_non_watchdog_watched_subtree",
"create_product_bug_followups_outside_watched_subtree",
"update_reusable_watchdog_issue",
]),
deniedOperations: expect.arrayContaining([
"create_visible_probe_issues_or_throwaway_tasks",
"create_product_bug_followups_as_source_tree_children",
"mutate_task_watchdog_descendants",
]),
},
},
});
const watchdogIssues = await db
.select()
.from(issues)
.where(and(eq(issues.companyId, companyId), eq(issues.originKind, "task_watchdog")));
expect(watchdogIssues).toHaveLength(1);
expect(watchdogIssues[0]).toMatchObject({
parentId: sourceId,
originId: sourceId,
assigneeAgentId: agentId,
status: "todo",
});
const [watchdog] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.issueId, sourceId));
expect(watchdog?.watchdogIssueId).toBe(watchdogIssues[0]?.id);
expect(watchdog?.lastObservedFingerprint).toMatch(/^task_watchdog_stop:/);
expect(watchdog?.triggerCount).toBe(1);
});
it("does not trigger while a non-watchdog descendant has live work", async () => {
const companyId = await seedCompany();
const sourceId = await seedIssue(companyId, { identifier: "WDOG-2", status: "in_progress" });
const childId = await seedIssue(companyId, { parentId: sourceId, status: "in_progress" });
const agentId = await seedAgent(companyId);
await seedWatchdog(companyId, sourceId, agentId);
await db.insert(heartbeatRuns).values({
companyId,
agentId,
status: "queued",
invocationSource: "assignment",
contextSnapshot: { issueId: childId },
});
const { service, wakes } = createService();
const result = await service.reconcileTaskWatchdogs({ companyId });
expect(result).toMatchObject({ checked: 1, triggered: 0, live: 1 });
expect(wakes).toHaveLength(0);
const watchdogIssues = await db
.select({ id: issues.id })
.from(issues)
.where(and(eq(issues.companyId, companyId), eq(issues.originKind, "task_watchdog")));
expect(watchdogIssues).toHaveLength(0);
});
it("does not trigger while a descendant has a queued assignment wake", async () => {
const companyId = await seedCompany();
const sourceId = await seedIssue(companyId, { identifier: "WDOG-WAKE", status: "in_progress" });
const childId = await seedIssue(companyId, { parentId: sourceId, status: "todo" });
const agentId = await seedAgent(companyId);
await seedWatchdog(companyId, sourceId, agentId);
await db.insert(agentWakeupRequests).values({
companyId,
agentId,
status: "queued",
source: "assignment",
triggerDetail: "system",
reason: "issue_assigned",
payload: { issueId: childId },
});
const { service, wakes } = createService();
const result = await service.reconcileTaskWatchdogs({ companyId });
expect(result).toMatchObject({ checked: 1, triggered: 0, live: 1 });
expect(wakes).toHaveLength(0);
const watchdogIssues = await db
.select({ id: issues.id })
.from(issues)
.where(and(eq(issues.companyId, companyId), eq(issues.originKind, "task_watchdog")));
expect(watchdogIssues).toHaveLength(0);
});
it("does not keep the source live for runs under a nested task-watchdog issue", async () => {
const companyId = await seedCompany();
const sourceId = await seedIssue(companyId, { identifier: "WDOG-NEST", status: "done" });
const agentId = await seedAgent(companyId);
const nestedWatchdogIssueId = await seedIssue(companyId, {
parentId: sourceId,
status: "in_progress",
originKind: "task_watchdog",
originId: sourceId,
originFingerprint: `task_watchdog:${companyId}:${sourceId}`,
});
const nestedChildId = await seedIssue(companyId, {
parentId: nestedWatchdogIssueId,
status: "in_progress",
});
await seedWatchdog(companyId, sourceId, agentId);
await db.insert(heartbeatRuns).values({
companyId,
agentId,
status: "running",
invocationSource: "assignment",
contextSnapshot: { issueId: nestedChildId },
});
const { service, wakes } = createService();
const result = await service.reconcileTaskWatchdogs({ companyId });
expect(result).toMatchObject({ checked: 1, triggered: 1, live: 0 });
expect(wakes).toHaveLength(1);
});
it("reconciles ancestor watchdogs for a descendant issue mutation", async () => {
const companyId = await seedCompany();
const sourceId = await seedIssue(companyId, { identifier: "WDOG-ANCESTOR", status: "done" });
const childId = await seedIssue(companyId, { parentId: sourceId, status: "done" });
const agentId = await seedAgent(companyId);
await seedWatchdog(companyId, sourceId, agentId);
const { service, wakes } = createService();
const result = await service.reconcileForIssueAndAncestors(companyId, childId);
expect(result).toMatchObject({ checked: 1, triggered: 1 });
expect(wakes).toHaveLength(1);
});
it("marks a completed watchdog fingerprint reviewed, then reuses the same issue for a later stopped state", async () => {
const companyId = await seedCompany();
const sourceId = await seedIssue(companyId, { identifier: "WDOG-3", status: "done" });
const childId = await seedIssue(companyId, { parentId: sourceId, status: "done" });
const agentId = await seedAgent(companyId);
await seedWatchdog(companyId, sourceId, agentId);
const { service, wakes } = createService();
await service.reconcileTaskWatchdogs({ companyId });
const [firstWatchdog] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.issueId, sourceId));
const watchdogIssueId = firstWatchdog!.watchdogIssueId!;
const [firstWatchdogIssue] = await db.select().from(issues).where(eq(issues.id, watchdogIssueId));
expect(firstWatchdogIssue?.originFingerprint).toBe(firstWatchdog?.lastObservedFingerprint);
await db.update(issues).set({ status: "done", updatedAt: new Date() }).where(eq(issues.id, watchdogIssueId));
const reviewed = await service.reconcileTaskWatchdogs({ companyId });
expect(reviewed).toMatchObject({ checked: 1, triggered: 0, alreadyReviewed: 1 });
const [reviewedWatchdog] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.issueId, sourceId));
expect(reviewedWatchdog?.lastReviewedFingerprint).toBe(firstWatchdog?.lastObservedFingerprint);
await db
.update(issues)
.set({ status: "blocked", updatedAt: new Date(Date.now() + 60_000) })
.where(eq(issues.id, childId));
const retriggered = await service.reconcileTaskWatchdogs({ companyId });
expect(retriggered).toMatchObject({ checked: 1, triggered: 1 });
const watchdogIssues = await db
.select()
.from(issues)
.where(and(eq(issues.companyId, companyId), eq(issues.originKind, "task_watchdog")));
expect(watchdogIssues).toHaveLength(1);
expect(watchdogIssues[0]).toMatchObject({ id: watchdogIssueId, status: "todo" });
const comments = await db
.select()
.from(issueComments)
.where(eq(issueComments.issueId, watchdogIssueId));
expect(comments.some((comment) => comment.body.includes("Stopped fingerprint"))).toBe(true);
expect(wakes.length).toBe(2);
});
it("does not let an old terminal watchdog review mark a newer observed fingerprint reviewed", async () => {
const companyId = await seedCompany();
const sourceId = await seedIssue(companyId, { identifier: "WDOG-STALE", status: "done" });
const childId = await seedIssue(companyId, { parentId: sourceId, status: "done" });
const agentId = await seedAgent(companyId);
await seedWatchdog(companyId, sourceId, agentId);
const { service, wakes } = createService();
await service.reconcileTaskWatchdogs({ companyId });
const [firstWatchdog] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.issueId, sourceId));
const oldFingerprint = firstWatchdog!.lastObservedFingerprint!;
const watchdogIssueId = firstWatchdog!.watchdogIssueId!;
const watchdogRunId = randomUUID();
await db.insert(heartbeatRuns).values({
id: watchdogRunId,
companyId,
agentId,
status: "running",
invocationSource: "assignment",
contextSnapshot: { issueId: watchdogIssueId },
});
await db
.update(issues)
.set({ status: "blocked", updatedAt: new Date(Date.now() + 60_000) })
.where(eq(issues.id, childId));
const changedWhileReviewLive = await service.reconcileTaskWatchdogs({ companyId });
expect(changedWhileReviewLive).toMatchObject({ checked: 1, triggered: 0, live: 1 });
const [observedWhileLive] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.issueId, sourceId));
const newerFingerprint = observedWhileLive!.lastObservedFingerprint!;
expect(newerFingerprint).not.toBe(oldFingerprint);
const [stillBoundReview] = await db.select().from(issues).where(eq(issues.id, watchdogIssueId));
expect(stillBoundReview?.originFingerprint).toBe(oldFingerprint);
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, watchdogRunId));
await db.update(issues).set({ status: "done", updatedAt: new Date() }).where(eq(issues.id, watchdogIssueId));
const afterOldReviewCompletes = await service.reconcileTaskWatchdogs({ companyId });
expect(afterOldReviewCompletes).toMatchObject({ checked: 1, triggered: 1 });
const [reviewedWatchdog] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.issueId, sourceId));
expect(reviewedWatchdog?.lastReviewedFingerprint).toBe(oldFingerprint);
expect(reviewedWatchdog?.lastReviewedFingerprint).not.toBe(newerFingerprint);
const [reopenedWatchdogIssue] = await db.select().from(issues).where(eq(issues.id, watchdogIssueId));
expect(reopenedWatchdogIssue).toMatchObject({
status: "todo",
originFingerprint: newerFingerprint,
});
const reviewActivities = await db
.select()
.from(activityLog)
.where(and(eq(activityLog.entityId, sourceId), eq(activityLog.action, "issue.task_watchdog_fingerprint_reviewed")));
expect(reviewActivities).toHaveLength(1);
expect(reviewActivities[0]?.details).toMatchObject({
reviewedFingerprint: oldFingerprint,
lastObservedFingerprint: newerFingerprint,
});
expect(wakes.length).toBe(2);
});
it("revalidates stale watchdog reviews against current source evidence before allowing mutations", async () => {
const companyId = await seedCompany();
const sourceId = await seedIssue(companyId, { identifier: "WDOG-REVALIDATE", status: "blocked" });
const agentId = await seedAgent(companyId);
await seedWatchdog(companyId, sourceId, agentId);
const { service } = createService();
await service.reconcileTaskWatchdogs({ companyId });
const [watchdog] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.issueId, sourceId));
const originalFingerprint = watchdog!.lastObservedFingerprint!;
expect(originalFingerprint).toMatch(/^task_watchdog_stop:/);
const later = new Date(Date.now() + 60_000);
await db.insert(issueComments).values({
companyId,
issueId: sourceId,
authorType: "agent",
body: "Fresh source evidence.",
updatedAt: later,
createdAt: later,
});
await seedIssueDocument(companyId, sourceId, new Date(later.getTime() + 1_000));
await seedIssueWorkProduct(companyId, sourceId, new Date(later.getTime() + 2_000));
const revalidated = await service.revalidateMutationScope({
kind: "watchdog",
watchdogId: watchdog!.id,
companyId,
watchedIssueId: sourceId,
stopFingerprint: originalFingerprint,
});
expect(revalidated.allowed).toBe(false);
expect(revalidated.reason).toContain("stop fingerprint changed");
expect(revalidated.classification?.state).toBe("stopped");
if (revalidated.classification?.state !== "stopped") throw new Error("Expected stopped classification");
expect(revalidated.classification.stopFingerprint).not.toBe(originalFingerprint);
expect(revalidated.classification.stoppedLeaves[0]).toMatchObject({
latestCommentAt: later.toISOString(),
latestDocumentAt: new Date(later.getTime() + 1_000).toISOString(),
latestWorkProductAt: new Date(later.getTime() + 2_000).toISOString(),
});
});
it("revalidates a stale watchdog review as live when the source gets a fresh run path", async () => {
const companyId = await seedCompany();
const sourceId = await seedIssue(companyId, { identifier: "WDOG-LIVE-REVALIDATE", status: "blocked" });
const agentId = await seedAgent(companyId);
await seedWatchdog(companyId, sourceId, agentId);
const { service } = createService();
await service.reconcileTaskWatchdogs({ companyId });
const [watchdog] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.issueId, sourceId));
const originalFingerprint = watchdog!.lastObservedFingerprint!;
await db.insert(heartbeatRuns).values({
companyId,
agentId,
status: "running",
invocationSource: "assignment",
contextSnapshot: { issueId: sourceId },
});
const revalidated = await service.revalidateMutationScope({
kind: "watchdog",
watchdogId: watchdog!.id,
companyId,
watchedIssueId: sourceId,
stopFingerprint: originalFingerprint,
});
expect(revalidated.allowed).toBe(false);
expect(revalidated.reason).toContain("now has a live");
expect(revalidated.classification?.state).toBe("live");
});
it("does not raise a stopped-subtree review while a freshly-created assigned issue's first run is starting", async () => {
const companyId = await seedCompany();
const agentId = await seedAgent(companyId);
// Issue + watchdog created in the same flow; the assignment run row is not
// yet visible to this evaluation (create-race).
const sourceId = await seedIssue(companyId, {
identifier: "WDOG-RACE",
status: "todo",
assigneeAgentId: agentId,
createdAt: new Date(),
});
await seedWatchdog(companyId, sourceId, agentId);
const { service, wakes } = createService();
const result = await service.reconcileTaskWatchdogs({ companyId });
expect(result).toMatchObject({ checked: 1, triggered: 0, pendingFirstRun: 1 });
expect(wakes).toHaveLength(0);
const watchdogIssues = await db
.select({ id: issues.id })
.from(issues)
.where(and(eq(issues.companyId, companyId), eq(issues.originKind, "task_watchdog")));
expect(watchdogIssues).toHaveLength(0);
const [watchdog] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.issueId, sourceId));
expect(watchdog?.triggerCount).toBe(0);
});
it("still triggers a genuinely idle assigned issue once it is past the first-run grace window", async () => {
const companyId = await seedCompany();
const agentId = await seedAgent(companyId);
// Established issue (default createdAt is an hour ago), assigned, non-terminal,
// with no live run or queued wake.
const sourceId = await seedIssue(companyId, {
identifier: "WDOG-IDLE",
status: "todo",
assigneeAgentId: agentId,
});
await seedWatchdog(companyId, sourceId, agentId);
const { service, wakes } = createService();
const result = await service.reconcileTaskWatchdogs({ companyId });
expect(result).toMatchObject({ checked: 1, triggered: 1 });
expect(wakes).toHaveLength(1);
});
it("does not defer once the freshly-created issue has a terminal run on record", async () => {
const companyId = await seedCompany();
const agentId = await seedAgent(companyId);
const sourceId = await seedIssue(companyId, {
identifier: "WDOG-RAN",
status: "blocked",
assigneeAgentId: agentId,
createdAt: new Date(),
});
await seedWatchdog(companyId, sourceId, agentId);
// A run for this issue already reached a terminal status, so the stop is
// genuine even though the issue was just created.
await db.insert(heartbeatRuns).values({
companyId,
agentId,
status: "succeeded",
invocationSource: "assignment",
contextSnapshot: { issueId: sourceId },
});
const { service, wakes } = createService();
const result = await service.reconcileTaskWatchdogs({ companyId });
expect(result).toMatchObject({ checked: 1, triggered: 1 });
expect(wakes).toHaveLength(1);
});
it("does not recursively trigger a watchdog configured on a task-watchdog issue", async () => {
const companyId = await seedCompany();
const agentId = await seedAgent(companyId);
const sourceId = await seedIssue(companyId, { identifier: "WDOG-4", status: "done" });
const watchdogIssueId = await seedIssue(companyId, {
parentId: sourceId,
status: "done",
originKind: "task_watchdog",
originId: sourceId,
originFingerprint: `task_watchdog:${companyId}:${sourceId}`,
});
await seedIssue(companyId, { parentId: watchdogIssueId, status: "done" });
await seedWatchdog(companyId, watchdogIssueId, agentId);
const { service, wakes } = createService();
const result = await service.reconcileTaskWatchdogs({ companyId });
expect(result).toMatchObject({ checked: 1, triggered: 0 });
expect(wakes).toHaveLength(0);
const watchdogIssues = await db
.select()
.from(issues)
.where(and(eq(issues.companyId, companyId), eq(issues.originKind, "task_watchdog")));
expect(watchdogIssues).toHaveLength(1);
});
});