Files
PaperClipAI/server/src/__tests__/task-watchdogs-scheduler.test.ts
T
Ash Simons 550e959934 fix(task-watchdogs): deliver board instructions and stopped leaves in the wake payload (#13771)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Task watchdogs wake an agent when a watched issue subtree stops
moving.
> - An operator can write `instructions` on the watchdog record. The
wake prompt has a slot for this text in the "Task Watchdog Mandate"
block.
> - The producer writes `customInstructions` and `stoppedLeaves` at the
top level of the wake payload. The normalizer reads them only from the
nested `taskWatchdog` object. Thus the normalizer drops both fields on
every watchdog wake.
> - The agent then sees "No board-supplied watchdog instructions"
although the record holds an instruction. The operator cannot see this
failure, and the agent cannot see it either.
> - This pull request puts both fields in the nested `taskWatchdog`
object.
> - The benefit is that operator instructions and the stopped-leaf list
reach the agent again.

## Linked Issues or Issue Description

No public issue exists. This is the bug description (bug_report
template).

**What happened?**
`watchdogWakeContext()` in `server/src/services/task-watchdogs.ts`
writes `customInstructions` and `stoppedLeaves` at the top level of the
wake payload. `normalizePaperclipWakePayload()` in
`packages/adapter-utils/src/server-utils.ts` reads
`payload.taskWatchdog` only. The two fields are lost. The "Task Watchdog
Mandate" block always shows "No board-supplied watchdog instructions.
Apply the mandate above." The "Terminal / stopped leaves to verify"
section never shows.

**Expected behavior**
When the watchdog record has non-empty `instructions`, the wake prompt
shows that text. When the subtree has stopped leaves, the prompt lists
them.

**Steps to reproduce**
1. Create a task watchdog on an issue. Set a non-empty `instructions`
value.
2. Let the watched subtree stop, so that the watchdog triggers.
3. Read the wake prompt of the watchdog agent. It shows the "No
board-supplied watchdog instructions" line.
4. `GET /api/issues/{id}/watchdog` still returns the non-empty
`instructions` value.

**Paperclip version or commit**
Reproduced on `master` before this change. The new test in this PR fails
on `master`.

**Agent adapter(s) involved**
Not adapter-specific (core bug). The drop occurs in the shared
wake-payload normalizer.

## What Changed

- `server/src/services/task-watchdogs.ts`: add `customInstructions` and
`stoppedLeaves` to the nested `taskWatchdog` object. Map each stopped
leaf to the shape the normalizer expects (`issueId` becomes `id`). Keep
the top-level copies, so that other consumers do not change.
- Add a test for the full path: real service, real wake payload,
`normalizePaperclipWakePayload`, then `renderPaperclipWakePrompt`. The
test also asserts that the "No board-supplied watchdog instructions"
line is absent.

## Verification

- Run from the repo root:
  ```
  npx vitest run server/src/__tests__/task-watchdogs-scheduler.test.ts \
server/src/__tests__/task-watchdogs-classifier.test.ts \
server/src/__tests__/task-watchdogs-incident-fixture.test.ts \
                 server/src/__tests__/issue-watchdogs-routes.test.ts
  npx vitest run packages/adapter-utils/src/server-utils.test.ts
  ```
- Local result: watchdog suites 52 of 52 pass. `server-utils.test.ts`
117 of 117 pass.
- The new test fails on `master` because
`taskWatchdog.customInstructions` is absent. It passes on this branch.
- All Paperclip CI gates on this PR are green. Greptile gives 5/5.

## Risks

- Low risk. The change adds fields to a nested object. It does not
remove fields.
- No schema change, no migration, no data write.
- Behavior change: agents now receive operator instructions that they
did not receive before. This is the intended result.
- Rollback: revert the single commit.
- Note: the normalizer field name is `terminalLeafSummaries`, but the
classifier fills `stoppedLeaves` with non-terminal stopped leaves. The
renderer heading ("Terminal / stopped leaves to verify") covers both.
This PR does not rename a public payload field. Maintainers can align
the names in a separate change.

> 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

- Provider: Anthropic Claude, Opus family, used through Claude Code as
an agent with tool use and shell execution.
- This PR description revision: `claude-opus-5-5`, 1M context window.
- The model found the cause, wrote the fix and the test, and ran the
test suites. A human owns the account that opened the PR.

## 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
- [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 (not
applicable: no documented behavior changed)
- [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

Duplicate search: I searched open and closed PRs and issues for
"watchdog instructions" and "watchdog customInstructions". I found no
related PR or issue.

Branch name: the branch name has an internal prefix. If the maintainers
want it, I can open the same commit again from a `fix/...` branch.
2026-10-15 15:47:54 -07:00

852 lines
34 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,
approvals,
companies,
createDb,
documents,
heartbeatRuns,
issueComments,
issueDocuments,
issueApprovals,
issueThreadInteractions,
issueWorkProducts,
issues,
issueWatchdogs,
} from "@paperclipai/db";
import {
normalizePaperclipWakePayload,
renderPaperclipWakePrompt,
} from "@paperclipai/adapter-utils/server-utils";
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(issueApprovals);
await db.delete(approvals);
await db.delete(issueThreadInteractions);
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,
instructions = "Verify stopped work.",
) {
const [row] = await db.insert(issueWatchdogs).values({
companyId,
issueId,
watchdogAgentId: agentId,
instructions,
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?.idempotencyKey).toMatch(/^task_watchdog:[^:]+:task_watchdog_stop:/);
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?.lastObservedStopSnapshot).toMatchObject({
version: 2,
fingerprint: watchdog?.lastObservedFingerprint,
materialLeaves: [],
waitsByIssueId: {},
});
expect(watchdog?.triggerCount).toBe(1);
});
it("delivers board-supplied watchdog instructions all the way into the rendered mandate", async () => {
const boardInstructions =
"Escalate to Luna before any production deploy; you do not hold Level B authority.";
const companyId = await seedCompany();
const sourceId = await seedIssue(companyId, { identifier: "WDOG-INSTR", status: "done" });
const leafId = await seedIssue(companyId, {
parentId: sourceId,
identifier: "WDOG-INSTR-LEAF",
status: "todo",
});
const agentId = await seedAgent(companyId);
await seedWatchdog(companyId, sourceId, agentId, boardInstructions);
const { service, wakes } = createService();
await service.reconcileTaskWatchdogs({ companyId });
expect(wakes).toHaveLength(1);
// The producer must place the instructions inside `taskWatchdog`, which is
// the only object the wake normalizer reads.
const snapshot = wakes[0]?.opts?.contextSnapshot;
expect(snapshot).toMatchObject({ taskWatchdog: { customInstructions: boardInstructions } });
// End-to-end: the text the agent actually receives.
const normalized = normalizePaperclipWakePayload(snapshot);
expect(normalized?.taskWatchdog?.customInstructions).toBe(boardInstructions);
const prompt = renderPaperclipWakePrompt(normalized);
expect(prompt).toContain("## Task Watchdog Mandate");
expect(prompt).toContain(boardInstructions);
expect(prompt).not.toContain("No board-supplied watchdog instructions");
// Same producer/normalizer contract: the stopped leaves the watchdog is
// asked to verify must reach the mandate too.
expect(normalized?.taskWatchdog?.terminalLeafSummaries).toEqual([
expect.objectContaining({ id: leafId, identifier: "WDOG-INSTR-LEAF", status: "todo" }),
]);
expect(prompt).toContain("Terminal / stopped leaves to verify:");
expect(prompt).toContain("WDOG-INSTR-LEAF");
});
it("does not append duplicate review comments for an already-open same-fingerprint review", async () => {
const companyId = await seedCompany();
const sourceId = await seedIssue(companyId, { identifier: "WDOG-DUPE", status: "done" });
const agentId = await seedAgent(companyId);
await seedWatchdog(companyId, sourceId, agentId);
const { service, wakes } = createService();
const first = await service.reconcileTaskWatchdogs({ companyId });
expect(first).toMatchObject({ checked: 1, triggered: 1 });
const [firstWatchdog] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.issueId, sourceId));
const watchdogIssueId = firstWatchdog!.watchdogIssueId!;
const initialComments = await db
.select()
.from(issueComments)
.where(eq(issueComments.issueId, watchdogIssueId));
expect(initialComments).toHaveLength(1);
const second = await service.reconcileTaskWatchdogs({ companyId });
expect(second).toMatchObject({ checked: 1, triggered: 0, live: 1 });
expect(wakes).toHaveLength(1);
const comments = await db
.select()
.from(issueComments)
.where(eq(issueComments.issueId, watchdogIssueId));
expect(comments).toHaveLength(1);
const [watchdog] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.issueId, sourceId));
expect(watchdog?.lastObservedFingerprint).toBe(firstWatchdog?.lastObservedFingerprint);
expect(watchdog?.triggerCount).toBe(1);
});
it("re-wakes a same-fingerprint watchdog review stuck in stale in_review", async () => {
const companyId = await seedCompany();
const sourceId = await seedIssue(companyId, { identifier: "WDOG-STALE", status: "done" });
const agentId = await seedAgent(companyId);
await seedWatchdog(companyId, sourceId, agentId);
const { service, wakes } = createService();
const first = await service.reconcileTaskWatchdogs({ companyId });
expect(first).toMatchObject({ checked: 1, triggered: 1 });
const [firstWatchdog] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.issueId, sourceId));
const watchdogIssueId = firstWatchdog!.watchdogIssueId!;
await db
.update(issues)
.set({
status: "in_review",
assigneeAgentId: null,
assigneeUserId: null,
executionState: null,
monitorNextCheckAt: null,
})
.where(eq(issues.id, watchdogIssueId));
const second = await service.reconcileTaskWatchdogs({ companyId });
expect(second).toMatchObject({ checked: 1, triggered: 1 });
expect(wakes).toHaveLength(2);
const [watchdogIssue] = await db.select().from(issues).where(eq(issues.id, watchdogIssueId));
expect(watchdogIssue).toMatchObject({
status: "todo",
assigneeAgentId: agentId,
originFingerprint: firstWatchdog?.lastObservedFingerprint,
});
const comments = await db
.select()
.from(issueComments)
.where(eq(issueComments.issueId, watchdogIssueId));
expect(comments).toHaveLength(2);
const [watchdog] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.issueId, sourceId));
expect(watchdog?.triggerCount).toBe(2);
});
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);
expect(reviewedWatchdog?.lastReviewedStopSnapshot).toEqual(firstWatchdog?.lastObservedStopSnapshot);
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("suppresses a shrink-only stop after review when the snapshot round-trips through jsonb", async () => {
const companyId = await seedCompany();
const sourceId = await seedIssue(companyId, { identifier: "WDOG-SHRINK", status: "in_review" });
const waitingLeafId = await seedIssue(companyId, { parentId: sourceId, status: "in_review" });
const siblingLeafId = await seedIssue(companyId, { parentId: sourceId, status: "in_progress" });
const agentId = await seedAgent(companyId);
await db.insert(issueThreadInteractions).values({
id: randomUUID(),
companyId,
issueId: waitingLeafId,
kind: "request_confirmation",
status: "pending",
payload: { version: 1, prompt: "Confirm the stop." },
createdByAgentId: agentId,
});
await seedWatchdog(companyId, sourceId, agentId);
const { service, wakes } = createService();
const first = await service.reconcileTaskWatchdogs({ companyId });
expect(first).toMatchObject({ checked: 1, triggered: 1 });
const [triggeredWatchdog] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.issueId, sourceId));
await db
.update(issues)
.set({ status: "done", updatedAt: new Date() })
.where(eq(issues.id, triggeredWatchdog!.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?.lastReviewedStopSnapshot).not.toBeNull();
// The sibling completing shrinks the material leaf set while the wait set
// is unchanged; the reviewed snapshot loaded back from jsonb (which does
// not preserve object key order) must still suppress the wake.
await db
.update(issues)
.set({ status: "done", updatedAt: new Date(Date.now() + 60_000) })
.where(eq(issues.id, siblingLeafId));
const afterShrink = await service.reconcileTaskWatchdogs({ companyId });
expect(afterShrink).toMatchObject({ checked: 1, triggered: 0, alreadyReviewed: 1 });
expect(wakes).toHaveLength(1);
});
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);
expect(reviewedWatchdog?.lastReviewedStopSnapshot).toBeNull();
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("keeps watchdog mutation scope valid across metadata-only source evidence", 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(true);
expect(revalidated.classification?.state).toBe("stopped");
if (revalidated.classification?.state !== "stopped") throw new Error("Expected stopped classification");
expect(revalidated.classification.stopFingerprint).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("surfaces pending interaction kinds and approval ids in the wake and watchdog comment", async () => {
const companyId = await seedCompany();
const sourceId = await seedIssue(companyId, { identifier: "WDOG-WAITS", status: "in_review" });
const agentId = await seedAgent(companyId);
await seedWatchdog(companyId, sourceId, agentId);
const interactionId = randomUUID();
const approvalId = randomUUID();
await db.insert(issueThreadInteractions).values({
id: interactionId,
companyId,
issueId: sourceId,
kind: "request_confirmation",
status: "pending",
payload: { version: 1, prompt: "Confirm the reviewed stop." },
createdByAgentId: agentId,
});
await db.insert(approvals).values({
id: approvalId,
companyId,
type: "request_board_approval",
requestedByAgentId: agentId,
status: "pending",
payload: { summary: "Approve the reviewed stop." },
});
await db.insert(issueApprovals).values({
companyId,
issueId: sourceId,
approvalId,
linkedByAgentId: agentId,
});
const { service, wakes } = createService();
const result = await service.reconcileTaskWatchdogs({ companyId });
expect(result).toMatchObject({ checked: 1, triggered: 1 });
expect(wakes[0]?.opts?.contextSnapshot).toMatchObject({
taskWatchdog: {
pendingInteractions: {
[sourceId]: [{ id: interactionId, kind: "request_confirmation" }],
},
pendingApprovals: {
[sourceId]: [approvalId],
},
},
});
const [watchdog] = await db.select().from(issueWatchdogs).where(eq(issueWatchdogs.issueId, sourceId));
expect(watchdog?.lastObservedStopSnapshot).toMatchObject({
waitsByIssueId: {
[sourceId]: {
pendingInteractionIds: [interactionId],
pendingApprovalIds: [approvalId],
},
},
});
const comments = await db
.select()
.from(issueComments)
.where(eq(issueComments.issueId, watchdog!.watchdogIssueId!));
expect(comments.at(-1)?.body).toContain(`pending request_confirmation ${interactionId.slice(0, 8)}…`);
expect(comments.at(-1)?.body).toContain(`approval ${approvalId.slice(0, 8)}…`);
const metadata = comments.at(-1)?.metadata as { sections?: Array<{ rows?: unknown[] }> } | null;
expect(metadata?.sections?.[0]?.rows).toEqual(expect.arrayContaining([
expect.objectContaining({ label: "Pending waits", text: "2" }),
]));
});
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);
});
it("handles an armed cutoff when no watchdogs are active", async () => {
const companyId = await seedCompany();
const { service } = createService();
const result = await service.reconcileTaskWatchdogs({
companyId,
issueCreatedAtGte: new Date(),
});
expect(result).toMatchObject({ checked: 0, triggered: 0 });
});
});