mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 18:35:33 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Pull request CI runs Vitest suites across five lanes: Runner native server, general chat, general server, serialized server, and Runner package tests. > - Even after pre-baked AMIs and 8-vCPU runners, single-shard `vitest native server`, 2-shard `general-chat`, and several oversized single-file Vitest specs still exceed the 85s per-shard ceiling and dominate pull request wall-clock time. > - Splitting those oversized test files and expanding AWS sharding where needed lowers the slowest Vitest shard under the sub-3-minute pull request budget while preserving every test case and keeping `ubuntu-latest` fallback fan-out compact. > - This pull request shards `vitest native server` (`1 -> 2` on AWS, `1` on hosted runners) and `general-chat` (`2 -> 3` on AWS, `1` on hosted runners), splits the remaining `>85s` single-file Vitest tails across all five lanes into focused `<1,000 LOC` sibling test files with shared harnesses, and refreshes the four Vitest timing manifests. > - The benefit is faster pull request feedback with lower tail variance across every Vitest lane and zero deleted tests. ## Linked Issues or Issue Description Refs #22916 **What existing behavior does this improve?** Pull request Vitest shard wall-clock time across `vitest native server`, `general-chat`, `general server`, `serialized server`, and `Runner vitest package`. **Current behavior** Single-shard `vitest native server`, 2-shard `general-chat`, and several monolithic test files still run above 85s on 8-vCPU AWS PR runners, holding back pull request CI completion. **Proposed behavior** Expand AWS sharding for `vitest native server` (`1 -> 2` with `release_crate: true` on both, `1` compacted shard on `ubuntu-latest`) and `general-chat` (`2 -> 3` on AWS, `1` on `ubuntu-latest`), split the remaining oversized single-file Vitest suites into focused sibling files under 1,000 LOC with shared test harnesses, and refresh the four Vitest shard duration manifests so LPT packing balances the split files immediately. **Reason and benefit** Cuts Vitest critical-path wall clock under 95s per shard while preserving 100% of test coverage, lane ownership boundaries, and compact 33-job `ubuntu-latest` fallback fan-out. **Breaking changes** None. Pure test-file refactoring and shard matrix configuration. ## What Changed - Expanded AWS sharding in `.github/ci-task-matrix.json`, `.github/workflows/pr-trusted.yml`, and `scripts/run-vitest-stable.mjs`: - `Verify Paperclip Runner (vitest native server)`: `1 -> 2` shards on AWS (`release_crate: true` on both), `1` shard on `ubuntu-latest` via `HOSTED_SHARD_COUNTS["ci:runner-vitest"] = 1` and `nativeServerLanePattern`. - `General tests (chat)`: `2 -> 3` shards on AWS, `1` shard on `ubuntu-latest`. - Split the remaining `>85s` single-file Vitest tails across all five lanes into focused `<1,000 LOC` sibling test files with shared harnesses (zero deleted tests, zero cross-test-file imports, anchor filenames and lane ownership preserved): - Runner package lane (`packages/paperclip-runner`): split oversized daemon/provider integration files. - Native server lane: split `native-ingress-bootstrap-retry` while keeping `native-ingress-bootstrap-retry-opencode` strictly in `native-runner`. - Chat lane: split oversized Telegram/GitHub/connection-management integration tests. - General server lane: split `tool-gateway-service.test.ts` and `attention-service` tests using shared harnesses. - Serialized server lane: split `heartbeat-dependency-scheduling` / `native-wakes` and `agent-adapter-validation` tests, keeping serialized ownership intact. - Refreshed all four Vitest shard duration manifests (`packages/paperclip-runner/scripts/vitest-lane-durations.json`, `scripts/chat-shard-durations.json`, `scripts/general-server-shard-durations.json`, `scripts/serialized-shard-durations.json`) and updated CI contract tests. ## Verification - Ran all CI contract suites after rebasing onto `origin/master`: - `node --test .github/scripts/tests/ci-plan.test.mjs scripts/ci/runner-release-crate-cache.test.mjs scripts/ci/run-vitest-stable-shard.test.mjs scripts/ci/run-vitest-stable-pr-mode.test.mjs scripts/ci/runner-vitest-package-lanes.test.mjs scripts/ci/test-selection-pr-timings.test.mjs scripts/ci/e2e-shard.test.mjs scripts/ci/check-test-budget.test.mjs` - `node scripts/check-test-budget.mjs` - `node scripts/check-maps.mjs` - Verified every new test file is under 1,000 LOC, zero cross-test-file imports exist, zero files are missing from the four timing manifests, and `ubuntu-latest` remains strictly at 33 jobs. ## Risks - Low risk: pure test-file refactoring and shard matrix expansion with zero production code changes. - Reverted cleanly by a single `git revert` if any shard balance or manifest adjustment is needed. ## Model Used - Google Gemini (Antigravity / Gemini 4 Neon (High), tool use and code execution 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 not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
1221 lines
42 KiB
TypeScript
1221 lines
42 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { and, eq, inArray, sql } from "drizzle-orm";
|
|
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
|
import {
|
|
costEvents,
|
|
activityLog,
|
|
agents,
|
|
agentRuntimeState,
|
|
agentWakeupRequests,
|
|
companySkills,
|
|
completionContracts,
|
|
nativeRunResults,
|
|
nativeRunFinalizations,
|
|
workAssessments,
|
|
statusDecisions,
|
|
statusDecisionEffects,
|
|
companies,
|
|
authUsers,
|
|
companyMemberships,
|
|
createDb,
|
|
documentRevisions,
|
|
documents,
|
|
environmentLeases,
|
|
environments,
|
|
executionWorkspaces,
|
|
heartbeatRunEvents,
|
|
heartbeatRuns,
|
|
issueComments,
|
|
issueDocuments,
|
|
issueRelations,
|
|
issueRecoveryActions,
|
|
issueThreadInteractions,
|
|
issueTreeHolds,
|
|
issues,
|
|
workspaceOperations,
|
|
} from "@paperclipai/db";
|
|
import {
|
|
getEmbeddedPostgresTestSupport,
|
|
startEmbeddedPostgresTestDatabase,
|
|
} from "./helpers/embedded-postgres.js";
|
|
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
|
import { heartbeatService } from "../services/heartbeat.ts";
|
|
import { runningProcesses } from "../adapters/index.ts";
|
|
import { createPostgresRunDispatchAdapter } from "../modules/run-dispatch/adapters/postgres.js";
|
|
import { taskInterruptionPresentation } from "../services/task-interruption-presentation.js";
|
|
import * as workspacePreparation from "../services/heartbeat/workspace-preparation.js";
|
|
import { WorkspaceBusyDeferral } from "../services/heartbeat/retries.js";
|
|
|
|
const mockAdapterExecute = vi.hoisted(() =>
|
|
vi.fn(async () => ({
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
summary: "Dependency-aware heartbeat test run.",
|
|
provider: "test",
|
|
model: "test-model",
|
|
})),
|
|
);
|
|
|
|
vi.mock("../adapters/index.ts", async () => {
|
|
const actual = await vi.importActual<typeof import("../adapters/index.ts")>("../adapters/index.ts");
|
|
return {
|
|
...actual,
|
|
getServerAdapter: vi.fn(() => ({
|
|
supportsLocalAgentJwt: false,
|
|
execute: mockAdapterExecute,
|
|
})),
|
|
};
|
|
});
|
|
|
|
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_DEPENDENCY_TEST_DATABASE_URL");
|
|
const embeddedPostgresSupport = external ? { supported: true, reason: undefined } : await getEmbeddedPostgresTestSupport();
|
|
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
|
|
|
if (!embeddedPostgresSupport.supported) {
|
|
console.warn(
|
|
`Skipping embedded Postgres heartbeat dependency scheduling tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
|
|
);
|
|
}
|
|
|
|
async function ensureIssueRelationsTable(db: ReturnType<typeof createDb>) {
|
|
await db.execute(sql.raw(`
|
|
CREATE TABLE IF NOT EXISTS "issue_relations" (
|
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
"company_id" uuid NOT NULL,
|
|
"issue_id" uuid NOT NULL,
|
|
"related_issue_id" uuid NOT NULL,
|
|
"type" text NOT NULL,
|
|
"created_by_agent_id" uuid,
|
|
"created_by_user_id" text,
|
|
"created_at" timestamptz NOT NULL DEFAULT now(),
|
|
"updated_at" timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
`));
|
|
}
|
|
|
|
async function waitForCondition(fn: () => Promise<boolean>, timeoutMs = 3_000) {
|
|
const deadline = Date.now() + timeoutMs;
|
|
while (Date.now() < deadline) {
|
|
if (await fn()) return true;
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
}
|
|
return fn();
|
|
}
|
|
|
|
describeEmbeddedPostgres("heartbeat dependency-aware queued run selection", () => {
|
|
let db!: ReturnType<typeof createDb>;
|
|
let heartbeat!: ReturnType<typeof heartbeatService>;
|
|
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
|
|
|
beforeAll(async () => {
|
|
if (!external) tempDb = await startEmbeddedPostgresTestDatabase("paperclip-heartbeat-dependency-scheduling-");
|
|
db = createDb(external ?? tempDb!.connectionString);
|
|
await db.insert(authUsers).values({ id: "responsible-user", name: "Fixture owner", email: "owner@example.test", createdAt: new Date(), updatedAt: new Date() });
|
|
heartbeat = heartbeatService(db);
|
|
await ensureIssueRelationsTable(db);
|
|
}, 20_000);
|
|
|
|
afterEach(async () => {
|
|
let idlePolls = 0;
|
|
for (let attempt = 0; attempt < 100; attempt += 1) {
|
|
const runs = await db
|
|
.select({ status: heartbeatRuns.status })
|
|
.from(heartbeatRuns);
|
|
const hasActiveRun = runs.some((run) => run.status === "queued" || run.status === "running");
|
|
if (!hasActiveRun) {
|
|
idlePolls += 1;
|
|
if (idlePolls >= 3) break;
|
|
} else {
|
|
idlePolls = 0;
|
|
}
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
}
|
|
await heartbeat.drainActiveRunExecutions();
|
|
vi.restoreAllMocks();
|
|
mockAdapterExecute.mockReset();
|
|
mockAdapterExecute.mockImplementation(async () => ({
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
summary: "Dependency-aware heartbeat test run.",
|
|
provider: "test",
|
|
model: "test-model",
|
|
}));
|
|
runningProcesses.clear();
|
|
await db.delete(environmentLeases);
|
|
await db.delete(activityLog);
|
|
await db.delete(companySkills);
|
|
await db.delete(issueComments);
|
|
await db.delete(issueDocuments);
|
|
await db.delete(documentRevisions);
|
|
await db.delete(documents);
|
|
await db.delete(issueRelations);
|
|
await db.delete(issueTreeHolds);
|
|
await db.delete(statusDecisionEffects);
|
|
await db.delete(statusDecisions);
|
|
await db.delete(workAssessments);
|
|
await db.delete(nativeRunFinalizations);
|
|
await db.delete(nativeRunResults);
|
|
await db.delete(completionContracts);
|
|
await db.delete(issues);
|
|
await db.delete(heartbeatRunEvents);
|
|
await db.delete(activityLog);
|
|
await db.delete(costEvents);
|
|
await db.delete(heartbeatRuns);
|
|
await db.delete(agentWakeupRequests);
|
|
await db.delete(agentRuntimeState);
|
|
await db.delete(agents);
|
|
await db.delete(companySkills);
|
|
await db.delete(environments);
|
|
await db.delete(workspaceOperations);
|
|
await db.delete(executionWorkspaces);
|
|
await db.delete(environmentLeases);
|
|
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
try {
|
|
await db.transaction(async (tx) => {
|
|
await tx.delete(companySkills);
|
|
await tx.delete(companyMemberships);
|
|
await tx.delete(companies);
|
|
});
|
|
break;
|
|
} catch (error) {
|
|
if (attempt === 4) throw error;
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
}
|
|
}
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await db?.delete(authUsers).where(eq(authUsers.id, "responsible-user"));
|
|
await db?.$client.end();
|
|
await tempDb?.cleanup();
|
|
});
|
|
|
|
|
|
it("keeps blocked descendants idle until their blockers resolve", async () => {
|
|
const companyId = randomUUID();
|
|
const agentId = randomUUID();
|
|
const blockerId = randomUUID();
|
|
const blockedIssueId = randomUUID();
|
|
const readyIssueId = randomUUID();
|
|
|
|
await db.insert(companies).values({
|
|
id: companyId,
|
|
name: "Paperclip",
|
|
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
|
requireBoardApprovalForNewAgents: false,
|
|
defaultResponsibleUserId: "responsible-user",
|
|
});
|
|
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "responsible-user", status: "active", membershipRole: "member" });
|
|
await db.insert(agents).values({
|
|
id: agentId,
|
|
companyId,
|
|
name: "CodexCoder",
|
|
role: "engineer",
|
|
status: "active",
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {
|
|
heartbeat: {
|
|
wakeOnDemand: true,
|
|
maxConcurrentRuns: 1,
|
|
},
|
|
},
|
|
permissions: {},
|
|
});
|
|
await db.insert(issues).values([
|
|
{
|
|
id: blockerId,
|
|
companyId,
|
|
title: "Mission 0",
|
|
status: "todo",
|
|
priority: "high",
|
|
responsibleUserId: "responsible-user",
|
|
},
|
|
{
|
|
id: blockedIssueId,
|
|
companyId,
|
|
title: "Mission 2",
|
|
status: "todo",
|
|
priority: "medium",
|
|
assigneeAgentId: agentId,
|
|
responsibleUserId: "responsible-user",
|
|
},
|
|
{
|
|
id: readyIssueId,
|
|
companyId,
|
|
title: "Mission 1",
|
|
status: "todo",
|
|
priority: "critical",
|
|
assigneeAgentId: agentId,
|
|
responsibleUserId: "responsible-user",
|
|
},
|
|
]);
|
|
await db.insert(issueRelations).values({
|
|
companyId,
|
|
issueId: blockerId,
|
|
relatedIssueId: blockedIssueId,
|
|
type: "blocks",
|
|
});
|
|
|
|
const blockedWake = await heartbeat.wakeup(agentId, {
|
|
source: "assignment",
|
|
triggerDetail: "system",
|
|
reason: "issue_assigned",
|
|
payload: { issueId: blockedIssueId },
|
|
contextSnapshot: { issueId: blockedIssueId, wakeReason: "issue_assigned" },
|
|
});
|
|
expect(blockedWake).toBeNull();
|
|
|
|
const blockedWakeRequest = await waitForCondition(async () => {
|
|
const wakeup = await db
|
|
.select({
|
|
status: agentWakeupRequests.status,
|
|
reason: agentWakeupRequests.reason,
|
|
})
|
|
.from(agentWakeupRequests)
|
|
.where(
|
|
and(
|
|
eq(agentWakeupRequests.agentId, agentId),
|
|
sql`${agentWakeupRequests.payload} ->> 'issueId' = ${blockedIssueId}`,
|
|
),
|
|
)
|
|
.orderBy(agentWakeupRequests.requestedAt)
|
|
.then((rows) => rows[0] ?? null);
|
|
return Boolean(
|
|
wakeup &&
|
|
wakeup.status === "skipped" &&
|
|
wakeup.reason === "issue_dependencies_blocked",
|
|
);
|
|
});
|
|
expect(blockedWakeRequest).toBe(true);
|
|
|
|
const blockedRunsBeforeResolution = await db
|
|
.select({ count: sql<number>`count(*)::int` })
|
|
.from(heartbeatRuns)
|
|
.where(sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${blockedIssueId}`)
|
|
.then((rows) => rows[0]?.count ?? 0);
|
|
expect(blockedRunsBeforeResolution).toBe(0);
|
|
|
|
const commentId = randomUUID();
|
|
await db.insert(issueComments).values({
|
|
id: commentId, companyId, issueId: blockedIssueId,
|
|
authorType: "user", authorUserId: "responsible-user",
|
|
body: "Explain the current dependency without starting blocked work.",
|
|
});
|
|
const interactionWake = await heartbeat.wakeup(agentId, {
|
|
source: "automation",
|
|
triggerDetail: "system",
|
|
reason: "issue_commented",
|
|
payload: { issueId: blockedIssueId, commentId },
|
|
contextSnapshot: {
|
|
issueId: blockedIssueId,
|
|
wakeReason: "issue_commented",
|
|
},
|
|
});
|
|
expect(interactionWake).not.toBeNull();
|
|
|
|
// This checks dependency interaction semantics, not provider startup speed.
|
|
// Join the admitted execution before inspecting its persisted outcome.
|
|
await heartbeat.drainActiveRunExecutions();
|
|
|
|
const interactionRun = await db
|
|
.select({
|
|
status: heartbeatRuns.status,
|
|
contextSnapshot: heartbeatRuns.contextSnapshot,
|
|
})
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, interactionWake!.id))
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
expect(interactionRun?.status).toBe("succeeded");
|
|
expect(interactionRun?.contextSnapshot).toMatchObject({
|
|
dependencyBlockedInteraction: true,
|
|
unresolvedBlockerIssueIds: [blockerId],
|
|
});
|
|
|
|
let finishReadyRun!: () => void;
|
|
const readyRunCanFinish = new Promise<void>((resolve) => {
|
|
finishReadyRun = resolve;
|
|
});
|
|
mockAdapterExecute.mockImplementationOnce(async () => {
|
|
await readyRunCanFinish;
|
|
return {
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
summary: "Ready dependency scheduling run complete.",
|
|
provider: "test",
|
|
model: "test-model",
|
|
};
|
|
});
|
|
|
|
const readyWake = await heartbeat.wakeup(agentId, {
|
|
source: "assignment",
|
|
triggerDetail: "system",
|
|
reason: "issue_assigned",
|
|
payload: { issueId: readyIssueId },
|
|
contextSnapshot: { issueId: readyIssueId, wakeReason: "issue_assigned" },
|
|
});
|
|
expect(readyWake).not.toBeNull();
|
|
await db.insert(issueComments).values({
|
|
companyId,
|
|
issueId: readyIssueId,
|
|
authorAgentId: agentId,
|
|
authorType: "agent",
|
|
createdByRunId: readyWake!.id,
|
|
body: "Ready dependency scheduling run complete.",
|
|
});
|
|
finishReadyRun();
|
|
|
|
await waitForCondition(async () => {
|
|
const run = await db
|
|
.select({ status: heartbeatRuns.status })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, readyWake!.id))
|
|
.then((rows) => rows[0] ?? null);
|
|
return run?.status === "succeeded";
|
|
});
|
|
|
|
const readyRun = await db
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, readyWake!.id))
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
expect(readyRun?.status).toBe("succeeded");
|
|
|
|
await db
|
|
.update(issues)
|
|
.set({ status: "done", updatedAt: new Date() })
|
|
.where(eq(issues.id, blockerId));
|
|
|
|
const promotedWake = await heartbeat.wakeup(agentId, {
|
|
source: "automation",
|
|
triggerDetail: "system",
|
|
reason: "issue_blockers_resolved",
|
|
payload: { issueId: blockedIssueId, resolvedBlockerIssueId: blockerId },
|
|
contextSnapshot: {
|
|
issueId: blockedIssueId,
|
|
wakeReason: "issue_blockers_resolved",
|
|
resolvedBlockerIssueId: blockerId,
|
|
},
|
|
});
|
|
expect(promotedWake).not.toBeNull();
|
|
|
|
await waitForCondition(async () => {
|
|
const run = await db
|
|
.select({ status: heartbeatRuns.status })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, promotedWake!.id))
|
|
.then((rows) => rows[0] ?? null);
|
|
return run?.status === "succeeded";
|
|
});
|
|
|
|
const promotedBlockedRun = await db
|
|
.select({
|
|
id: heartbeatRuns.id,
|
|
status: heartbeatRuns.status,
|
|
})
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, promotedWake!.id))
|
|
.then((rows) => rows[0] ?? null);
|
|
const blockedWakeRequestCount = await db
|
|
.select({ count: sql<number>`count(*)::int` })
|
|
.from(agentWakeupRequests)
|
|
.where(
|
|
and(
|
|
eq(agentWakeupRequests.agentId, agentId),
|
|
sql`${agentWakeupRequests.payload} ->> 'issueId' = ${blockedIssueId}`,
|
|
),
|
|
)
|
|
.then((rows) => rows[0]?.count ?? 0);
|
|
|
|
expect(promotedBlockedRun?.status).toBe("succeeded");
|
|
expect(blockedWakeRequestCount).toBeGreaterThanOrEqual(2);
|
|
|
|
const noActiveRuns = await waitForCondition(async () => {
|
|
const rows = await db
|
|
.select({ status: heartbeatRuns.status })
|
|
.from(heartbeatRuns);
|
|
return rows.every((run) => run.status !== "queued" && run.status !== "running");
|
|
}, 10_000);
|
|
expect(noActiveRuns).toBe(true);
|
|
});
|
|
|
|
it("admits an issue_blocker_stalled wake while a blocker is unresolved", async () => {
|
|
// The waiter's blocker stalled on a board-owned recovery action. Parking
|
|
// this wake until the blocker resolves would hide the stall again.
|
|
const companyId = randomUUID();
|
|
const agentId = randomUUID();
|
|
const blockerId = randomUUID();
|
|
const dependentId = randomUUID();
|
|
await db.insert(companies).values({
|
|
id: companyId, name: "Paperclip", issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
|
requireBoardApprovalForNewAgents: false, defaultResponsibleUserId: "responsible-user",
|
|
});
|
|
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "responsible-user", status: "active", membershipRole: "member" });
|
|
await db.insert(agents).values({
|
|
id: agentId, companyId, name: "CodexCoder", role: "engineer", status: "active", adapterType: "codex_local",
|
|
adapterConfig: {}, runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } }, permissions: {},
|
|
});
|
|
await db.insert(issues).values([
|
|
{ id: blockerId, companyId, title: "Stalled blocker", status: "blocked", priority: "high", responsibleUserId: "responsible-user" },
|
|
{ id: dependentId, companyId, title: "Waiting dependent", status: "blocked", priority: "medium", assigneeAgentId: agentId,
|
|
responsibleUserId: "responsible-user" },
|
|
]);
|
|
await db.insert(issueRelations).values({ companyId, issueId: blockerId, relatedIssueId: dependentId, type: "blocks" });
|
|
const [action] = await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: blockerId, kind: "run_recovery",
|
|
status: "resolved", outcome: "blocked", ownerType: "board", cause: "native_session_retry_exhausted",
|
|
fingerprint: "stall", nextAction: "Retry", resolvedAt: new Date() }).returning();
|
|
const stallWake = (requestedByActorType: "system" | "agent") => heartbeat.wakeup(agentId, {
|
|
source: "automation",
|
|
triggerDetail: "system",
|
|
reason: "issue_blocker_stalled",
|
|
payload: { issueId: dependentId, stalledIssueId: blockerId },
|
|
idempotencyKey: `issue_blocker_stalled:${dependentId}:${blockerId}:${action.id}:${requestedByActorType}`,
|
|
requestedByActorType,
|
|
requestedByActorId: requestedByActorType === "system" ? "issue-blocker-stall" : agentId,
|
|
contextSnapshot: { issueId: dependentId, wakeReason: "issue_blocker_stalled",
|
|
blockerStall: { stalledIssueId: blockerId, relation: "blocker", recoveryAction: { id: action.id } } },
|
|
});
|
|
|
|
// The reason string alone is not trusted: an agent cannot use it to skip the blocker gate.
|
|
expect(await stallWake("agent")).toBeNull();
|
|
|
|
const stalledWake = await stallWake("system");
|
|
expect(stalledWake).not.toBeNull();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
const [run] = await db.select({ status: heartbeatRuns.status, contextSnapshot: heartbeatRuns.contextSnapshot })
|
|
.from(heartbeatRuns).where(eq(heartbeatRuns.id, stalledWake!.id));
|
|
expect(run?.status).toBe("succeeded");
|
|
expect(run?.contextSnapshot).toMatchObject({ dependencyBlockedInteraction: true, unresolvedBlockerIssueIds: [blockerId] });
|
|
|
|
// A resource wait replaces the run with a server-created retry that keeps
|
|
// the stall context but not the wake reason. The retry gate still admits it.
|
|
const retryGate = async (contextSnapshot: Record<string, unknown>) => {
|
|
const [retry] = await db.insert(heartbeatRuns).values({ companyId, agentId, invocationSource: "automation",
|
|
status: "scheduled_retry", scheduledRetryAt: new Date(), scheduledRetryReason: "transient_failure",
|
|
retryOfRunId: stalledWake!.id, contextSnapshot }).returning();
|
|
return createPostgresRunDispatchAdapter(db).evaluateScheduledRetryGate({ companyId, runId: retry.id,
|
|
retryReasonOverride: "transient_failure", now: new Date() });
|
|
};
|
|
const replacement: Record<string, unknown> = { ...(run!.contextSnapshot as Record<string, unknown>),
|
|
wakeReason: "bounded_transient_heartbeat_retry", retryReason: "transient_failure", retryOfRunId: stalledWake!.id };
|
|
expect(await retryGate(replacement)).toMatchObject({ allowed: true });
|
|
const { blockerStall: _stall, ...withoutStall } = replacement;
|
|
expect(await retryGate(withoutStall)).toMatchObject({ allowed: false, errorCode: "issue_dependencies_blocked" });
|
|
// Once the stall's action is no longer current, the retry waits for the blocker like any other.
|
|
await db.update(issueRecoveryActions).set({ outcome: "restored" }).where(eq(issueRecoveryActions.id, action.id));
|
|
expect(await retryGate(replacement)).toMatchObject({ allowed: false, errorCode: "issue_dependencies_blocked" });
|
|
});
|
|
|
|
it("defers issue_blockers_resolved as a follow-up when the same issue is already running", async () => {
|
|
const companyId = randomUUID();
|
|
const agentId = randomUUID();
|
|
const blockerId = randomUUID();
|
|
const blockedIssueId = randomUUID();
|
|
const activeRunId = randomUUID();
|
|
|
|
await db.insert(companies).values({
|
|
id: companyId,
|
|
name: "Paperclip",
|
|
issuePrefix: `D${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
|
requireBoardApprovalForNewAgents: false,
|
|
});
|
|
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "responsible-user", status: "active", membershipRole: "member" });
|
|
await db.insert(agents).values({
|
|
id: agentId,
|
|
companyId,
|
|
name: "CodexCoder",
|
|
role: "engineer",
|
|
status: "active",
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {
|
|
heartbeat: {
|
|
wakeOnDemand: true,
|
|
maxConcurrentRuns: 1,
|
|
},
|
|
},
|
|
permissions: {},
|
|
});
|
|
await db.insert(heartbeatRuns).values({
|
|
id: activeRunId,
|
|
companyId,
|
|
agentId,
|
|
status: "running",
|
|
invocationSource: "on_demand",
|
|
contextSnapshot: {
|
|
issueId: blockedIssueId,
|
|
wakeReason: "manual_test_active_run",
|
|
},
|
|
});
|
|
await db.insert(issues).values([
|
|
{
|
|
id: blockerId,
|
|
companyId,
|
|
title: "Completed prerequisite",
|
|
status: "done",
|
|
priority: "medium",
|
|
},
|
|
{
|
|
id: blockedIssueId,
|
|
companyId,
|
|
title: "Blocked dependent",
|
|
status: "blocked",
|
|
priority: "medium",
|
|
assigneeAgentId: agentId,
|
|
executionRunId: activeRunId,
|
|
executionLockedAt: new Date(),
|
|
},
|
|
]);
|
|
await db.insert(issueRelations).values({
|
|
companyId,
|
|
issueId: blockerId,
|
|
relatedIssueId: blockedIssueId,
|
|
type: "blocks",
|
|
});
|
|
runningProcesses.set(activeRunId, {
|
|
child: {} as import("node:child_process").ChildProcess,
|
|
graceSec: 1,
|
|
processGroupId: null,
|
|
});
|
|
|
|
const idempotencyKey = `issue_blockers_resolved:${blockedIssueId}:${blockerId}`;
|
|
const wake = await heartbeat.wakeup(agentId, {
|
|
source: "automation",
|
|
triggerDetail: "system",
|
|
reason: "issue_blockers_resolved",
|
|
payload: {
|
|
issueId: blockedIssueId,
|
|
resolvedBlockerIssueId: blockerId,
|
|
},
|
|
idempotencyKey,
|
|
contextSnapshot: {
|
|
issueId: blockedIssueId,
|
|
wakeReason: "issue_blockers_resolved",
|
|
resolvedBlockerIssueId: blockerId,
|
|
},
|
|
});
|
|
|
|
expect(wake).toBeNull();
|
|
|
|
const wakeRequests = await db
|
|
.select({
|
|
status: agentWakeupRequests.status,
|
|
reason: agentWakeupRequests.reason,
|
|
idempotencyKey: agentWakeupRequests.idempotencyKey,
|
|
runId: agentWakeupRequests.runId,
|
|
})
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.idempotencyKey, idempotencyKey));
|
|
|
|
expect(wakeRequests).toEqual([
|
|
expect.objectContaining({
|
|
status: "deferred_issue_execution",
|
|
reason: "issue_execution_deferred",
|
|
idempotencyKey,
|
|
runId: null,
|
|
}),
|
|
]);
|
|
|
|
runningProcesses.delete(activeRunId);
|
|
await db
|
|
.update(heartbeatRuns)
|
|
.set({ status: "succeeded", finishedAt: new Date(), updatedAt: new Date() })
|
|
.where(eq(heartbeatRuns.id, activeRunId));
|
|
});
|
|
|
|
it("honors maxConcurrentRuns 1 by leaving a second assignment wake queued", async () => {
|
|
const companyId = randomUUID();
|
|
const agentId = randomUUID();
|
|
const firstIssueId = randomUUID();
|
|
const secondIssueId = randomUUID();
|
|
let finishFirstRun!: () => void;
|
|
const firstRunFinished = new Promise<void>((resolve) => {
|
|
finishFirstRun = resolve;
|
|
});
|
|
|
|
mockAdapterExecute.mockImplementationOnce(async () => {
|
|
await firstRunFinished;
|
|
return {
|
|
exitCode: 0,
|
|
signal: null,
|
|
timedOut: false,
|
|
errorMessage: null,
|
|
summary: "First assignment run completed.",
|
|
provider: "test",
|
|
model: "test-model",
|
|
};
|
|
});
|
|
|
|
await db.insert(companies).values({
|
|
id: companyId,
|
|
name: "Paperclip",
|
|
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
|
requireBoardApprovalForNewAgents: false,
|
|
defaultResponsibleUserId: "responsible-user",
|
|
});
|
|
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "responsible-user", status: "active", membershipRole: "member" });
|
|
await db.insert(agents).values({
|
|
id: agentId,
|
|
companyId,
|
|
name: "CodexCoder",
|
|
role: "engineer",
|
|
status: "active",
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {
|
|
heartbeat: {
|
|
wakeOnDemand: true,
|
|
maxConcurrentRuns: 1,
|
|
},
|
|
},
|
|
permissions: {},
|
|
});
|
|
await db.insert(issues).values([
|
|
{
|
|
id: firstIssueId,
|
|
companyId,
|
|
title: "First assignment",
|
|
status: "todo",
|
|
priority: "high",
|
|
assigneeAgentId: agentId,
|
|
responsibleUserId: "responsible-user",
|
|
},
|
|
{
|
|
id: secondIssueId,
|
|
companyId,
|
|
title: "Second assignment",
|
|
status: "todo",
|
|
priority: "high",
|
|
assigneeAgentId: agentId,
|
|
responsibleUserId: "responsible-user",
|
|
},
|
|
]);
|
|
|
|
try {
|
|
const firstWake = await heartbeat.wakeup(agentId, {
|
|
source: "assignment",
|
|
triggerDetail: "system",
|
|
reason: "issue_assigned",
|
|
payload: { issueId: firstIssueId },
|
|
contextSnapshot: { issueId: firstIssueId, wakeReason: "issue_assigned" },
|
|
});
|
|
expect(firstWake).not.toBeNull();
|
|
await db.insert(issueComments).values({
|
|
companyId,
|
|
issueId: firstIssueId,
|
|
authorAgentId: agentId,
|
|
authorType: "agent",
|
|
createdByRunId: firstWake!.id,
|
|
body: "First assignment run completed.",
|
|
});
|
|
|
|
const firstRunStarted = await waitForCondition(async () => {
|
|
const run = await db
|
|
.select({ status: heartbeatRuns.status })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, firstWake!.id))
|
|
.then((rows) => rows[0] ?? null);
|
|
return run?.status === "running";
|
|
});
|
|
expect(firstRunStarted).toBe(true);
|
|
const firstAdapterStarted = await waitForCondition(async () => mockAdapterExecute.mock.calls.length === 1, 30_000);
|
|
expect(firstAdapterStarted).toBe(true);
|
|
|
|
const secondWake = await heartbeat.wakeup(agentId, {
|
|
source: "assignment",
|
|
triggerDetail: "system",
|
|
reason: "issue_assigned",
|
|
payload: { issueId: secondIssueId },
|
|
contextSnapshot: { issueId: secondIssueId, wakeReason: "issue_assigned" },
|
|
});
|
|
expect(secondWake).not.toBeNull();
|
|
await db.insert(issueComments).values({
|
|
companyId,
|
|
issueId: secondIssueId,
|
|
authorAgentId: agentId,
|
|
authorType: "agent",
|
|
createdByRunId: secondWake!.id,
|
|
body: "Second assignment run completed.",
|
|
});
|
|
|
|
const secondRunWhileFirstRunning = await db
|
|
.select({ status: heartbeatRuns.status })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, secondWake!.id))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(secondRunWhileFirstRunning?.status).toBe("queued");
|
|
expect(mockAdapterExecute).toHaveBeenCalledTimes(1);
|
|
|
|
finishFirstRun();
|
|
|
|
const firstRunSucceeded = await waitForCondition(async () => {
|
|
const run = await db
|
|
.select({ status: heartbeatRuns.status })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, firstWake!.id))
|
|
.then((rows) => rows[0] ?? null);
|
|
return run?.status === "succeeded";
|
|
});
|
|
expect(firstRunSucceeded).toBe(true);
|
|
|
|
const secondRunSucceeded = await waitForCondition(async () => {
|
|
const run = await db
|
|
.select({ status: heartbeatRuns.status })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, secondWake!.id))
|
|
.then((rows) => rows[0] ?? null);
|
|
return run?.status === "succeeded";
|
|
}, 10_000);
|
|
expect(secondRunSucceeded).toBe(true);
|
|
expect(mockAdapterExecute.mock.calls.length).toBeGreaterThanOrEqual(2);
|
|
} finally {
|
|
finishFirstRun();
|
|
}
|
|
}, 40_000);
|
|
|
|
it("cancels stale queued runs when issue blockers are still unresolved", async () => {
|
|
const companyId = randomUUID();
|
|
const agentId = randomUUID();
|
|
const blockerId = randomUUID();
|
|
const blockedIssueId = randomUUID();
|
|
const readyIssueId = randomUUID();
|
|
const blockedWakeupRequestId = randomUUID();
|
|
const readyWakeupRequestId = randomUUID();
|
|
const blockedRunId = randomUUID();
|
|
const readyRunId = randomUUID();
|
|
|
|
await db.insert(companies).values({
|
|
id: companyId,
|
|
name: "Paperclip",
|
|
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
|
requireBoardApprovalForNewAgents: false,
|
|
defaultResponsibleUserId: "responsible-user",
|
|
});
|
|
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "responsible-user", status: "active", membershipRole: "member" });
|
|
await db.insert(agents).values({
|
|
id: agentId,
|
|
companyId,
|
|
name: "QAChecker",
|
|
role: "qa",
|
|
status: "active",
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {
|
|
heartbeat: {
|
|
wakeOnDemand: true,
|
|
maxConcurrentRuns: 2,
|
|
},
|
|
},
|
|
permissions: {},
|
|
});
|
|
await db.insert(issues).values([
|
|
{
|
|
id: blockerId,
|
|
companyId,
|
|
title: "Security review",
|
|
status: "blocked",
|
|
priority: "high",
|
|
responsibleUserId: "responsible-user",
|
|
},
|
|
{
|
|
id: blockedIssueId,
|
|
companyId,
|
|
title: "QA validation",
|
|
status: "blocked",
|
|
priority: "medium",
|
|
assigneeAgentId: agentId,
|
|
responsibleUserId: "responsible-user",
|
|
},
|
|
{
|
|
id: readyIssueId,
|
|
companyId,
|
|
title: "Ready QA task",
|
|
status: "todo",
|
|
priority: "low",
|
|
assigneeAgentId: agentId,
|
|
responsibleUserId: "responsible-user",
|
|
},
|
|
]);
|
|
await db.insert(issueRelations).values({
|
|
companyId,
|
|
issueId: blockerId,
|
|
relatedIssueId: blockedIssueId,
|
|
type: "blocks",
|
|
});
|
|
await db.insert(agentWakeupRequests).values([
|
|
{
|
|
id: blockedWakeupRequestId,
|
|
companyId,
|
|
agentId,
|
|
source: "automation",
|
|
triggerDetail: "system",
|
|
reason: "transient_failure_retry",
|
|
payload: { issueId: blockedIssueId },
|
|
status: "queued",
|
|
},
|
|
{
|
|
id: readyWakeupRequestId,
|
|
companyId,
|
|
agentId,
|
|
source: "assignment",
|
|
triggerDetail: "system",
|
|
reason: "issue_assigned",
|
|
payload: { issueId: readyIssueId },
|
|
status: "queued",
|
|
},
|
|
]);
|
|
await db.insert(heartbeatRuns).values([
|
|
{
|
|
id: blockedRunId,
|
|
companyId,
|
|
agentId,
|
|
invocationSource: "automation",
|
|
triggerDetail: "system",
|
|
status: "queued",
|
|
wakeupRequestId: blockedWakeupRequestId,
|
|
contextSnapshot: {
|
|
issueId: blockedIssueId,
|
|
wakeReason: "transient_failure_retry",
|
|
},
|
|
},
|
|
{
|
|
id: readyRunId,
|
|
companyId,
|
|
agentId,
|
|
invocationSource: "assignment",
|
|
triggerDetail: "system",
|
|
status: "queued",
|
|
wakeupRequestId: readyWakeupRequestId,
|
|
contextSnapshot: {
|
|
issueId: readyIssueId,
|
|
wakeReason: "issue_assigned",
|
|
},
|
|
},
|
|
]);
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({ runId: blockedRunId })
|
|
.where(eq(agentWakeupRequests.id, blockedWakeupRequestId));
|
|
await db
|
|
.update(agentWakeupRequests)
|
|
.set({ runId: readyRunId })
|
|
.where(eq(agentWakeupRequests.id, readyWakeupRequestId));
|
|
await db.insert(issueComments).values({
|
|
companyId,
|
|
issueId: readyIssueId,
|
|
authorAgentId: agentId,
|
|
authorType: "agent",
|
|
createdByRunId: readyRunId,
|
|
body: "Ready queued run completed.",
|
|
});
|
|
await db
|
|
.update(issues)
|
|
.set({
|
|
executionRunId: blockedRunId,
|
|
executionAgentNameKey: "qa-checker",
|
|
executionLockedAt: new Date(),
|
|
})
|
|
.where(eq(issues.id, blockedIssueId));
|
|
|
|
mockAdapterExecute.mockImplementationOnce(async () => {
|
|
await db.update(issues).set({ status: "done" }).where(eq(issues.id, readyIssueId));
|
|
return { exitCode: 0, signal: null, timedOut: false, errorMessage: null,
|
|
summary: "Ready queued run completed.", provider: "test", model: "test-model" };
|
|
});
|
|
await heartbeat.resumeQueuedRuns();
|
|
|
|
expect(await waitForCondition(async () => {
|
|
const [ready] = await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns).where(eq(heartbeatRuns.id, readyRunId));
|
|
return ready?.status === "succeeded";
|
|
}, 30_000)).toBe(true);
|
|
await heartbeat.drainActiveRunExecutions();
|
|
|
|
const [blockedRun, blockedWakeup, blockedIssue, readyRun] = await Promise.all([
|
|
db
|
|
.select({
|
|
status: heartbeatRuns.status,
|
|
errorCode: heartbeatRuns.errorCode,
|
|
finishedAt: heartbeatRuns.finishedAt,
|
|
resultJson: heartbeatRuns.resultJson,
|
|
})
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, blockedRunId))
|
|
.then((rows) => rows[0] ?? null),
|
|
db
|
|
.select({
|
|
status: agentWakeupRequests.status,
|
|
error: agentWakeupRequests.error,
|
|
})
|
|
.from(agentWakeupRequests)
|
|
.where(eq(agentWakeupRequests.id, blockedWakeupRequestId))
|
|
.then((rows) => rows[0] ?? null),
|
|
db
|
|
.select({
|
|
executionRunId: issues.executionRunId,
|
|
executionAgentNameKey: issues.executionAgentNameKey,
|
|
executionLockedAt: issues.executionLockedAt,
|
|
})
|
|
.from(issues)
|
|
.where(eq(issues.id, blockedIssueId))
|
|
.then((rows) => rows[0] ?? null),
|
|
db
|
|
.select({ status: heartbeatRuns.status })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, readyRunId))
|
|
.then((rows) => rows[0] ?? null),
|
|
]);
|
|
|
|
expect(blockedRun?.status).toBe("cancelled");
|
|
expect(blockedRun?.errorCode).toBe("issue_dependencies_blocked");
|
|
expect(blockedRun?.finishedAt).toBeTruthy();
|
|
expect(blockedRun?.resultJson).toMatchObject({ stopReason: "issue_dependencies_blocked" });
|
|
expect(blockedRun?.resultJson).toMatchObject({ cancellation: { source: "control_plane", expected: true } });
|
|
const [waitingIssue] = await db.select().from(issues).where(eq(issues.id, blockedIssueId));
|
|
expect(await taskInterruptionPresentation(db, waitingIssue!)).toMatchObject({ state: "resolved", canRetry: false });
|
|
await db.update(heartbeatRuns).set({ resultJson: { ...blockedRun!.resultJson, timeoutFired: true } })
|
|
.where(eq(heartbeatRuns.id, blockedRunId));
|
|
expect(await taskInterruptionPresentation(db, waitingIssue!)).toMatchObject({ state: "failed", canRetry: true });
|
|
await db.update(heartbeatRuns).set({ resultJson: blockedRun!.resultJson }).where(eq(heartbeatRuns.id, blockedRunId));
|
|
expect(blockedWakeup?.status).toBe("skipped");
|
|
expect(blockedWakeup?.error).toContain("dependencies are still blocked");
|
|
expect(blockedIssue).toMatchObject({
|
|
executionRunId: null,
|
|
executionAgentNameKey: null,
|
|
executionLockedAt: null,
|
|
});
|
|
expect(readyRun?.status).toBe("succeeded");
|
|
expect(mockAdapterExecute).toHaveBeenCalledTimes(1);
|
|
}, 40_000);
|
|
|
|
it("suppresses normal wakeups while allowing comment interaction wakes under a pause hold", async () => {
|
|
const companyId = randomUUID();
|
|
const agentId = randomUUID();
|
|
const rootIssueId = randomUUID();
|
|
const issueChain = Array.from({ length: 17 }, () => randomUUID());
|
|
const deepDescendantIssueId = issueChain.at(-1)!;
|
|
|
|
await db.insert(companies).values({
|
|
id: companyId,
|
|
name: "Paperclip",
|
|
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
|
requireBoardApprovalForNewAgents: false,
|
|
defaultResponsibleUserId: "responsible-user",
|
|
});
|
|
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "responsible-user", status: "active", membershipRole: "member" });
|
|
await db.insert(agents).values({
|
|
id: agentId,
|
|
companyId,
|
|
name: "SecurityEngineer",
|
|
role: "engineer",
|
|
status: "active",
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {
|
|
heartbeat: {
|
|
wakeOnDemand: true,
|
|
maxConcurrentRuns: 1,
|
|
},
|
|
},
|
|
permissions: {},
|
|
});
|
|
await db.insert(issues).values([
|
|
{
|
|
id: rootIssueId,
|
|
companyId,
|
|
title: "Paused root",
|
|
status: "todo",
|
|
priority: "medium",
|
|
assigneeAgentId: agentId,
|
|
responsibleUserId: "responsible-user",
|
|
},
|
|
...issueChain.map((issueId, index) => ({
|
|
id: issueId,
|
|
companyId,
|
|
parentId: index === 0 ? rootIssueId : issueChain[index - 1],
|
|
title: `Paused desc ${index + 1}`,
|
|
status: "todo",
|
|
priority: "medium",
|
|
assigneeAgentId: agentId,
|
|
responsibleUserId: "responsible-user",
|
|
})),
|
|
]);
|
|
const [hold] = await db
|
|
.insert(issueTreeHolds)
|
|
.values({
|
|
companyId,
|
|
rootIssueId,
|
|
mode: "pause",
|
|
status: "active",
|
|
reason: "security test hold",
|
|
releasePolicy: { strategy: "manual" },
|
|
})
|
|
.returning();
|
|
|
|
const blockedWake = await heartbeat.wakeup(agentId, {
|
|
source: "automation",
|
|
triggerDetail: "system",
|
|
reason: "issue_blockers_resolved",
|
|
payload: { issueId: deepDescendantIssueId },
|
|
contextSnapshot: { issueId: deepDescendantIssueId, wakeReason: "issue_blockers_resolved" },
|
|
});
|
|
|
|
expect(blockedWake).toBeNull();
|
|
const skippedWake = await db
|
|
.select({
|
|
status: agentWakeupRequests.status,
|
|
reason: agentWakeupRequests.reason,
|
|
})
|
|
.from(agentWakeupRequests)
|
|
.where(sql`${agentWakeupRequests.payload} ->> 'issueId' = ${deepDescendantIssueId}`)
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(skippedWake).toMatchObject({ status: "skipped", reason: "issue_tree_hold_active" });
|
|
|
|
const childCommentId = randomUUID();
|
|
await db.insert(issueComments).values({
|
|
id: childCommentId,
|
|
companyId,
|
|
issueId: deepDescendantIssueId,
|
|
authorUserId: "board-user",
|
|
body: "Please respond while this hold is active.",
|
|
});
|
|
|
|
const forgedChildCommentWake = await heartbeat.wakeup(agentId, {
|
|
source: "on_demand",
|
|
triggerDetail: "manual",
|
|
reason: "issue_commented",
|
|
payload: { issueId: deepDescendantIssueId, commentId: childCommentId },
|
|
requestedByActorType: "agent",
|
|
requestedByActorId: agentId,
|
|
});
|
|
expect(forgedChildCommentWake).toBeNull();
|
|
|
|
const childCommentWake = await heartbeat.wakeup(agentId, {
|
|
source: "automation",
|
|
triggerDetail: "system",
|
|
reason: "issue_commented",
|
|
payload: { issueId: deepDescendantIssueId, commentId: childCommentId },
|
|
requestedByActorType: "user",
|
|
requestedByActorId: "board-user",
|
|
contextSnapshot: {
|
|
issueId: deepDescendantIssueId,
|
|
commentId: childCommentId,
|
|
wakeCommentId: childCommentId,
|
|
wakeReason: "issue_commented",
|
|
source: "issue.comment",
|
|
},
|
|
});
|
|
|
|
expect(childCommentWake).not.toBeNull();
|
|
const childRun = await db
|
|
.select({ contextSnapshot: heartbeatRuns.contextSnapshot })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, childCommentWake!.id))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(childRun?.contextSnapshot).toMatchObject({
|
|
treeHoldInteraction: true,
|
|
activeTreeHold: {
|
|
holdId: hold.id,
|
|
rootIssueId,
|
|
mode: "pause",
|
|
interaction: true,
|
|
},
|
|
});
|
|
});
|
|
|
|
it("allows comment interaction wakes when a legacy hold has a full_pause note", async () => {
|
|
const companyId = randomUUID();
|
|
const agentId = randomUUID();
|
|
const rootIssueId = randomUUID();
|
|
|
|
await db.insert(companies).values({
|
|
id: companyId,
|
|
name: "Paperclip",
|
|
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
|
|
requireBoardApprovalForNewAgents: false,
|
|
defaultResponsibleUserId: "responsible-user",
|
|
});
|
|
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "responsible-user", status: "active", membershipRole: "member" });
|
|
await db.insert(agents).values({
|
|
id: agentId,
|
|
companyId,
|
|
name: "SecurityEngineer",
|
|
role: "engineer",
|
|
status: "active",
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {
|
|
heartbeat: {
|
|
wakeOnDemand: true,
|
|
maxConcurrentRuns: 1,
|
|
},
|
|
},
|
|
permissions: {},
|
|
});
|
|
await db.insert(issues).values({
|
|
id: rootIssueId,
|
|
companyId,
|
|
title: "Paused root",
|
|
status: "todo",
|
|
priority: "medium",
|
|
assigneeAgentId: agentId,
|
|
responsibleUserId: "responsible-user",
|
|
});
|
|
await db.insert(issueTreeHolds).values({
|
|
companyId,
|
|
rootIssueId,
|
|
mode: "pause",
|
|
status: "active",
|
|
reason: "full pause",
|
|
releasePolicy: { strategy: "manual", note: "full_pause" },
|
|
});
|
|
|
|
const rootCommentId = randomUUID();
|
|
await db.insert(issueComments).values({
|
|
id: rootCommentId,
|
|
companyId,
|
|
issueId: rootIssueId,
|
|
authorUserId: "board-user",
|
|
body: "Please respond while this hold is active.",
|
|
});
|
|
|
|
const rootCommentWake = await heartbeat.wakeup(agentId, {
|
|
source: "automation",
|
|
triggerDetail: "system",
|
|
reason: "issue_commented",
|
|
payload: { issueId: rootIssueId, commentId: rootCommentId },
|
|
requestedByActorType: "user",
|
|
requestedByActorId: "board-user",
|
|
contextSnapshot: {
|
|
issueId: rootIssueId,
|
|
commentId: rootCommentId,
|
|
wakeCommentId: rootCommentId,
|
|
wakeReason: "issue_commented",
|
|
source: "issue.comment",
|
|
},
|
|
});
|
|
|
|
expect(rootCommentWake).not.toBeNull();
|
|
const rootRun = await db
|
|
.select({ contextSnapshot: heartbeatRuns.contextSnapshot })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, rootCommentWake!.id))
|
|
.then((rows) => rows[0] ?? null);
|
|
expect(rootRun?.contextSnapshot).toMatchObject({
|
|
treeHoldInteraction: true,
|
|
activeTreeHold: {
|
|
rootIssueId,
|
|
mode: "pause",
|
|
interaction: true,
|
|
},
|
|
});
|
|
});
|
|
});
|