Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
CREATE UNIQUE INDEX IF NOT EXISTS "issues_open_routine_origin_uq" ON "issues" USING btree ("company_id","origin_kind","origin_id") WHERE "issues"."origin_kind" = 'routine_execution'
and "issues"."origin_id" is not null
and "issues"."hidden_at" is null
and "issues"."status" in ('backlog', 'todo', 'in_progress', 'in_review', 'blocked');
9 changes: 8 additions & 1 deletion packages/db/src/migrations/meta/_journal.json
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,13 @@
"when": 1776084034244,
"tag": "0056_spooky_ultragirl",
"breakpoints": true
},
{
"idx": 57,
"version": "7",
"when": 1776375450733,
"tag": "0057_open_routine_origin_uniqueness",
"breakpoints": true
}
]
}
}
8 changes: 8 additions & 0 deletions packages/db/src/schema/issues.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,5 +90,13 @@ export const issues = pgTable(
and ${table.executionRunId} is not null
and ${table.status} in ('backlog', 'todo', 'in_progress', 'in_review', 'blocked')`,
),
openRoutineOriginIdx: uniqueIndex("issues_open_routine_origin_uq")
.on(table.companyId, table.originKind, table.originId)
.where(
sql`${table.originKind} = 'routine_execution'
and ${table.originId} is not null
and ${table.hiddenAt} is null
and ${table.status} in ('backlog', 'todo', 'in_progress', 'in_review', 'blocked')`,
),
}),
);
24 changes: 24 additions & 0 deletions server/src/__tests__/heartbeat-process-recovery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -650,6 +650,30 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
expect(comments[0]?.body).toContain("Latest retry failure: `process_lost` - run failed before issue advanced.");
});

it("does not auto-block in-progress work when the latest continuation retry already succeeded", async () => {
const { issueId, runId } = await seedStrandedIssueFixture({
status: "in_progress",
runStatus: "succeeded",
retryReason: "issue_continuation_needed",
});
const heartbeat = heartbeatService(db);

const result = await heartbeat.reconcileStrandedAssignedIssues();
expect(result.continuationRequeued).toBe(0);
expect(result.escalated).toBe(0);
expect(result.issueIds).toEqual([]);

const issue = await db.select().from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null);
expect(issue?.status).toBe("in_progress");

const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, issueId));
expect(comments).toHaveLength(0);

const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
expect(runs).toHaveLength(1);
expect(runs[0]?.status).toBe("succeeded");
});

it("does not reconcile user-assigned work through the agent stranded-work recovery path", async () => {
const { issueId, runId } = await seedStrandedIssueFixture({
status: "todo",
Expand Down
62 changes: 62 additions & 0 deletions server/src/__tests__/routines-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,68 @@ describeEmbeddedPostgres("routine service live-execution coalescing", () => {
expect(routineIssues[0]?.id).toBe(previousIssue.id);
});

it("repairs stale execution locks after duplicate-key conflicts and creates a fresh issue", async () => {
const { agentId, companyId, issueSvc, routine, svc } = await seedFixture();
const previousRunId = randomUUID();
const staleHeartbeatRunId = randomUUID();
const previousIssue = await issueSvc.create(companyId, {
projectId: routine.projectId,
title: routine.title,
description: routine.description,
status: "todo",
priority: routine.priority,
assigneeAgentId: routine.assigneeAgentId,
originKind: "routine_execution",
originId: routine.id,
originRunId: previousRunId,
});

await db.insert(routineRuns).values({
id: previousRunId,
companyId,
routineId: routine.id,
triggerId: null,
source: "manual",
status: "issue_created",
triggeredAt: new Date("2026-03-20T12:00:00.000Z"),
linkedIssueId: previousIssue.id,
});

await db.insert(heartbeatRuns).values({
id: staleHeartbeatRunId,
companyId,
agentId,
invocationSource: "assignment",
triggerDetail: "system",
status: "succeeded",
contextSnapshot: { issueId: previousIssue.id },
startedAt: new Date("2026-03-20T12:01:00.000Z"),
finishedAt: new Date("2026-03-20T12:03:00.000Z"),
});

await db
.update(issues)
.set({
executionRunId: staleHeartbeatRunId,
executionLockedAt: new Date("2026-03-20T12:01:00.000Z"),
})
.where(eq(issues.id, previousIssue.id));

const run = await svc.runRoutine(routine.id, { source: "manual" });

expect(run.status).toBe("issue_created");
expect(run.linkedIssueId).toBeTruthy();
expect(run.linkedIssueId).not.toBe(previousIssue.id);

const refreshedPreviousIssue = await db
.select({ executionRunId: issues.executionRunId })
.from(issues)
.where(eq(issues.id, previousIssue.id))
.then((rows) => rows[0] ?? null);

expect(refreshedPreviousIssue?.executionRunId).toBeNull();
});

it("interpolates routine variables into the execution issue and stores resolved values", async () => {
const { companyId, agentId, projectId, svc } = await seedFixture();
const variableRoutine = await svc.create(
Expand Down
20 changes: 20 additions & 0 deletions server/src/routes/issues.ts
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,25 @@ export function issueRoutes(
throw unauthorized();
}

function canCreateIssuesLegacy(agent: { permissions: Record<string, unknown> | null | undefined; role: string }) {
if (agent.role === "ceo") return true;
if (!agent.permissions || typeof agent.permissions !== "object") return false;
const permissions = agent.permissions as Record<string, unknown>;
return Boolean(permissions.canCreateIssues || permissions.canCreateAgents);
}

async function assertCanCreateIssues(req: Request, companyId: string) {
assertCompanyAccess(req, companyId);
if (req.actor.type === "board") return;
if (req.actor.type === "agent") {
if (!req.actor.agentId) throw forbidden("Agent authentication required");
const actorAgent = await agentsSvc.getById(req.actor.agentId);
if (actorAgent && actorAgent.companyId === companyId && canCreateIssuesLegacy(actorAgent)) return;
throw forbidden("Missing permission: issues:create");
}
throw unauthorized();
Comment thread
DeadlySilent marked this conversation as resolved.
}

function requireAgentRunId(req: Request, res: Response) {
if (req.actor.type !== "agent") return null;
const runId = req.actor.runId?.trim();
Expand Down Expand Up @@ -1329,6 +1348,7 @@ export function issueRoutes(
router.post("/companies/:companyId/issues", validate(createIssueSchema), async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
Comment thread
DeadlySilent marked this conversation as resolved.
Outdated
await assertCanCreateIssues(req, companyId);
assertNoAgentHostWorkspaceCommandMutation(req, collectIssueWorkspaceCommandPaths(req.body));
if (req.body.assigneeAgentId || req.body.assigneeUserId) {
await assertCanAssignTasks(req, companyId);
Expand Down
5 changes: 5 additions & 0 deletions server/src/services/heartbeat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3083,6 +3083,11 @@ export function heartbeatService(db: Db) {
continue;
}

if (latestRun?.status === "succeeded") {
result.skipped += 1;
continue;
}

if (latestRetryReason === "issue_continuation_needed") {
const failureSummary = summarizeRunFailureForIssueComment(latestRun);
const updated = await escalateStrandedAssignedIssue({
Expand Down
Loading