Files
PaperClipAI/server/src/services/issue-tree-control.ts
T
DottaandClaude Opus 5.5 b4fa1c7fb1 perf(recovery): load changed rows, not every task, for company hints, boots and reconnects (#21872)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The task recovery queues (stranded assignments, assigned-work
invariant, resolved dependencies, stale issue locks) check tasks to find
work that has no live run and no queued wake
> - A plain company hint, or an unscoped `"*"` reload, made each queue
load and check every eligible task of the company, at about 22 read-only
statements per task
> - Many writers send that hint (issue creation, documents, budgets,
work intents, agent status changes), every server boot reloads every
task, and the notification connection publishes a `"*"` reload each time
it opens or reconnects
> - On staging this shows as bursts of about 1,400 to 1,550 checks for
one company roughly every 9 minutes, with almost no real work
> - #21861 removed one writer. This pull request fixes the class: a
company hint, a boot and a reconnect now load only changed rows since
the queue last looked, and the hourly full pass is saved so a replaced
server keeps its schedule
> - The benefit is that settled tasks are checked by the hourly full
pass and by real changes, not by every write, deploy or reconnect

## Linked Issues or Issue Description

Refs #21861, #21831, #21867

**What happened?**
A company hint `{ companyId }` on a task queue loaded every eligible
task of the company with no changed-rows filter. The same happened for a
`"*"` reload. Three sources send these all the time:
1. Each server boot starts every task queue with a `"*"` reload.
2. `reconcileDatabaseWorkNotifications` publishes a `"*"` reload to
every queue each time the deployment notification connection opens or
reconnects. The connection opens at boot and again whenever a native
execution starts after an idle period.
3. Many writers send a bare company hint: issue creation, document lock,
unlock, restore and delete, budget pause and resume, work intent
promotion, agent status changes, watchdog writes, and others.

In a staging-shaped fixture each server replacement caused two full
reloads (boot and connection open).

**Expected behavior**
A company hint, a boot or a reconnect re-checks the tasks whose rows
changed. A change that makes tasks eligible without writing any of their
rows (a company or project resume, a tree hold release) still re-checks
every task of the company. An agent status change re-checks that agent's
tasks. The hourly full pass stays the safety net, also across server
replacements.

**Steps to reproduce**
1. Seed one agent with settled in-review tasks and a live native run.
2. Start the recovery workers with
`PAPERCLIP_DEBUG_WORK_SIGNALS=stranded-assignments:1`.
3. Restart the workers, call `reconcileDatabaseWorkNotifications(db)`,
or create an issue.
4. See one `check` event per settled task with `wake: "reload"` or
`wake: "company"`.

**Paperclip version or commit**
`master` at 278660149c.

## What Changed

- `recovery/work.ts`: the full-pass bookkeeping now decides a row filter
per load.
- A plain company hint and the changed-rows backstop load the rows
changed since the queue last looked at the company
(`changedTaskCondition`, minus the existing 5-minute margin). They load
every task only when no full pass is recent.
- A boot and a reconnect use a new reload scope. One statement loads,
per company, every task when that company has no saved full pass within
the hour, and otherwise the rows changed since that saved pass (or since
this server's last reload).
- An agent scope resolves the tasks the agent is assigned, currently
reviews, or holds a run lock on, and checks only those.
- The graph fallback for a graph too large to list now sends the
explicit `everyTask` hint, so it keeps its old meaning.
- When scheduling is suppressed, the queue forgets its passes and
ignores older saved ones, so the first pass after suppression checks
every task (entries were dropped while suppressed).
- New table `issue_recovery_deferrals` (queue, issue, company, due_at),
in the same migration. A row exists while a task's check has deferred
itself (grace period, back-off, live owner lease). A boot or reconnect
reload also loads these tasks and checks them again, which rebuilds each
deadline. Deferrals cannot be rebuilt from changed rows: several defer
with no limit while none of the task's rows change (see the table
below). The store is built so that any race or lost write costs at most
one extra check, never a missed one:
- A deferring check upserts the row with its deadline when the deadline
differs from the one this server last read or wrote (one statement; none
when unchanged). A failed write keeps the full pass unsaved, so a
successor's full pass rebuilds the deadline, and drops the server's
memory of the row.
- A check that no longer defers deletes the row only if `due_at` still
equals the deadline this server read or wrote (one statement, only when
it knew of a row). A row another server rewrote since stays.
- A reload deletes the row of a task it did not load (the task left the
queue, for any reason) when, in the same statement, `due_at` still
equals the value the reload read and either the task is closed or that
deadline passed more than 10 minutes ago. This bounds the table without
listing each queue's eligibility rules.
  - A check that does not defer and knows of no row adds no statement.
- Two overlapping servers both keep the row current; a crash leaves it
in place.
- New table `issue_recovery_full_passes` (company, queue, started_at),
migration `0488`. A full pass writes it only after every task it loaded
has been checked (a check that fails keeps it unsaved), so a server
replaced mid-pass leaves no record and its replacement runs the full
pass again; a server with no memory of its own reads it. This keeps the
hourly full pass on one schedule for replaced and overlapping servers.
Reads and writes are one statement each and only happen when a full pass
is due or done. A failed read means a full pass; a failed write means
one extra full pass later.
- `issue-recovery-notifications.ts`: new scope fields `everyTask`,
`agentId` and `reload`, `notifyAgentRecovery`, `resolveAgentIssues`, and
the reload hint.
- `run-dispatch-notifications.ts`: `RunDispatchScope.everyTask` and
`notifyAgentStatusDispatch`. The agent lifecycle status-change effect
uses it instead of a company hint.
- `work-signals.ts`: `setDatabaseWorkReconnectHint` lets a topic declare
the hint it gets on reconnect instead of an unscoped reload. The task
queues declare the reload hint. Other topics keep the unscoped reload.
- `scoped-deadline-work.ts`: optional `initialHint` for the first pass
after registration. The task queues start with the reload hint.
- Writers that make tasks eligible without changing their rows now send
`everyTask`: company resume (`companies.ts`), project and company budget
resume (`budgets.ts`), tree hold resume and hold creation
(`issue-tree-control.ts`), conversation reset that releases a tree hold
(`agent-conversations.ts`), work intent promotion for `pause_lifted` and
`tree_hold_released`, task reparenting and task deletion (`issues.ts`),
company import relations (`company-portability.ts`), and company-wide
chat milestones.
- Writers with a known task now send a task or graph hint instead of a
company hint: document lock, unlock, restore and delete
(`documents.ts`), blocker edits and attachment delete (`issues.ts`),
watchdog writes (`task-watchdogs.ts`).
- Native run writers that sent a company hint now send a graph hint for
the run and its task: Runner file handoff
(`native-runner-file-handoff.ts`) and chat attachment reuse
(`chat-attachment-reuse.ts`).
- Agent-scoped hint: only the agent lifecycle status-change effect sends
it, for transitions that go through the lifecycle (pause, resume, hold
and release, terminate, error recovery, environment pause, and budget
holds through `applyAgentBudgetHoldInTransaction`). A run starting or
finishing writes the agent row directly (execution start,
`finalizeAgentStatus`) and sends only run-scoped hints, which re-check
the run's task and its graph. Queued-run dispatch after a run finishes
is unchanged (its own dispatch queues).
- `assigned-work-sweep.ts`: `listSuspects` takes the row filter as SQL.
- Tests: new census `issue-recovery-company-reload-census.test.ts`, new
`issue-recovery-saved-deferrals.test.ts` (real test database, recorded
checks), a `restart` helper in the recovery fixture, and a work-signals
test for the reconnect hint.

## Verification

Census (`issue-recovery-company-reload-census.test.ts`, real workers,
fake clock, 28 simulated minutes, 140 + 20 settled reviews, an agent
with a live native run, no fixture agent can start a run). Steps: server
replacement plus connection open, issue creation, document lock, project
budget hard stop, agent pause, agent resume, second server replacement
plus connection open.

| | Settled-task checks | Stranded checks by wake | Statements |
| --- | --- | --- | --- |
| Before (master code) | 1,440 (320 per replacement, 160 per other step)
| company 830, reload 662, hint 163 | 33,485 |
| After | 0 | hint 168, reconnect 12, backstop 7, agent 5, company 5 |
4,293 |

An earlier run of the same census at staging size (700 + 80 settled
reviews, 35 minutes) gave 8,028 settled checks and 165,882 statements
before, and 240 settled checks (only the paused agent's own tasks) and
9,714 statements after.

Guard tests in the same file:
- A task stranded by a write that sends no hint, right before each step,
is checked within 1 minute (replacements, issue creation, budget stop,
pause, resume) or within the 5-minute backstop plus 2 minutes (document
lock, which now re-checks only its own task). Passes before and after.
- A server replaced after its first full pass loaded every task but
before it checked them all: the replacement checks every unchecked task
within 2 minutes. Fails before the deferred save (112 tasks never
checked), passes after.
- Run start and finish (same census file): an agent with a settled
backlog runs start, finish, start, finish through the run row, the
execution-start agent write, the execution-run hints and
`finalizeAgentStatus` (no process runs). 0 settled-task checks on this
branch and on master; only the run's task is checked. A run that fails
has its task checked within 1 minute of the run ending.
- `issue-recovery-saved-deferrals.test.ts`: a task's check defers 20
minutes, the full pass is saved, the server is replaced 5 minutes later
without shutdown work. The replacement checks the task within 1 minute
of the original deadline. Fails at the previous head (never checked
before the next full pass), passes after.
- Same file: server B saves a deadline; server A boots and reads it; B
clears it and defers again to a new deadline; A's check stops deferring
and clears the row it read; B is replaced. The successor checks at B's
deadline. Fails at the previous head (A deleted B's row by id), passes
after.
- Same file: a saved deferral is removed at the next reload once its
task closed.
- Same file: an open task that leaves the queue (taken over by a user)
while deferred has its row removed by the first reload after its
deadline is 10 minutes past. Fails at the previous head (row kept
forever), passes after.
- Same file: after scheduling suppression, a plain company hint checks
every task again even though a recent full pass is saved.
- A change that no changed-rows clause sees is not checked by either
server replacement, and is checked by the next full pass on the saved
schedule. Fails before (each replacement did a full pass), passes after.

The file takes about 30 s locally. Every wait has a 20 s real-time limit
and each test a 2-minute limit, as in #21867.

Focused suites (all `issue-recovery-*` suites and censuses,
assigned-work, scoped deadline work, deployment notifications, budgets,
companies, run dispatch notifications, and related idle tests) on the
final head (34 files with the new deferral test): 288 passed, 1 skipped.
The #21867 agent-row census still reports 0 settled checks.
`packages/db` `work-signals.test.ts`: 34 passed. Server `tsc --noEmit`:
passed. `pnpm --filter @paperclipai/db check:migrations`: passed. `pnpm
verify` returned exit 2 (broad input: the new migration), so required CI
supplies broad coverage.

## Risks

Time bound that changes:
- A task stranded by a change that no changed-rows rule sees was often
found sooner by an unrelated company hint, boot or reconnect. It is now
found by the next full pass: at the next backstop (needs activity in the
company), boot or reconnect after one hour from the last saved full
pass. This was already the documented worst case.

Row changes the changed-rows rules see (`recovery/changed-tasks.ts`),
for auditing completeness. A task is loaded when, since the window
start:
- its own `issues.updated_at` moved;
- a `heartbeat_runs` row whose `context_snapshot.issueId` is the task
has `updated_at` in the window;
- an `issue_recovery_actions` row with the task as `source_issue_id` has
`updated_at` in the window;
- an `agent_wakeup_requests` row whose `payload.issueId` is the task has
`updated_at` in the window;
- an `issue_thread_interactions` row of the task has `updated_at` in the
window;
- an `issue_comments` row of the task was created in the window;
- its assignee agent row has `updated_at` in the window, is not
`running`, and has no heartbeat since that update (pause, resume, hold,
termination, configuration).
Not seen: company, project, tree-hold and budget rows (their resumes
send `everyTask`), the activity log, other agents' rows, lease renewals
that do not move `updated_at`, and time passing. Deferrals are covered
separately by the saved deferral rows.

Rebuilt across a replacement (no change): every pending deferral, by the
saved deferral rows. Every way the four checks defer, from tracing each
`onDeferredDeadline` call:

| Queue | Deferral | Deadline | Bounded after a seen row change? |
| --- | --- | --- | --- |
| stranded | terminal run still settling | run lease, or now + 30 s
while the run executes in memory | no (repeats while it executes) |
| stranded | chat agent daily limit | next 00:00 UTC | < 24 h |
| stranded | accepted interaction, no run since | interaction resolved +
2 min | yes |
| stranded | transient continuation back-off | run finished + up to 16
min | yes |
| dependencies | refused or failed stall wake | last attempt + up to 20
min | yes |
| dependencies | waiter's workspace hold | now + 1 h | no (repeats while
held) |
| dependencies | waiter's agent takes no wakes | now + 10 min | no
(another agent's row) |
| locks | live legacy controller lease | lease expiry | no (renewal does
not move `updated_at`) |
| locks | lapsed lease, owner proven alive | lease + up to 5 min | yes |
| locks | run updated less than 5 min ago | run updated + 5 min | yes |
| locks | adopted or lost child process still alive | now + 30 s | no
(repeats while it lives) |
| locks | prior-boot setup | about run updated + 5 min | yes |
| assigned work | settling, saved-work due, reattach | row time + up to
10 min, or now + 2 s during reattach | yes |
| assigned work | repair budget, company run brake, stalled queued run,
saved work busy | now + 60 s to 1 h | no (repeats while the condition
lasts) |
| assigned work | `waiting_unchanged` (same refusal state) | last
refusal + up to 6 h (activity log) | no |
| assigned work | continuation cap, spacing, fallback back-off | first
attempt + up to 1 h | no (activity log) |

`unchanged` (assigned work only) changes queue priority, not whether a
deferral is pending.
- Unchanged: the 5-minute changed-rows backstop, the 1-minute bound for
paused, resumed, held and terminated agents (covered by the
#21861/#21867 guards and the new agent scope), and whole-company
re-checks for company and project resumes and tree hold releases.

Other risks:
- During the deploy that ships this change, the old build still sends a
bare company hint for a company or budget resume. The new build reads
that as changed rows only. The old build re-checks every task for its
own hint while its workers run; otherwise the next full pass does. After
this deploy both builds send `everyTask`.
- If another server's `everyTask` hint is lost while this server's
notification connection is closed, the reconnect no longer re-checks
every task. The writing server checks its own hint; otherwise the next
full pass does.
- The first boot after this deploy has no saved full passes, so it runs
one full pass per company (as every boot did before).
- Nothing is added before a run's first turn or on the run-start path.
- Schema change: two new company-scoped tables with cascade foreign
keys, no change to existing tables. The old build ignores them. Neither
is a timer: no deadline is stored or scheduled from them, they only tell
a boot which tasks to check again.
- Extra statements: per deferring check, one upsert when its deadline
changed (a deferral to `now + 30 s` changes each time, so about two
writes a minute per such task) and none otherwise; one delete when a
check stops deferring; one read of the queue's deferral rows and at most
one prune per reload; one write per completed full pass.

> 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

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code
execution in Claude Code.

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 05:52:57 -06:00

1380 lines
52 KiB
TypeScript

import { notifyStrandedAgentStatus } from "./live-run-recovery-notifications.js";
import { promoteDeferredWorkIntents } from "./work-intent-outbox.js";
import { notifyStatusCardIssueChange } from "./status-card-notifications.js";
import { notifyRoutineExecutionStatus } from "./routine-execution-status-notifications.js";
import { notifyDeferredExecutionEligibility } from "./deferred-execution-notifications.js";
import { notifyIssueRecovery } from "./issue-recovery-notifications.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import { notifyNativeStatusReassessment } from "./native-status-reassessment-notifications.js";
import { notifyUnsafeWorkspaceExportRecovery } from "./unsafe-workspace-export-notifications.js";
import { notifyChatResponseAvailability } from "./chat-response-availability.js";
import { notifyChatInboundWakeNotices } from "./chat-inbound-wake-notice-notifications.js";
import { and, asc, eq, inArray, isNull, notInArray, or, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
agentWakeupRequests,
heartbeatRuns,
issueComments,
issueTreeHoldMembers,
issueTreeHolds,
issues,
} from "@paperclipai/db";
import {
ISSUE_STATUSES,
type IssueStatus,
type IssueTreeControlMode,
type IssueTreeControlPreview,
type IssueTreeHold,
type IssueTreeHoldMember,
type IssueTreeHoldReleasePolicy,
type IssueTreePreviewAgent,
type IssueTreePreviewIssue,
type IssueTreePreviewRun,
type IssueTreePreviewWarning,
} from "@paperclipai/shared";
import { conflict, notFound, unprocessable } from "../errors.js";
import type { IssuePostCommitAction } from "./issues.js";
import { notifyTerminalWorkspaceWork } from "./terminal-workspace-work.js";
import { readRunCancellation } from "./run-cancellation.js";
type IssueRow = typeof issues.$inferSelect;
type HoldRow = typeof issueTreeHolds.$inferSelect;
type HoldMemberRow = typeof issueTreeHoldMembers.$inferSelect;
export type ActiveIssueTreePauseHoldGate = {
holdId: string;
rootIssueId: string;
issueId: string;
isRoot: boolean;
mode: "pause";
reason: string | null;
releasePolicy: IssueTreeHoldReleasePolicy | null;
};
type ActorInput = {
actorType: "user" | "agent" | "system";
actorId: string;
agentId?: string | null;
userId?: string | null;
runId?: string | null;
};
type TreeIssue = IssueRow & { depth: number };
type ActiveRunRow = {
id: string;
issueId: string;
agentId: string;
status: "queued" | "running";
startedAt: Date | null;
createdAt: Date;
};
type ActiveCancelSnapshot = {
holdIds: string[];
member: IssueTreeHoldMember | null;
};
type TreeStatusUpdateResult = {
updatedIssueIds: string[];
updatedIssues: Array<{
id: string;
status: IssueStatus;
assigneeAgentId: string | null;
}>;
};
type RestoreTreeStatusResult = TreeStatusUpdateResult & {
releasedCancelHoldIds: string[];
restoreHold: IssueTreeHold | null;
};
const TERMINAL_ISSUE_STATUSES = new Set<IssueStatus>(["done", "cancelled"]);
export const ISSUE_TREE_RESUME_EXECUTABLE_STATUSES = ["todo", "in_progress", "in_review"];
/** The error code a dispatch gate records when an active pause hold refuses a run. */
export const ISSUE_PAUSED_ERROR_CODE = "issue_paused";
/**
* Recorded on a run a dispatch gate refused because a pause hold covered its
* task, so that hold's release can re-dispatch the refused work once.
*/
export function pauseSuppressionResult(hold: { holdId: string; rootIssueId?: string | null }) {
return { treeHoldSuppression: { holdId: hold.holdId, rootIssueId: hold.rootIssueId ?? null } };
}
function readPauseSuppressionHoldId(resultJson: Record<string, unknown> | null) {
const marker = resultJson?.treeHoldSuppression;
if (!marker || typeof marker !== "object" || Array.isArray(marker)) return null;
const holdId = (marker as Record<string, unknown>).holdId;
return typeof holdId === "string" && holdId.length > 0 ? holdId : null;
}
const ACTIVE_RUN_STATUSES = ["queued", "running"] as const;
const DEFAULT_RELEASE_POLICY: IssueTreeHoldReleasePolicy = { strategy: "manual" };
const MAX_PAUSE_HOLD_ANCESTOR_DEPTH = 100;
export const ISSUE_TREE_CONTROL_INTERACTION_WAKE_REASONS: ReadonlySet<string> = new Set([
"issue_commented",
"issue_reopened_via_comment",
"issue_comment_mentioned",
] as const);
const ISSUE_TREE_CONTROL_INTERACTION_WAKE_SOURCES: Readonly<Record<string, ReadonlySet<string>>> = {
issue_commented: new Set(["issue.comment"]),
issue_reopened_via_comment: new Set(["issue.comment.reopen"]),
issue_comment_mentioned: new Set(["comment.mention"]),
};
type VerifiedInteractionActor = {
requestedByActorType?: string | null;
requestedByActorId?: string | null;
};
function readNonEmptyStringFromRecord(record: unknown, key: string) {
if (!record || typeof record !== "object") return null;
const value = (record as Record<string, unknown>)[key];
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
function readInteractionWakeCommentId(record: unknown) {
if (!record || typeof record !== "object") return null;
const value = (record as Record<string, unknown>).wakeCommentIds;
if (Array.isArray(value)) {
const latest = value
.filter((entry): entry is string => typeof entry === "string" && entry.trim().length > 0)
.at(-1);
if (latest) return latest.trim();
}
return readNonEmptyStringFromRecord(record, "wakeCommentId") ?? readNonEmptyStringFromRecord(record, "commentId");
}
function hasVerifiedInteractionSource(wakeReason: string, contextSnapshot: Record<string, unknown>) {
const source = readNonEmptyStringFromRecord(contextSnapshot, "source");
if (!source) return false;
return ISSUE_TREE_CONTROL_INTERACTION_WAKE_SOURCES[wakeReason]?.has(source) ?? false;
}
function actorMatchesComment(
actor: VerifiedInteractionActor,
comment: { authorAgentId: string | null; authorUserId: string | null },
) {
if (!actor.requestedByActorType) return false;
if (actor.requestedByActorType === "system") return true;
if (!actor.requestedByActorId) return false;
if (actor.requestedByActorType === "agent") return comment.authorAgentId === actor.requestedByActorId;
if (actor.requestedByActorType === "user") return comment.authorUserId === actor.requestedByActorId;
return false;
}
async function hasVerifiedInteractionWakeRequest(
dbOrTx: Pick<Db, "select">,
input: {
companyId: string;
agentId?: string | null;
runId?: string | null;
wakeupRequestId?: string | null;
issueId: string;
commentId: string;
comment: { authorAgentId: string | null; authorUserId: string | null };
},
) {
if (!input.runId && !input.wakeupRequestId) return false;
const predicates = [
eq(agentWakeupRequests.companyId, input.companyId),
sql`${agentWakeupRequests.payload} ->> 'issueId' = ${input.issueId}`,
sql`${agentWakeupRequests.payload} ->> 'commentId' = ${input.commentId}`,
];
if (input.agentId) predicates.push(eq(agentWakeupRequests.agentId, input.agentId));
if (input.runId && input.wakeupRequestId) {
const requestScope = or(
eq(agentWakeupRequests.runId, input.runId),
eq(agentWakeupRequests.id, input.wakeupRequestId),
);
if (requestScope) predicates.push(requestScope);
} else if (input.runId) {
predicates.push(eq(agentWakeupRequests.runId, input.runId));
} else if (input.wakeupRequestId) {
predicates.push(eq(agentWakeupRequests.id, input.wakeupRequestId));
}
const requests = await dbOrTx
.select({
requestedByActorType: agentWakeupRequests.requestedByActorType,
requestedByActorId: agentWakeupRequests.requestedByActorId,
})
.from(agentWakeupRequests)
.where(and(...predicates));
return requests.some((request) => actorMatchesComment(request, input.comment));
}
export async function isVerifiedIssueTreeControlInteractionWake(
dbOrTx: Pick<Db, "select">,
input: {
companyId: string;
issueId: string;
agentId?: string | null;
contextSnapshot: Record<string, unknown> | null | undefined;
requestedByActorType?: "user" | "agent" | "system" | string | null;
requestedByActorId?: string | null;
runId?: string | null;
wakeupRequestId?: string | null;
},
) {
const contextSnapshot = input.contextSnapshot ?? null;
const wakeReason =
readNonEmptyStringFromRecord(contextSnapshot, "wakeReason") ??
readNonEmptyStringFromRecord(contextSnapshot, "reason");
if (!wakeReason || !ISSUE_TREE_CONTROL_INTERACTION_WAKE_REASONS.has(wakeReason)) return false;
if (!contextSnapshot || !hasVerifiedInteractionSource(wakeReason, contextSnapshot)) return false;
const commentId = readInteractionWakeCommentId(contextSnapshot);
if (!commentId) return false;
const comment = await dbOrTx
.select({
id: issueComments.id,
authorAgentId: issueComments.authorAgentId,
authorUserId: issueComments.authorUserId,
})
.from(issueComments)
.where(
and(
eq(issueComments.companyId, input.companyId),
eq(issueComments.issueId, input.issueId),
eq(issueComments.id, commentId),
),
)
.then((rows) => rows[0] ?? null);
if (!comment) return false;
const directActor = {
requestedByActorType: input.requestedByActorType,
requestedByActorId: input.requestedByActorId,
};
if (actorMatchesComment(directActor, comment)) return true;
return hasVerifiedInteractionWakeRequest(dbOrTx, {
companyId: input.companyId,
agentId: input.agentId,
runId: input.runId,
wakeupRequestId: input.wakeupRequestId,
issueId: input.issueId,
commentId,
comment,
});
}
function normalizeReleasePolicy(
releasePolicy: IssueTreeHoldReleasePolicy | null | undefined,
): IssueTreeHoldReleasePolicy {
return releasePolicy ?? DEFAULT_RELEASE_POLICY;
}
function coerceIssueStatus(status: string): IssueStatus {
return ISSUE_STATUSES.includes(status as IssueStatus) ? (status as IssueStatus) : "backlog";
}
function isTerminalIssue(status: string): status is IssueStatus {
return TERMINAL_ISSUE_STATUSES.has(coerceIssueStatus(status));
}
function toPreviewRun(row: ActiveRunRow): IssueTreePreviewRun {
return {
id: row.id,
issueId: row.issueId,
agentId: row.agentId,
status: row.status,
startedAt: row.startedAt,
createdAt: row.createdAt,
};
}
function toHold(row: HoldRow, members?: HoldMemberRow[]): IssueTreeHold {
return {
id: row.id,
companyId: row.companyId,
rootIssueId: row.rootIssueId,
mode: row.mode as IssueTreeControlMode,
status: row.status as IssueTreeHold["status"],
reason: row.reason,
releasePolicy: (row.releasePolicy as IssueTreeHoldReleasePolicy | null) ?? null,
createdByActorType: row.createdByActorType as IssueTreeHold["createdByActorType"],
createdByAgentId: row.createdByAgentId,
createdByUserId: row.createdByUserId,
createdByRunId: row.createdByRunId,
releasedAt: row.releasedAt,
releasedByActorType: row.releasedByActorType as IssueTreeHold["releasedByActorType"],
releasedByAgentId: row.releasedByAgentId,
releasedByUserId: row.releasedByUserId,
releasedByRunId: row.releasedByRunId,
releaseReason: row.releaseReason,
releaseMetadata: row.releaseMetadata ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(members ? { members: members.map(toHoldMember) } : {}),
};
}
function toHoldMember(row: HoldMemberRow): IssueTreeHoldMember {
return {
id: row.id,
companyId: row.companyId,
holdId: row.holdId,
issueId: row.issueId,
parentIssueId: row.parentIssueId,
depth: row.depth,
issueIdentifier: row.issueIdentifier,
issueTitle: row.issueTitle,
issueStatus: coerceIssueStatus(row.issueStatus),
assigneeAgentId: row.assigneeAgentId,
assigneeUserId: row.assigneeUserId,
activeRunId: row.activeRunId,
activeRunStatus: row.activeRunStatus,
skipped: row.skipped,
skipReason: row.skipReason,
createdAt: row.createdAt,
};
}
function issueSkipReason(input: {
mode: IssueTreeControlMode;
issue: TreeIssue;
activePauseHoldIds: string[];
activeCancelSnapshot?: ActiveCancelSnapshot | null;
}): string | null {
const status = coerceIssueStatus(input.issue.status);
if (input.mode === "restore") {
if (input.activeCancelSnapshot?.member && status !== "cancelled") {
return "changed_after_cancel";
}
if (status !== "cancelled") return "not_cancelled";
if (!input.activeCancelSnapshot?.member) return "not_cancelled_by_tree_control";
const snapshotStatus = coerceIssueStatus(input.activeCancelSnapshot.member.issueStatus);
return isTerminalIssue(snapshotStatus) ? "terminal_status" : null;
}
if (isTerminalIssue(status)) {
return "terminal_status";
}
if (input.mode === "pause" && input.activePauseHoldIds.length > 0) {
return "already_held";
}
if (input.mode === "resume" && input.activePauseHoldIds.length === 0) {
return "not_held";
}
return null;
}
function canWakeOnResume(issue: IssueTreePreviewIssue): boolean {
return !!issue.assigneeAgentId && ISSUE_TREE_RESUME_EXECUTABLE_STATUSES.includes(issue.status);
}
function buildAffectedAgents(
issuesToPreview: IssueTreePreviewIssue[],
mode: IssueTreeControlMode,
): IssueTreePreviewAgent[] {
const byAgentId = new Map<string, IssueTreePreviewAgent>();
for (const issue of issuesToPreview) {
if (issue.skipped) continue;
if (mode === "resume" && !canWakeOnResume(issue)) continue;
const agentIds = new Set<string>();
if (issue.assigneeAgentId) agentIds.add(issue.assigneeAgentId);
if (mode !== "resume" && issue.activeRun) agentIds.add(issue.activeRun.agentId);
for (const agentId of agentIds) {
const current = byAgentId.get(agentId) ?? { agentId, issueCount: 0, activeRunCount: 0 };
current.issueCount += 1;
if (issue.activeRun?.agentId === agentId) current.activeRunCount += 1;
byAgentId.set(agentId, current);
}
}
return [...byAgentId.values()].sort((a, b) => a.agentId.localeCompare(b.agentId));
}
function buildWarnings(input: {
mode: IssueTreeControlMode;
issuesToPreview: IssueTreePreviewIssue[];
activeRuns: IssueTreePreviewRun[];
}): IssueTreePreviewWarning[] {
const affectedIssues = input.issuesToPreview.filter((issue) => !issue.skipped);
const affectedIssueIds = new Set(affectedIssues.map((issue) => issue.id));
const affectedRuns = input.activeRuns.filter((run) => affectedIssueIds.has(run.issueId));
const warnings: IssueTreePreviewWarning[] = [];
if (affectedIssues.length === 0) {
warnings.push({
code: "no_affected_issues",
message: "No issues in this subtree match the requested control action.",
});
}
const runningRunIssueIds = affectedRuns
.filter((run) => run.status === "running")
.map((run) => run.issueId);
if ((input.mode === "pause" || input.mode === "cancel") && runningRunIssueIds.length > 0) {
warnings.push({
code: "running_runs_present",
message: "Some affected issues have running heartbeat runs.",
issueIds: [...new Set(runningRunIssueIds)].sort(),
});
}
const queuedRunIssueIds = affectedRuns
.filter((run) => run.status === "queued")
.map((run) => run.issueId);
if ((input.mode === "pause" || input.mode === "cancel") && queuedRunIssueIds.length > 0) {
warnings.push({
code: "queued_runs_present",
message: "Some affected issues have queued heartbeat runs.",
issueIds: [...new Set(queuedRunIssueIds)].sort(),
});
}
if (input.mode === "resume" && affectedIssues.length === 0) {
warnings.push({
code: "no_active_pause_holds",
message: "No active pause holds were found in this subtree.",
});
}
if (input.mode === "resume") {
const idleIssueIds = affectedIssues.filter((issue) => !canWakeOnResume(issue)).map((issue) => issue.id);
if (idleIssueIds.length > 0) {
warnings.push({
code: "resume_tasks_remain_idle",
message: "Blocked, backlog, and unassigned tasks will be unpaused but will not start.",
issueIds: idleIssueIds.sort(),
});
}
}
if (input.mode === "restore") {
const changedIssueIds = input.issuesToPreview
.filter((issue) => issue.skipReason === "changed_after_cancel")
.map((issue) => issue.id);
if (changedIssueIds.length > 0) {
warnings.push({
code: "restore_conflicts_present",
message: "Some issues changed after subtree cancellation and will be skipped.",
issueIds: changedIssueIds,
});
}
}
return warnings;
}
function restoreStatusFromCancelSnapshot(status: IssueStatus): IssueStatus | null {
if (status === "in_progress") return "todo";
if (isTerminalIssue(status)) return null;
return status;
}
export function issueTreeControlService(db: Db) {
async function listTreeIssues(companyId: string, rootIssueId: string): Promise<TreeIssue[]> {
const root = await db
.select()
.from(issues)
.where(and(eq(issues.id, rootIssueId), eq(issues.companyId, companyId)))
.then((rows) => rows[0] ?? null);
if (!root) {
throw notFound("Root issue not found");
}
const result: TreeIssue[] = [{ ...root, depth: 0 }];
const visited = new Set<string>([root.id]);
let frontier = [{ id: root.id, depth: 0 }];
while (frontier.length > 0) {
const parentIds = frontier.map((item) => item.id);
const depthByParentId = new Map(frontier.map((item) => [item.id, item.depth]));
const children = await db
.select()
.from(issues)
.where(and(eq(issues.companyId, companyId), inArray(issues.parentId, parentIds)))
.orderBy(asc(issues.createdAt), asc(issues.id));
const nextFrontier: typeof frontier = [];
for (const child of children) {
if (visited.has(child.id)) continue;
const depth = (depthByParentId.get(child.parentId ?? "") ?? 0) + 1;
visited.add(child.id);
result.push({ ...child, depth });
nextFrontier.push({ id: child.id, depth });
}
frontier = nextFrontier;
}
return result;
}
async function activeRunsForTree(companyId: string, treeIssues: TreeIssue[]) {
const issueIds = treeIssues.map((issue) => issue.id);
if (issueIds.length === 0) return [];
const runIds = treeIssues
.map((issue) => issue.executionRunId)
.filter((id): id is string => typeof id === "string" && id.length > 0);
const uniqueRunIds = [...new Set(runIds)];
const issueIdFromContext = sql<string | null>`${heartbeatRuns.contextSnapshot} ->> 'issueId'`;
const issueIdSet = new Set(issueIds);
const rows = await db
.select({
id: heartbeatRuns.id,
agentId: heartbeatRuns.agentId,
status: heartbeatRuns.status,
issueIdFromContext,
startedAt: heartbeatRuns.startedAt,
createdAt: heartbeatRuns.createdAt,
})
.from(heartbeatRuns)
.where(
and(
eq(heartbeatRuns.companyId, companyId),
inArray(heartbeatRuns.status, [...ACTIVE_RUN_STATUSES]),
uniqueRunIds.length > 0
? or(inArray(heartbeatRuns.id, uniqueRunIds), inArray(issueIdFromContext, issueIds))
: inArray(issueIdFromContext, issueIds),
),
);
const issueIdByExecutionRunId = new Map(
treeIssues
.filter((issue) => issue.executionRunId)
.map((issue) => [issue.executionRunId as string, issue.id]),
);
return rows
.map((run) => {
if (run.status !== "queued" && run.status !== "running") return null;
const issueId = run.issueIdFromContext && issueIdSet.has(run.issueIdFromContext)
? run.issueIdFromContext
: issueIdByExecutionRunId.get(run.id) ?? null;
if (!issueId) return null;
return {
id: run.id,
issueId,
agentId: run.agentId,
status: run.status,
startedAt: run.startedAt,
createdAt: run.createdAt,
} satisfies ActiveRunRow;
})
.filter((run): run is ActiveRunRow => run !== null)
.sort((a, b) => a.issueId.localeCompare(b.issueId) || a.createdAt.getTime() - b.createdAt.getTime());
}
async function activeHoldsByIssueId(companyId: string, issueIds: string[]) {
const byIssueId = new Map<string, { all: string[]; pause: string[] }>();
if (issueIds.length === 0) return byIssueId;
const rows = await db
.select({
issueId: issueTreeHoldMembers.issueId,
holdId: issueTreeHolds.id,
mode: issueTreeHolds.mode,
})
.from(issueTreeHoldMembers)
.innerJoin(issueTreeHolds, eq(issueTreeHoldMembers.holdId, issueTreeHolds.id))
.where(
and(
eq(issueTreeHoldMembers.companyId, companyId),
eq(issueTreeHolds.status, "active"),
inArray(issueTreeHoldMembers.issueId, issueIds),
),
)
.orderBy(asc(issueTreeHolds.createdAt), asc(issueTreeHolds.id));
for (const row of rows) {
const current = byIssueId.get(row.issueId) ?? { all: [], pause: [] };
current.all.push(row.holdId);
if (row.mode === "pause") current.pause.push(row.holdId);
byIssueId.set(row.issueId, current);
}
return byIssueId;
}
async function activeCancelSnapshotsByIssueId(companyId: string, rootIssueId: string) {
const activeCancelHolds = await listHolds(companyId, rootIssueId, {
status: "active",
mode: "cancel",
includeMembers: true,
});
const byIssueId = new Map<string, ActiveCancelSnapshot>();
for (const hold of [...activeCancelHolds].reverse()) {
for (const member of hold.members ?? []) {
const current = byIssueId.get(member.issueId) ?? { holdIds: [], member: null };
if (!current.holdIds.includes(hold.id)) current.holdIds.push(hold.id);
if (!current.member && !member.skipped) current.member = member;
byIssueId.set(member.issueId, current);
}
}
return byIssueId;
}
async function activePauseHoldsForIssueIds(companyId: string, issueIds: string[]) {
if (issueIds.length === 0) return [];
return db
.select()
.from(issueTreeHolds)
.where(
and(
eq(issueTreeHolds.companyId, companyId),
eq(issueTreeHolds.status, "active"),
eq(issueTreeHolds.mode, "pause"),
inArray(issueTreeHolds.rootIssueId, issueIds),
),
)
.orderBy(asc(issueTreeHolds.createdAt), asc(issueTreeHolds.id));
}
async function getActivePauseHoldGate(
companyId: string,
issueId: string,
): Promise<ActiveIssueTreePauseHoldGate | null> {
const activePauseHolds = await db
.select({
id: issueTreeHolds.id,
rootIssueId: issueTreeHolds.rootIssueId,
reason: issueTreeHolds.reason,
releasePolicy: issueTreeHolds.releasePolicy,
})
.from(issueTreeHolds)
.where(
and(
eq(issueTreeHolds.companyId, companyId),
eq(issueTreeHolds.status, "active"),
eq(issueTreeHolds.mode, "pause"),
),
)
.orderBy(asc(issueTreeHolds.createdAt), asc(issueTreeHolds.id));
if (activePauseHolds.length === 0) return null;
const holdByRootIssueId = new Map(activePauseHolds.map((hold) => [hold.rootIssueId, hold]));
let currentIssueId: string | null = issueId;
const visited = new Set<string>();
while (
currentIssueId
&& !visited.has(currentIssueId)
&& visited.size < MAX_PAUSE_HOLD_ANCESTOR_DEPTH
) {
visited.add(currentIssueId);
const hold = holdByRootIssueId.get(currentIssueId);
if (hold) {
return {
holdId: hold.id,
rootIssueId: hold.rootIssueId,
issueId,
isRoot: hold.rootIssueId === issueId,
mode: "pause",
reason: hold.reason,
releasePolicy: (hold.releasePolicy as IssueTreeHoldReleasePolicy | null) ?? null,
};
}
const parent: { parentId: string | null } | null = await db
.select({ parentId: issues.parentId })
.from(issues)
.where(and(eq(issues.id, currentIssueId), eq(issues.companyId, companyId)))
.then((rows) => rows[0] ?? null);
currentIssueId = parent?.parentId ?? null;
}
return null;
}
async function listActivePauseHeldIssueIds(companyId: string, issueIds: string[]): Promise<Set<string>> {
if (issueIds.length === 0) return new Set();
const [anyHold] = await db.select({ id: issueTreeHolds.id }).from(issueTreeHolds).where(and(
eq(issueTreeHolds.companyId, companyId), eq(issueTreeHolds.status, "active"), eq(issueTreeHolds.mode, "pause"))).limit(1);
if (!anyHold) return new Set();
const result = await db.execute<{ issueId: string }>(sql`
with recursive chain(start_id, id, depth, path) as (
select requested.id, requested.id, 1, array[requested.id]
from unnest(${sql.param(issueIds)}::uuid[]) as requested(id)
union all
select chain.start_id, parent.parent_id, chain.depth + 1, chain.path || parent.parent_id
from chain
join issues parent on parent.id = chain.id and parent.company_id = ${companyId}
where parent.parent_id is not null and chain.depth < ${MAX_PAUSE_HOLD_ANCESTOR_DEPTH}
and not parent.parent_id = any(chain.path)
)
select distinct chain.start_id::text as "issueId" from chain
where exists (select 1 from issue_tree_holds hold where hold.company_id = ${companyId}
and hold.status = 'active' and hold.mode = 'pause' and hold.root_issue_id = chain.id)`);
const rows = Array.isArray(result) ? result : (result as { rows?: Array<{ issueId: string }> }).rows ?? [];
return new Set(rows.map(row => row.issueId));
}
async function preview(
companyId: string,
rootIssueId: string,
input: {
mode: IssueTreeControlMode;
releasePolicy?: IssueTreeHoldReleasePolicy | null;
},
): Promise<IssueTreeControlPreview> {
const treeIssues = await listTreeIssues(companyId, rootIssueId);
const issueIds = treeIssues.map((issue) => issue.id);
const [activeRunRows, holdsByIssueId, activeCancelSnapshots] = await Promise.all([
activeRunsForTree(companyId, treeIssues),
activeHoldsByIssueId(companyId, issueIds),
input.mode === "restore"
? activeCancelSnapshotsByIssueId(companyId, rootIssueId)
: Promise.resolve(new Map<string, ActiveCancelSnapshot>()),
]);
const runsByIssueId = new Map<string, ActiveRunRow>();
for (const run of activeRunRows) {
if (!runsByIssueId.has(run.issueId)) runsByIssueId.set(run.issueId, run);
}
const countsByStatus: Partial<Record<IssueStatus, number>> = {};
const issuesToPreview = treeIssues.map((issue) => {
const status = coerceIssueStatus(issue.status);
countsByStatus[status] = (countsByStatus[status] ?? 0) + 1;
const holdState = holdsByIssueId.get(issue.id) ?? { all: [], pause: [] };
const skipReason = issueSkipReason({
mode: input.mode,
issue,
activePauseHoldIds: holdState.pause,
activeCancelSnapshot: activeCancelSnapshots.get(issue.id) ?? null,
});
const run = runsByIssueId.get(issue.id);
return {
id: issue.id,
identifier: issue.identifier,
title: issue.title,
status,
parentId: issue.parentId,
depth: issue.depth,
assigneeAgentId: issue.assigneeAgentId,
assigneeUserId: issue.assigneeUserId,
activeRun: run ? toPreviewRun(run) : null,
activeHoldIds: holdState.all,
action: input.mode,
skipped: skipReason !== null,
skipReason,
} satisfies IssueTreePreviewIssue;
});
const skippedIssues = issuesToPreview.filter((issue) => issue.skipped);
const activeRuns = activeRunRows
.map(toPreviewRun)
.sort((a, b) => a.issueId.localeCompare(b.issueId) || a.id.localeCompare(b.id));
const affectedAgents = buildAffectedAgents(issuesToPreview, input.mode);
return {
companyId,
rootIssueId,
mode: input.mode,
generatedAt: new Date(),
releasePolicy: normalizeReleasePolicy(input.releasePolicy),
totals: {
totalIssues: issuesToPreview.length,
affectedIssues: issuesToPreview.length - skippedIssues.length,
skippedIssues: skippedIssues.length,
activeRuns: activeRuns.filter((run) => run.status === "running").length,
queuedRuns: activeRuns.filter((run) => run.status === "queued").length,
affectedAgents: affectedAgents.length,
},
countsByStatus,
issues: issuesToPreview,
skippedIssues,
activeRuns,
affectedAgents,
warnings: buildWarnings({ mode: input.mode, issuesToPreview, activeRuns }),
};
}
async function createHold(
companyId: string,
rootIssueId: string,
input: {
mode: IssueTreeControlMode;
reason?: string | null;
releasePolicy?: IssueTreeHoldReleasePolicy | null;
actor: ActorInput;
},
): Promise<{
hold: IssueTreeHold;
preview: IssueTreeControlPreview;
resumedPauseHoldIds?: string[];
}> {
if (input.mode === "cancel") {
const [conversation] = await db.select({ id: issues.id }).from(issues).where(and(
eq(issues.id, rootIssueId), eq(issues.companyId, companyId), sql`${issues.conversationAgentId} is not null`,
));
if (conversation) throw unprocessable("Stop the active reply instead of cancelling the persistent conversation");
}
const holdReleasePolicy = normalizeReleasePolicy(input.releasePolicy);
const holdPreview = await preview(companyId, rootIssueId, {
mode: input.mode,
releasePolicy: holdReleasePolicy,
});
if (input.mode === "resume") {
const issueIds = [...new Set(holdPreview.issues.map((issue) => issue.id))];
const activePauseHolds = await activePauseHoldsForIssueIds(companyId, issueIds);
const releaseReason = input.reason ?? "Subtree resume applied.";
const { hold: resumeHold } = await db.transaction(async (tx) => {
await notifyIssueRecovery(tx, { companyId, everyTask: true });
await notifyDeferredExecutionEligibility(tx, { companyId });
const [createdHold] = await tx
.insert(issueTreeHolds)
.values({
companyId,
rootIssueId,
mode: input.mode,
status: "active",
reason: input.reason ?? null,
releasePolicy: holdReleasePolicy as unknown as Record<string, unknown>,
createdByActorType: input.actor.actorType,
createdByAgentId: input.actor.agentId ?? null,
createdByUserId: input.actor.userId ?? (input.actor.actorType === "user" ? input.actor.actorId : null),
createdByRunId: input.actor.runId ?? null,
})
.returning();
const memberRows = holdPreview.issues.map((issue) => ({
companyId,
holdId: createdHold.id,
issueId: issue.id,
parentIssueId: issue.parentId,
depth: issue.depth,
issueIdentifier: issue.identifier,
issueTitle: issue.title,
issueStatus: issue.status,
assigneeAgentId: issue.assigneeAgentId,
assigneeUserId: issue.assigneeUserId,
activeRunId: issue.activeRun?.id ?? null,
activeRunStatus: issue.activeRun?.status ?? null,
skipped: issue.skipped,
skipReason: issue.skipReason,
}));
const createdMembers = memberRows.length > 0
? await tx
.insert(issueTreeHoldMembers)
.values(memberRows)
.returning()
: [];
return { hold: toHold(createdHold, createdMembers) };
});
const resumedPauseHoldIds = activePauseHolds.map((hold) => hold.id);
if (resumedPauseHoldIds.length > 0) {
await Promise.all(
activePauseHolds.map((pauseHold) =>
releaseHold(companyId, pauseHold.rootIssueId, pauseHold.id, {
reason: releaseReason,
metadata: {
resumedByResumeHoldId: resumeHold.id,
resumeHoldMode: "tree_resume",
resumedPauseHoldId: pauseHold.id,
},
actor: input.actor,
}),
),
);
}
const releasedResumeHold = await releaseHold(companyId, rootIssueId, resumeHold.id, {
reason: releaseReason,
metadata: {
resumedPauseHoldIds,
resumeMode: "subtree",
...(input.releasePolicy ? { releasePolicy: holdReleasePolicy } : {}),
},
actor: input.actor,
});
return {
hold: releasedResumeHold,
preview: holdPreview,
resumedPauseHoldIds,
};
}
const { hold, members } = await db.transaction(async (tx) => {
await notifyIssueRecovery(tx, { companyId, everyTask: true });
await notifyDeferredExecutionEligibility(tx, { companyId });
const [createdHold] = await tx
.insert(issueTreeHolds)
.values({
companyId,
rootIssueId,
mode: input.mode,
status: "active",
reason: input.reason ?? null,
releasePolicy: holdReleasePolicy as unknown as Record<string, unknown>,
createdByActorType: input.actor.actorType,
createdByAgentId: input.actor.agentId ?? null,
createdByUserId: input.actor.userId ?? (input.actor.actorType === "user" ? input.actor.actorId : null),
createdByRunId: input.actor.runId ?? null,
})
.returning();
const memberRows = holdPreview.issues.map((issue) => ({
companyId,
holdId: createdHold.id,
issueId: issue.id,
parentIssueId: issue.parentId,
depth: issue.depth,
issueIdentifier: issue.identifier,
issueTitle: issue.title,
issueStatus: issue.status,
assigneeAgentId: issue.assigneeAgentId,
assigneeUserId: issue.assigneeUserId,
activeRunId: issue.activeRun?.id ?? null,
activeRunStatus: issue.activeRun?.status ?? null,
skipped: issue.skipped,
skipReason: issue.skipReason,
}));
const createdMembers = memberRows.length > 0
? await tx.insert(issueTreeHoldMembers).values(memberRows).returning()
: [];
return { hold: createdHold, members: createdMembers };
});
return {
hold: toHold(hold, members),
preview: holdPreview,
};
}
async function cancelIssueStatusesForHold(
companyId: string,
rootIssueId: string,
holdId: string,
): Promise<TreeStatusUpdateResult> {
const hold = await getHold(companyId, holdId);
if (!hold) throw notFound("Issue tree hold not found");
if (hold.rootIssueId !== rootIssueId) {
throw unprocessable("Issue tree hold does not belong to the requested root issue");
}
if (hold.mode !== "cancel") {
throw unprocessable("Issue tree hold is not a cancel operation");
}
const issueIds = [...new Set((hold.members ?? [])
.filter((member) => !member.skipped)
.map((member) => member.issueId))];
if (issueIds.length === 0) return { updatedIssueIds: [], updatedIssues: [] };
const now = new Date();
const postCommitIssueActions: IssuePostCommitAction[] = [];
const { executeIssuePostCommitActions, issueService } = await import("./issues.js");
const svc = issueService(db);
const updated = await db.transaction(async (tx) => {
const eligibleIssues = await tx
.select({ id: issues.id })
.from(issues)
.where(
and(
eq(issues.companyId, companyId),
inArray(issues.id, issueIds),
notInArray(issues.status, ["done", "cancelled"]),
),
);
const rows = [];
for (const issue of eligibleIssues) {
const updatedIssue = await svc.update(
issue.id,
{
status: "cancelled",
cancelledAt: now,
actorAgentId: hold.createdByAgentId,
actorUserId: hold.createdByUserId,
},
tx,
undefined,
postCommitIssueActions,
);
if (updatedIssue) rows.push(updatedIssue);
}
return rows;
});
await executeIssuePostCommitActions(db, postCommitIssueActions);
return {
updatedIssueIds: updated.map((issue) => issue.id),
updatedIssues: updated.map((issue) => ({
id: issue.id,
status: coerceIssueStatus(issue.status),
assigneeAgentId: issue.assigneeAgentId,
})),
};
}
async function restoreIssueStatusesForHold(
companyId: string,
rootIssueId: string,
restoreHoldId: string,
input: {
reason?: string | null;
actor: ActorInput;
},
): Promise<RestoreTreeStatusResult> {
const restoreHold = await getHold(companyId, restoreHoldId);
if (!restoreHold) throw notFound("Issue tree hold not found");
if (restoreHold.rootIssueId !== rootIssueId) {
throw unprocessable("Issue tree hold does not belong to the requested root issue");
}
if (restoreHold.mode !== "restore") {
throw unprocessable("Issue tree hold is not a restore operation");
}
const activeCancelHolds = await listHolds(companyId, rootIssueId, {
status: "active",
mode: "cancel",
includeMembers: true,
});
const cancelSnapshotByIssueId = new Map<string, IssueTreeHoldMember>();
for (const hold of [...activeCancelHolds].reverse()) {
for (const member of hold.members ?? []) {
if (!member.skipped && !cancelSnapshotByIssueId.has(member.issueId)) {
cancelSnapshotByIssueId.set(member.issueId, member);
}
}
}
const restoreIssueIds = [...new Set((restoreHold.members ?? [])
.filter((member) => !member.skipped)
.map((member) => member.issueId))];
const restoreStatusByIssueId = new Map<string, IssueStatus>();
for (const issueId of restoreIssueIds) {
const snapshot = cancelSnapshotByIssueId.get(issueId);
if (!snapshot) continue;
const restoredStatus = restoreStatusFromCancelSnapshot(coerceIssueStatus(snapshot.issueStatus));
if (restoredStatus) restoreStatusByIssueId.set(issueId, restoredStatus);
}
const issueIdsByStatus = new Map<IssueStatus, string[]>();
for (const [issueId, status] of restoreStatusByIssueId) {
const current = issueIdsByStatus.get(status) ?? [];
current.push(issueId);
issueIdsByStatus.set(status, current);
}
const now = new Date();
const releasedCancelHoldIds = activeCancelHolds.map((hold) => hold.id);
const updatedIssues = await db.transaction(async (tx) => {
await notifyDeferredExecutionEligibility(tx, { companyId });
await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors);
await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentTimers);
const restored: TreeStatusUpdateResult["updatedIssues"] = [];
for (const [status, issueIdsForStatus] of issueIdsByStatus) {
if (issueIdsForStatus.length === 0) continue;
for (const issueId of issueIdsForStatus) {
await notifyRoutineExecutionStatus(tx, issueId, companyId);
await notifyNativeStatusReassessment(tx, { companyId, issueId });
await notifyTerminalWorkspaceWork(tx, `issue:${issueId}`);
await notifyChatResponseAvailability(tx, { companyId, issueId });
if (status === "blocked" || status === "in_review") await notifyUnsafeWorkspaceExportRecovery(tx, { companyId, issueId });
}
await notifyStatusCardIssueChange(tx, companyId);
const rows = await tx
.update(issues)
.set({
status,
cancelledAt: null,
completedAt: null,
checkoutRunId: null,
executionRunId: null,
executionAgentNameKey: null,
executionLockedAt: null,
updatedAt: now,
})
.where(
and(
eq(issues.companyId, companyId),
inArray(issues.id, issueIdsForStatus),
eq(issues.status, "cancelled"),
),
)
.returning({
id: issues.id,
status: issues.status,
assigneeAgentId: issues.assigneeAgentId,
});
restored.push(...rows.map((issue) => ({
id: issue.id,
status: coerceIssueStatus(issue.status),
assigneeAgentId: issue.assigneeAgentId,
})));
}
if (releasedCancelHoldIds.length > 0) {
await tx
.update(issueTreeHolds)
.set({
status: "released",
releasedAt: now,
releasedByActorType: input.actor.actorType,
releasedByAgentId: input.actor.agentId ?? null,
releasedByUserId: input.actor.userId ?? (input.actor.actorType === "user" ? input.actor.actorId : null),
releasedByRunId: input.actor.runId ?? null,
releaseReason: input.reason ?? "Restored by subtree restore operation",
releaseMetadata: {
restoreHoldId,
restoredIssueIds: restored.map((issue) => issue.id),
},
updatedAt: now,
})
.where(and(eq(issueTreeHolds.companyId, companyId), inArray(issueTreeHolds.id, releasedCancelHoldIds)));
}
await tx
.update(issueTreeHolds)
.set({
status: "released",
releasedAt: now,
releasedByActorType: input.actor.actorType,
releasedByAgentId: input.actor.agentId ?? null,
releasedByUserId: input.actor.userId ?? (input.actor.actorType === "user" ? input.actor.actorId : null),
releasedByRunId: input.actor.runId ?? null,
releaseReason: input.reason ?? "Restore operation applied",
releaseMetadata: {
restoredIssueIds: restored.map((issue) => issue.id),
releasedCancelHoldIds,
},
updatedAt: now,
})
.where(and(eq(issueTreeHolds.companyId, companyId), eq(issueTreeHolds.id, restoreHoldId)));
return restored;
});
return {
updatedIssueIds: updatedIssues.map((issue) => issue.id),
updatedIssues,
releasedCancelHoldIds,
restoreHold: await getHold(companyId, restoreHoldId),
};
}
async function getHold(companyId: string, holdId: string) {
const hold = await db
.select()
.from(issueTreeHolds)
.where(and(eq(issueTreeHolds.id, holdId), eq(issueTreeHolds.companyId, companyId)))
.then((rows) => rows[0] ?? null);
if (!hold) return null;
const members = await db
.select()
.from(issueTreeHoldMembers)
.where(and(eq(issueTreeHoldMembers.companyId, companyId), eq(issueTreeHoldMembers.holdId, holdId)))
.orderBy(asc(issueTreeHoldMembers.depth), asc(issueTreeHoldMembers.createdAt), asc(issueTreeHoldMembers.issueId));
return toHold(hold, members);
}
async function listHolds(
companyId: string,
rootIssueId: string,
input?: {
status?: IssueTreeHold["status"];
mode?: IssueTreeControlMode;
includeMembers?: boolean;
},
) {
const whereClauses = [
eq(issueTreeHolds.companyId, companyId),
eq(issueTreeHolds.rootIssueId, rootIssueId),
];
if (input?.status) whereClauses.push(eq(issueTreeHolds.status, input.status));
if (input?.mode) whereClauses.push(eq(issueTreeHolds.mode, input.mode));
const holds = await db
.select()
.from(issueTreeHolds)
.where(and(...whereClauses))
.orderBy(asc(issueTreeHolds.createdAt), asc(issueTreeHolds.id));
if (!input?.includeMembers || holds.length === 0) {
return holds.map((hold) => toHold(hold));
}
const holdIds = holds.map((hold) => hold.id);
const members = await db
.select()
.from(issueTreeHoldMembers)
.where(
and(
eq(issueTreeHoldMembers.companyId, companyId),
inArray(issueTreeHoldMembers.holdId, holdIds),
),
)
.orderBy(asc(issueTreeHoldMembers.depth), asc(issueTreeHoldMembers.createdAt), asc(issueTreeHoldMembers.issueId));
const membersByHoldId = new Map<string, HoldMemberRow[]>();
for (const member of members) {
const existing = membersByHoldId.get(member.holdId) ?? [];
existing.push(member);
membersByHoldId.set(member.holdId, existing);
}
return holds.map((hold) => toHold(hold, membersByHoldId.get(hold.id) ?? []));
}
async function releaseHold(
companyId: string,
rootIssueId: string,
holdId: string,
input: {
reason?: string | null;
releasePolicy?: IssueTreeHoldReleasePolicy | null;
metadata?: Record<string, unknown> | null;
actor: ActorInput;
},
) {
const existing = await db
.select()
.from(issueTreeHolds)
.where(and(eq(issueTreeHolds.id, holdId), eq(issueTreeHolds.companyId, companyId)))
.then((rows) => rows[0] ?? null);
if (!existing) throw notFound("Issue tree hold not found");
if (existing.rootIssueId !== rootIssueId) {
throw unprocessable("Issue tree hold does not belong to the requested root issue");
}
if (existing.status === "released") {
throw conflict("Issue tree hold is already released");
}
const [updated] = await db.transaction(async tx => {
await promoteDeferredWorkIntents(tx, { companyId, trigger: "tree_hold_released" });
return tx
.update(issueTreeHolds)
.set({
status: "released",
releasedAt: new Date(),
releasedByActorType: input.actor.actorType,
releasedByAgentId: input.actor.agentId ?? null,
releasedByUserId: input.actor.userId ?? (input.actor.actorType === "user" ? input.actor.actorId : null),
releasedByRunId: input.actor.runId ?? null,
releaseReason: input.reason ?? null,
releasePolicy: input.releasePolicy
? (normalizeReleasePolicy(input.releasePolicy) as unknown as Record<string, unknown>)
: existing.releasePolicy,
releaseMetadata: input.metadata ?? null,
updatedAt: new Date(),
})
.where(and(eq(issueTreeHolds.id, holdId), eq(issueTreeHolds.companyId, companyId),
eq(issueTreeHolds.status, "active")))
.returning();
});
// A concurrent release won; it alone owns the resumed work.
if (!updated) throw conflict("Issue tree hold is already released");
const members = await db
.select()
.from(issueTreeHoldMembers)
.where(and(eq(issueTreeHoldMembers.companyId, companyId), eq(issueTreeHoldMembers.holdId, holdId)))
.orderBy(asc(issueTreeHoldMembers.depth), asc(issueTreeHoldMembers.createdAt), asc(issueTreeHoldMembers.issueId));
return toHold(updated, members);
}
/**
* A pause interrupts runs as an operator hold, not as a failure. That pending
* work is owed one re-dispatch once no pause covers the task. A run is owed
* when a pause hold's member snapshot names it and an operator Stop ended it,
* or when a dispatch gate refused it because a pause covered the task (a
* scheduled retry that came due, or a queued run reaching its claim); the
* gate records the covering hold on the run. The obligation belongs to the
* run, so overlapping holds keep it until the last release. Current state
* governs: the interrupted run must still be the task's latest run, the task
* must be executable by the same agent, and the claim marker makes the
* resume happen at most once. Execution blockers are the caller's.
*/
async function findOwedPauseResume(companyId: string, issueId: string) {
const [issue] = await db.select({
status: issues.status, assigneeAgentId: issues.assigneeAgentId, assigneeUserId: issues.assigneeUserId,
}).from(issues).where(and(eq(issues.companyId, companyId), eq(issues.id, issueId)));
if (!issue?.assigneeAgentId || issue.assigneeUserId
|| !ISSUE_TREE_RESUME_EXECUTABLE_STATUSES.includes(issue.status)) return null;
const [run] = await db.select({
id: heartbeatRuns.id, agentId: heartbeatRuns.agentId, status: heartbeatRuns.status,
finishedAt: heartbeatRuns.finishedAt, resultJson: heartbeatRuns.resultJson, errorCode: heartbeatRuns.errorCode,
}).from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, companyId),
sql`coalesce(${heartbeatRuns.issueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId') = ${issueId}`,
)).orderBy(sql`${heartbeatRuns.createdAt} desc`).limit(1);
if (!run || run.status !== "cancelled" || !run.finishedAt || run.agentId !== issue.assigneeAgentId
|| run.resultJson?.treeHoldResume !== undefined) return null;
// Only a cancellation recorded while a covering pause was active is owed.
const activeAtCancellation = and(
eq(issueTreeHolds.companyId, companyId), eq(issueTreeHolds.mode, "pause"),
sql`${issueTreeHolds.createdAt} <= ${run.finishedAt.toISOString()}::timestamptz`,
or(isNull(issueTreeHolds.releasedAt),
sql`${issueTreeHolds.releasedAt} >= ${run.finishedAt.toISOString()}::timestamptz`),
);
const memberHold = (snapshotRunId?: string) => db.select({ id: issueTreeHolds.id }).from(issueTreeHoldMembers)
.innerJoin(issueTreeHolds, eq(issueTreeHolds.id, issueTreeHoldMembers.holdId))
.where(and(
eq(issueTreeHoldMembers.companyId, companyId), eq(issueTreeHoldMembers.issueId, issueId),
snapshotRunId ? eq(issueTreeHoldMembers.activeRunId, snapshotRunId) : undefined,
eq(issueTreeHoldMembers.skipped, false), activeAtCancellation,
)).orderBy(asc(issueTreeHolds.createdAt)).limit(1);
let hold: { id: string } | undefined;
if (run.errorCode === ISSUE_PAUSED_ERROR_CODE) {
const suppressedBy = readPauseSuppressionHoldId(run.resultJson);
// The gate recorded the pause it observed. A run refused before gates
// recorded that hold falls back to a snapshot pause active at the time.
[hold] = suppressedBy
? await db.select({ id: issueTreeHolds.id }).from(issueTreeHolds).where(and(eq(issueTreeHolds.id, suppressedBy),
eq(issueTreeHolds.companyId, companyId), eq(issueTreeHolds.mode, "pause"))).limit(1)
: await memberHold();
} else if (readRunCancellation(run.resultJson)?.source === "operator") {
// A Stop is owed only when the pause snapshot named the stopped run.
[hold] = await memberHold(run.id);
}
if (!hold) return null;
if (await getActivePauseHoldGate(companyId, issueId)) return null;
return { issueId, agentId: run.agentId, interruptedRunId: run.id, holdId: hold.id };
}
async function cancelUnclaimedWakeupsForTree(companyId: string, rootIssueId: string, reason: string) {
const treeIssues = await listTreeIssues(companyId, rootIssueId);
const issueIds = treeIssues.map((issue) => issue.id);
if (issueIds.length === 0) return [];
const now = new Date();
return db.transaction(async tx => {
const affected = await tx.select({ agentId: agentWakeupRequests.agentId }).from(agentWakeupRequests).where(and(
eq(agentWakeupRequests.companyId, companyId), inArray(agentWakeupRequests.status, ["queued", "deferred_issue_execution"]),
isNull(agentWakeupRequests.runId), inArray(sql<string | null>`${agentWakeupRequests.payload} ->> 'issueId'`, issueIds),
)).for("update");
for (const agentId of new Set(affected.map(wake => wake.agentId))) await notifyStrandedAgentStatus(tx, { companyId, agentId });
await notifyChatInboundWakeNotices(tx, { companyId });
return tx
.update(agentWakeupRequests)
.set({
status: "cancelled",
finishedAt: now,
error: reason,
updatedAt: now,
})
.where(
and(
eq(agentWakeupRequests.companyId, companyId),
inArray(agentWakeupRequests.status, ["queued", "deferred_issue_execution"]),
isNull(agentWakeupRequests.runId),
inArray(sql<string | null>`${agentWakeupRequests.payload} ->> 'issueId'`, issueIds),
),
)
.returning({
id: agentWakeupRequests.id,
agentId: agentWakeupRequests.agentId,
reason: agentWakeupRequests.reason,
payload: agentWakeupRequests.payload,
});
});
}
return {
listTreeIssues,
preview,
createHold,
cancelIssueStatusesForHold,
restoreIssueStatusesForHold,
getHold,
listHolds,
getActivePauseHoldGate,
listActivePauseHeldIssueIds,
releaseHold,
findOwedPauseResume,
cancelUnclaimedWakeupsForTree,
};
}