mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
feat(decisions): improve desk triage and queue parity (#10785)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The decisions desk and queue help operators find work that needs a human decision. > - The current views use different grouping, sorting, and labels. > - Repeated confirmation requests can also leave stale pending actions in the queue. > - Blocked-work attention can point at an intermediate issue instead of the terminal blocker. > - This pull request aligns the server contract and both user interfaces. > - The benefit is a smaller, clearer queue that ranks the decisions with the largest impact. ## Linked Issues or Issue Description Related PR: #10774 **What existing behavior does this improve?** The decisions desk and queue currently use different triage rules. They can show stale repeated confirmations and can rank blocked work by an intermediate issue. **Subsystem affected** This change affects attention aggregation, issue thread interactions, shared attention contracts, and the decisions user interface. **Current behavior** The desk uses a can-wait group that has no clear arrival meaning. The queue has fewer controls than the desk. Repeated pending confirmations remain actionable. Blocked-work rows do not always identify the terminal actionable blocker. **Proposed behavior** Group desk items by arrival date, and reserve Decide now for explicit due dates. Use one toolbar and shelf model on both pages. Supersede older repeated pending confirmations. Aggregate blocked work under the terminal actionable blocker and rank it by impact. **Reason and benefit** Operators get one consistent triage model. The badge reflects new and overdue work. High-impact blockers move to the top. Duplicate confirmation work no longer consumes attention. **Breaking changes** The attention summary field `decideNowCount` changes to `deskBadgeCount`. Consumers must use the new field. Older repeated confirmation interactions can now finish with the `superseded_by_newer_request` outcome. ## What Changed - Supersede older pending confirmation requests for the same issue and record the mutation in activity history. - Resolve blocked-work attention to actionable terminal blockers, suppress live blocker trees, and rank rows by blocked-work impact. - Group the decisions desk into New today and Earlier, and count new plus overdue work in the desk badge. - Share the decision toolbar and shelf components across the desk and queue. - Add queue grouping, sorting, filtering, aging, visible training controls, and clearer recommendation copy. - Add server, shared-contract, and user-interface tests for the new behavior. ## Verification - `pnpm check:token-gates` - `pnpm -r typecheck` - `env -u AWS_ACCESS_KEY_ID -u AWS_SECRET_ACCESS_KEY pnpm test:run` (all server, UI, CLI, shared, and catalog tests passed; one fixed five-second DB timeout flaked under full-suite load) - `NODE_ENV=test pnpm --filter @paperclipai/db exec vitest run src/status-card-migrations.test.ts` (passed in isolation) - `pnpm build` ## Risks - The attention summary field rename requires synchronized consumers. - Terminal-blocker traversal uses cycle and depth guards. A malformed dependency graph can stop at the last safe node. - The new arrival grouping changes which items contribute to the decisions badge. - Superseding repeated confirmations changes the terminal state of older pending interactions. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI Codex with GPT-5. The runtime did not expose a dated model snapshot or context-window size. The model used reasoning, repository tools, code execution, and test execution. ## 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 --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
9b9631b724
commit
8e7f1c03eb
23 files changed
+1909
-583
No files matched your search
@@ -611,8 +611,10 @@ describeEmbeddedPostgres("attention service", () => {
|
||||
});
|
||||
expect(feed.items.find((item) => item.sourceKind === "blocker_attention")?.detail).toMatchObject({
|
||||
kind: "blocker",
|
||||
blockingIssue: { identifier: "ATN-5", title: "Stalled review blocker" },
|
||||
blockingIssue: null,
|
||||
blockedTaskCount: 1,
|
||||
});
|
||||
expect(feed.items.find((item) => item.sourceKind === "blocker_attention")?.subject.id).toBe(blockerLeafId);
|
||||
expect(feed.items.find((item) => item.sourceKind === "failed_run")?.detail).toMatchObject({
|
||||
kind: "failed_run",
|
||||
agentName: "Worker",
|
||||
@@ -872,6 +874,70 @@ describeEmbeddedPostgres("attention service", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("shows only the newest pending confirmation per issue and kind", async () => {
|
||||
const { companyId, workerId, reviewerId } = await seedCompany("ATC");
|
||||
const issueId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATC-1",
|
||||
title: "Repeated sign-offs",
|
||||
status: "in_review",
|
||||
assigneeAgentId: workerId,
|
||||
});
|
||||
const olderConfirmationId = randomUUID();
|
||||
const newerConfirmationId = randomUUID();
|
||||
const checkboxId = randomUUID();
|
||||
await db.insert(issueThreadInteractions).values([
|
||||
{
|
||||
id: olderConfirmationId,
|
||||
companyId,
|
||||
issueId,
|
||||
kind: "request_confirmation",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
createdByAgentId: workerId,
|
||||
title: "Approve V1",
|
||||
payload: { version: 1, prompt: "Approve V1?" },
|
||||
createdAt: new Date("2026-07-09T12:00:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:10:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: newerConfirmationId,
|
||||
companyId,
|
||||
issueId,
|
||||
kind: "request_confirmation",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
createdByAgentId: reviewerId,
|
||||
title: "Approve V2",
|
||||
payload: { version: 1, prompt: "Approve V2?" },
|
||||
createdAt: new Date("2026-07-09T12:05:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:05:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: checkboxId,
|
||||
companyId,
|
||||
issueId,
|
||||
kind: "request_checkbox_confirmation",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
createdByAgentId: workerId,
|
||||
title: "Select rollout",
|
||||
payload: { version: 1, prompt: "Select rollout", options: [{ id: "one", label: "One" }] },
|
||||
createdAt: new Date("2026-07-09T12:01:00.000Z"),
|
||||
updatedAt: new Date("2026-07-09T12:01:00.000Z"),
|
||||
},
|
||||
]);
|
||||
|
||||
const feed = await attentionService(db).list(companyId, { userId: "board-user" });
|
||||
const interactionIds = feed.items
|
||||
.filter((item) => item.sourceKind === "issue_thread_interaction")
|
||||
.map((item) => item.subject.id);
|
||||
|
||||
expect(interactionIds).toContain(newerConfirmationId);
|
||||
expect(interactionIds).toContain(checkboxId);
|
||||
expect(interactionIds).not.toContain(olderConfirmationId);
|
||||
});
|
||||
|
||||
it("uses inbox_dismissals with attention-prefixed dedup keys and resurfaces newer activity", async () => {
|
||||
const { companyId } = await seedCompany("ATD");
|
||||
const approvalId = randomUUID();
|
||||
@@ -938,7 +1004,7 @@ describeEmbeddedPostgres("attention service", () => {
|
||||
|
||||
const feed = await attentionService(db).list(companyId, { userId: "board-user" });
|
||||
|
||||
expect(feed.items.some((item) => item.dedupKey === `blocker:${issueId}:ATP-1`)).toBe(true);
|
||||
expect(feed.items.some((item) => item.dedupKey === `blocker:${issueId}`)).toBe(true);
|
||||
});
|
||||
|
||||
// Regression: both blocker_attention call sites fell back to the blocked
|
||||
@@ -955,15 +1021,14 @@ describeEmbeddedPostgres("attention service", () => {
|
||||
});
|
||||
|
||||
const feed = await attentionService(db).list(companyId, { userId: "board-user" });
|
||||
const row = feed.items.find((item) => item.dedupKey === `blocker:${issueId}:ATV-1`);
|
||||
const row = feed.items.find((item) => item.dedupKey === `blocker:${issueId}`);
|
||||
|
||||
expect(row).toBeTruthy();
|
||||
expect(row?.detail).toMatchObject({ kind: "blocker", blockingIssue: null });
|
||||
// The dedup key keeps its original fallback so existing dismissals survive.
|
||||
expect(row?.dismissalKey).toBe(`attention:blocker:${issueId}:ATV-1`);
|
||||
expect(row?.dismissalKey).toBe(`attention:blocker:${issueId}`);
|
||||
});
|
||||
|
||||
it("names the real blocking task when a blocks relation exists", async () => {
|
||||
it("suppresses a blocked dependency row while its blocker is actively progressing", async () => {
|
||||
const { companyId } = await seedCompany("ATW");
|
||||
const blockedId = await insertIssue({
|
||||
companyId,
|
||||
@@ -986,12 +1051,129 @@ describeEmbeddedPostgres("attention service", () => {
|
||||
});
|
||||
|
||||
const feed = await attentionService(db).list(companyId, { userId: "board-user" });
|
||||
const row = feed.items.find((item) => item.sourceKind === "blocker_attention" && item.subject.id === blockedId);
|
||||
expect(feed.items.some((item) => item.sourceKind === "blocker_attention")).toBe(false);
|
||||
});
|
||||
|
||||
expect(row?.detail).toMatchObject({
|
||||
kind: "blocker",
|
||||
blockingIssue: { identifier: "ATW-2", title: "The actual blocker" },
|
||||
it("suppresses a mixed blocker tree when any blocker is live", async () => {
|
||||
const { companyId } = await seedCompany("ATL");
|
||||
const blockedId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATL-1",
|
||||
title: "Blocked rollout",
|
||||
status: "blocked",
|
||||
});
|
||||
const blockerIds = await Promise.all([
|
||||
insertIssue({ companyId, identifier: "ATL-2", title: "Live phase one", status: "in_progress" }),
|
||||
insertIssue({ companyId, identifier: "ATL-3", title: "Live phase two", status: "in_progress" }),
|
||||
insertIssue({ companyId, identifier: "ATL-4", title: "Live phase three", status: "in_progress" }),
|
||||
insertIssue({ companyId, identifier: "ATL-5", title: "Stopped phase", status: "todo" }),
|
||||
]);
|
||||
await db.insert(issueRelations).values(blockerIds.map((issueId) => ({
|
||||
companyId,
|
||||
issueId,
|
||||
relatedIssueId: blockedId,
|
||||
type: "blocks" as const,
|
||||
})));
|
||||
|
||||
const feed = await attentionService(db).list(companyId, { userId: "board-user" });
|
||||
|
||||
expect(feed.items.filter((item) => item.sourceKind === "blocker_attention")).toEqual([]);
|
||||
});
|
||||
|
||||
it("emits one terminal-blocker row with a cycle-safe transitive blocked-work count", async () => {
|
||||
const { companyId } = await seedCompany("ATC");
|
||||
const terminalId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATC-1",
|
||||
title: "Choose migration owner",
|
||||
status: "todo",
|
||||
});
|
||||
const blockedId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATC-2",
|
||||
title: "Blocked migration",
|
||||
status: "blocked",
|
||||
});
|
||||
await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATC-3",
|
||||
title: "Open migration child",
|
||||
status: "todo",
|
||||
parentId: blockedId,
|
||||
});
|
||||
const transitiveId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATC-4",
|
||||
title: "Transitively blocked follow-up",
|
||||
status: "todo",
|
||||
});
|
||||
await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATC-5",
|
||||
title: "Closed child",
|
||||
status: "done",
|
||||
parentId: blockedId,
|
||||
});
|
||||
await db.insert(issueRelations).values([
|
||||
{ companyId, issueId: terminalId, relatedIssueId: blockedId, type: "blocks" },
|
||||
{ companyId, issueId: blockedId, relatedIssueId: transitiveId, type: "blocks" },
|
||||
// Corrupt legacy cycles must not inflate or hang the count.
|
||||
{ companyId, issueId: transitiveId, relatedIssueId: blockedId, type: "blocks" },
|
||||
]);
|
||||
|
||||
const feed = await attentionService(db).list(companyId, { userId: "board-user" });
|
||||
const rows = feed.items.filter((item) => item.sourceKind === "blocker_attention");
|
||||
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toMatchObject({
|
||||
subject: { id: terminalId, identifier: "ATC-1", title: "Choose migration owner" },
|
||||
relatedIssue: { id: blockedId },
|
||||
whyNow: "Blocks 3 tasks and needs human attention.",
|
||||
detail: { kind: "blocker", blockingIssue: null, blockedTaskCount: 3 },
|
||||
});
|
||||
expect(rows[0]?.subject.id).not.toBe(blockedId);
|
||||
});
|
||||
|
||||
it("orders terminal blockers by blocked-work weight descending", async () => {
|
||||
const { companyId } = await seedCompany("ATR");
|
||||
const heavyTerminalId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATR-1",
|
||||
title: "Heavy blocker",
|
||||
status: "todo",
|
||||
updatedAt: new Date("2026-07-01T00:00:00.000Z"),
|
||||
});
|
||||
const lightTerminalId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATR-2",
|
||||
title: "Light blocker",
|
||||
status: "todo",
|
||||
updatedAt: new Date("2026-07-03T00:00:00.000Z"),
|
||||
});
|
||||
const heavyBlockedId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATR-3",
|
||||
title: "Heavy blocked root",
|
||||
status: "blocked",
|
||||
});
|
||||
const lightBlockedId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATR-4",
|
||||
title: "Light blocked root",
|
||||
status: "blocked",
|
||||
});
|
||||
await insertIssue({ companyId, identifier: "ATR-5", title: "Heavy child one", status: "todo", parentId: heavyBlockedId });
|
||||
await insertIssue({ companyId, identifier: "ATR-6", title: "Heavy child two", status: "todo", parentId: heavyBlockedId });
|
||||
await db.insert(issueRelations).values([
|
||||
{ companyId, issueId: heavyTerminalId, relatedIssueId: heavyBlockedId, type: "blocks" },
|
||||
{ companyId, issueId: lightTerminalId, relatedIssueId: lightBlockedId, type: "blocks" },
|
||||
]);
|
||||
|
||||
const feed = await attentionService(db).list(companyId, { userId: "board-user" });
|
||||
const rows = feed.items.filter((item) => item.sourceKind === "blocker_attention");
|
||||
|
||||
expect(rows.map((item) => item.subject.id)).toEqual([heavyTerminalId, lightTerminalId]);
|
||||
expect(rows.map((item) => item.detail?.kind === "blocker" ? item.detail.blockedTaskCount : null)).toEqual([3, 1]);
|
||||
});
|
||||
|
||||
it("does not name the blocked task as its own blocker on a human-owned unblock row", async () => {
|
||||
@@ -1195,7 +1377,19 @@ describeEmbeddedPostgres("attention service", () => {
|
||||
sort: "decide",
|
||||
limit: 20,
|
||||
});
|
||||
expect(feed.decideNowCount).toBe(2);
|
||||
// Desk badge = distinct items surfaced today OR with a due decide-by
|
||||
// Everything here was seeded ~now, so every visible row
|
||||
// counts; the whole page fits under limit:20 so items == rankedItems.
|
||||
const startOfUtcDay = Date.UTC(
|
||||
new Date(now).getUTCFullYear(),
|
||||
new Date(now).getUTCMonth(),
|
||||
new Date(now).getUTCDate(),
|
||||
);
|
||||
const expectedBadge = feed.items.filter(
|
||||
(item) => new Date(item.createdAt).getTime() >= startOfUtcDay || item.decideBy === "today",
|
||||
).length;
|
||||
expect(expectedBadge).toBeGreaterThanOrEqual(2);
|
||||
expect(feed.deskBadgeCount).toBe(expectedBadge);
|
||||
expect(feed.items.some((item) => item.subject.id === snoozedId)).toBe(false);
|
||||
expect(feed.items.slice(0, 3).map((item) => item.subject.id)).toEqual([
|
||||
expiringSoonId,
|
||||
@@ -1228,7 +1422,7 @@ describeEmbeddedPostgres("attention service", () => {
|
||||
sort: "decide",
|
||||
limit: 1,
|
||||
});
|
||||
expect(firstPage).toMatchObject({ totalCount: 2, decideNowCount: 2 });
|
||||
expect(firstPage).toMatchObject({ totalCount: 2, deskBadgeCount: 2 });
|
||||
expect(firstPage.items.map((item) => item.subject.id)).toEqual([expiringSoonId]);
|
||||
expect(firstPage.nextCursor).toBeTruthy();
|
||||
const secondPage = await attentionService(db).list(companyId, {
|
||||
@@ -1334,6 +1528,51 @@ describeEmbeddedPostgres("attention service", () => {
|
||||
})).rejects.toThrow("all cannot be combined with cursor or limit");
|
||||
});
|
||||
|
||||
it("does not apply the open-decision safety limit to complete snapshots", async () => {
|
||||
const { companyId, workerId } = await seedCompany("ATC");
|
||||
const originIssueId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "ATC-1",
|
||||
title: "Decision origin",
|
||||
status: "in_progress",
|
||||
assigneeAgentId: workerId,
|
||||
});
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({
|
||||
id: runId,
|
||||
companyId,
|
||||
agentId: workerId,
|
||||
status: "succeeded",
|
||||
contextSnapshot: { issueId: originIssueId },
|
||||
});
|
||||
await db.insert(decisions).values(["First decision", "Second decision"].map((title) => ({
|
||||
id: randomUUID(),
|
||||
companyId,
|
||||
originAgentId: workerId,
|
||||
originIssueId,
|
||||
originRunId: runId,
|
||||
title,
|
||||
body: title,
|
||||
options: [],
|
||||
status: "open" as const,
|
||||
expiresAt: new Date("2026-08-10T00:00:00.000Z"),
|
||||
signedSpec: "test",
|
||||
targetSnapshots: {},
|
||||
})));
|
||||
|
||||
const svc = attentionService(db, { openDecisionLimit: 1 });
|
||||
const limited = await svc.list(companyId, { userId: "board-user" });
|
||||
expect(limited.items.filter((item) => item.sourceKind === "decision")).toHaveLength(1);
|
||||
|
||||
const complete = await svc.list(companyId, {
|
||||
userId: "board-user",
|
||||
all: true,
|
||||
allowUnscopedAll: true,
|
||||
});
|
||||
expect(complete.items.filter((item) => item.sourceKind === "decision")).toHaveLength(2);
|
||||
expect(complete.nextCursor).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps this-week deadlines in the current UTC week", async () => {
|
||||
const { companyId, workerId } = await seedCompany("ATW");
|
||||
const now = Date.parse("2026-08-02T12:00:00.000Z"); // Sunday in an ISO Monday-Sunday week.
|
||||
@@ -1442,6 +1681,10 @@ describeEmbeddedPostgres("attention service", () => {
|
||||
};
|
||||
|
||||
await request(app(board)).get(`/api/companies/${companyId}/attention`).expect(200);
|
||||
const completeFeed = await request(app(board))
|
||||
.get(`/api/companies/${companyId}/attention?includeDismissed=true&all=true`)
|
||||
.expect(200);
|
||||
expect(completeFeed.body.nextCursor).toBeNull();
|
||||
await request(app(board))
|
||||
.get(`/api/companies/${companyId}/attention?activitySince=yesterday`)
|
||||
.expect(400, { error: "activitySince must be an ISO timestamp" });
|
||||
|
||||
@@ -892,6 +892,172 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => {
|
||||
expect(rows[0]?.idempotencyKey).toBe("run-1:questionnaire");
|
||||
});
|
||||
|
||||
it("supersedes older pending confirmations from the same agent without crossing agent or kind", async () => {
|
||||
const { companyId, issueId } = await seedConfirmationIssue("Newer confirmation supersedes older");
|
||||
const firstAgentId = randomUUID();
|
||||
const secondAgentId = randomUUID();
|
||||
await db.insert(agents).values([
|
||||
{
|
||||
id: firstAgentId,
|
||||
companyId,
|
||||
name: "First agent",
|
||||
role: "engineer",
|
||||
status: "active",
|
||||
adapterType: "codex_local",
|
||||
adapterConfig: {},
|
||||
runtimeConfig: {},
|
||||
permissions: {},
|
||||
},
|
||||
{
|
||||
id: secondAgentId,
|
||||
companyId,
|
||||
name: "Second agent",
|
||||
role: "engineer",
|
||||
status: "active",
|
||||
adapterType: "codex_local",
|
||||
adapterConfig: {},
|
||||
runtimeConfig: {},
|
||||
permissions: {},
|
||||
},
|
||||
]);
|
||||
|
||||
const older = await interactionsSvc.create({ id: issueId, companyId }, {
|
||||
kind: "request_confirmation",
|
||||
idempotencyKey: "confirmation:first:older",
|
||||
payload: { version: 1, prompt: "Approve the older draft?" },
|
||||
}, { agentId: firstAgentId });
|
||||
const otherKind = await interactionsSvc.create({ id: issueId, companyId }, {
|
||||
kind: "request_checkbox_confirmation",
|
||||
idempotencyKey: "checkbox:first",
|
||||
payload: {
|
||||
version: 1,
|
||||
prompt: "Select regions",
|
||||
options: [{ id: "us", label: "US" }],
|
||||
},
|
||||
}, { agentId: firstAgentId });
|
||||
const otherAgent = await interactionsSvc.create({ id: issueId, companyId }, {
|
||||
kind: "request_confirmation",
|
||||
idempotencyKey: "confirmation:second",
|
||||
payload: { version: 1, prompt: "Approve the second agent's draft?" },
|
||||
}, { agentId: secondAgentId });
|
||||
const replacement = await interactionsSvc.create({ id: issueId, companyId }, {
|
||||
kind: "request_confirmation",
|
||||
idempotencyKey: "confirmation:first:newer",
|
||||
payload: { version: 1, prompt: "Approve the newer draft?" },
|
||||
}, { agentId: firstAgentId });
|
||||
|
||||
const interactions = await interactionsSvc.listForIssue(issueId);
|
||||
expect(interactions.find((interaction) => interaction.id === older.id)).toMatchObject({
|
||||
status: "expired",
|
||||
resolvedByAgentId: firstAgentId,
|
||||
result: {
|
||||
outcome: "superseded_by_newer_request",
|
||||
supersededByInteractionId: replacement.id,
|
||||
},
|
||||
});
|
||||
expect(interactions.find((interaction) => interaction.id === replacement.id)?.status).toBe("pending");
|
||||
expect(interactions.find((interaction) => interaction.id === otherAgent.id)?.status).toBe("pending");
|
||||
expect(interactions.find((interaction) => interaction.id === otherKind.id)?.status).toBe("pending");
|
||||
});
|
||||
|
||||
it("sweeps historical confirmation pile-ups idempotently per issue, kind, and agent", async () => {
|
||||
const { companyId, issueId } = await seedConfirmationIssue("Historical confirmation sweep");
|
||||
const firstAgentId = randomUUID();
|
||||
const secondAgentId = randomUUID();
|
||||
await db.insert(agents).values([
|
||||
{
|
||||
id: firstAgentId,
|
||||
companyId,
|
||||
name: "First agent",
|
||||
role: "engineer",
|
||||
status: "active",
|
||||
adapterType: "codex_local",
|
||||
adapterConfig: {},
|
||||
runtimeConfig: {},
|
||||
permissions: {},
|
||||
},
|
||||
{
|
||||
id: secondAgentId,
|
||||
companyId,
|
||||
name: "Second agent",
|
||||
role: "engineer",
|
||||
status: "active",
|
||||
adapterType: "codex_local",
|
||||
adapterConfig: {},
|
||||
runtimeConfig: {},
|
||||
permissions: {},
|
||||
},
|
||||
]);
|
||||
|
||||
const firstAgentIds = [randomUUID(), randomUUID(), randomUUID()];
|
||||
const secondAgentIds = [randomUUID(), randomUUID()];
|
||||
const checkboxId = randomUUID();
|
||||
await db.insert(issueThreadInteractions).values([
|
||||
...firstAgentIds.map((id, index) => ({
|
||||
id,
|
||||
companyId,
|
||||
issueId,
|
||||
kind: "request_confirmation",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
createdByAgentId: firstAgentId,
|
||||
payload: { version: 1 as const, prompt: `First agent draft ${index + 1}` },
|
||||
createdAt: new Date(`2026-07-01T12:0${index}:00.000Z`),
|
||||
updatedAt: new Date(`2026-07-01T12:0${index}:00.000Z`),
|
||||
})),
|
||||
...secondAgentIds.map((id, index) => ({
|
||||
id,
|
||||
companyId,
|
||||
issueId,
|
||||
kind: "request_confirmation",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
createdByAgentId: secondAgentId,
|
||||
payload: { version: 1 as const, prompt: `Second agent draft ${index + 1}` },
|
||||
createdAt: new Date(`2026-07-01T13:0${index}:00.000Z`),
|
||||
updatedAt: new Date(`2026-07-01T13:0${index}:00.000Z`),
|
||||
})),
|
||||
{
|
||||
id: checkboxId,
|
||||
companyId,
|
||||
issueId,
|
||||
kind: "request_checkbox_confirmation",
|
||||
status: "pending",
|
||||
continuationPolicy: "wake_assignee",
|
||||
createdByAgentId: firstAgentId,
|
||||
payload: { version: 1, prompt: "Select one", options: [{ id: "one", label: "One" }] },
|
||||
createdAt: new Date("2026-07-01T14:00:00.000Z"),
|
||||
updatedAt: new Date("2026-07-01T14:00:00.000Z"),
|
||||
},
|
||||
]);
|
||||
|
||||
await expect(interactionsSvc.sweepSupersededPendingRequestConfirmations())
|
||||
.resolves.toEqual({ expired: 3 });
|
||||
await expect(interactionsSvc.sweepSupersededPendingRequestConfirmations())
|
||||
.resolves.toEqual({ expired: 0 });
|
||||
|
||||
const interactions = await interactionsSvc.listForIssue(issueId);
|
||||
for (const id of firstAgentIds.slice(0, -1)) {
|
||||
expect(interactions.find((interaction) => interaction.id === id)).toMatchObject({
|
||||
status: "expired",
|
||||
result: {
|
||||
outcome: "superseded_by_newer_request",
|
||||
supersededByInteractionId: firstAgentIds.at(-1),
|
||||
},
|
||||
});
|
||||
}
|
||||
expect(interactions.find((interaction) => interaction.id === firstAgentIds.at(-1))?.status).toBe("pending");
|
||||
expect(interactions.find((interaction) => interaction.id === secondAgentIds[0])).toMatchObject({
|
||||
status: "expired",
|
||||
result: {
|
||||
outcome: "superseded_by_newer_request",
|
||||
supersededByInteractionId: secondAgentIds[1],
|
||||
},
|
||||
});
|
||||
expect(interactions.find((interaction) => interaction.id === secondAgentIds[1])?.status).toBe("pending");
|
||||
expect(interactions.find((interaction) => interaction.id === checkboxId)?.status).toBe("pending");
|
||||
});
|
||||
|
||||
it("refuses to create an interaction on a closed issue", async () => {
|
||||
const { companyId, issueId } = await seedConfirmationIssue("Closed issue create guard");
|
||||
await db.update(issues).set({ status: "done" }).where(eq(issues.id, issueId));
|
||||
|
||||
@@ -24,6 +24,8 @@ const {
|
||||
fakeServer,
|
||||
heartbeatServiceFactoryMock,
|
||||
heartbeatServiceMock,
|
||||
issueThreadInteractionServiceFactoryMock,
|
||||
issueThreadInteractionServiceMock,
|
||||
loadConfigMock,
|
||||
resolveHeartbeatSchedulingSuppressionMock,
|
||||
routineServiceFactoryMock,
|
||||
@@ -69,6 +71,10 @@ const {
|
||||
tickTimers: vi.fn(async () => ({ checked: 0, enqueued: 0, skipped: 0 })),
|
||||
};
|
||||
const heartbeatServiceFactoryMock = vi.fn(() => heartbeatServiceMock);
|
||||
const issueThreadInteractionServiceMock = {
|
||||
sweepSupersededPendingRequestConfirmations: vi.fn(async () => ({ expired: 0 })),
|
||||
};
|
||||
const issueThreadInteractionServiceFactoryMock = vi.fn(() => issueThreadInteractionServiceMock);
|
||||
const environmentCustomImagesServiceMock = {
|
||||
cleanupExpiredSetupSessions: vi.fn(async () => ({ scanned: 0, timedOut: 0, failed: 0 })),
|
||||
};
|
||||
@@ -111,6 +117,8 @@ const {
|
||||
fakeServer,
|
||||
heartbeatServiceFactoryMock,
|
||||
heartbeatServiceMock,
|
||||
issueThreadInteractionServiceFactoryMock,
|
||||
issueThreadInteractionServiceMock,
|
||||
loadConfigMock,
|
||||
resolveHeartbeatSchedulingSuppressionMock,
|
||||
routineServiceFactoryMock,
|
||||
@@ -235,6 +243,7 @@ vi.mock("../services/index.js", () => ({
|
||||
environmentCustomImageService: environmentCustomImagesServiceFactoryMock,
|
||||
externalObjectService: externalObjectsServiceFactoryMock,
|
||||
heartbeatService: heartbeatServiceFactoryMock,
|
||||
issueThreadInteractionService: issueThreadInteractionServiceFactoryMock,
|
||||
issueService: vi.fn(() => ({ update: vi.fn(async () => null) })),
|
||||
instanceSettingsService: vi.fn(() => ({
|
||||
getExperimental: vi.fn(async () => ({
|
||||
|
||||
@@ -51,6 +51,7 @@ import {
|
||||
decisionRetentionService,
|
||||
externalObjectService,
|
||||
heartbeatService,
|
||||
issueThreadInteractionService,
|
||||
issueService,
|
||||
instanceSettingsService,
|
||||
reconcileBuiltInAgentsOnStartup,
|
||||
@@ -561,6 +562,11 @@ export async function startServer(): Promise<StartedServer> {
|
||||
if (toolOAuthBackfill.sanitizedConnections > 0 || toolOAuthBackfill.migratedConnections > 0) {
|
||||
logger.info(toolOAuthBackfill, "Backfilled legacy tool OAuth credentials into company secrets");
|
||||
}
|
||||
const confirmationSweep = await issueThreadInteractionService(db as any)
|
||||
.sweepSupersededPendingRequestConfirmations();
|
||||
if (confirmationSweep.expired > 0) {
|
||||
logger.info(confirmationSweep, "Expired pending confirmations superseded by newer agent requests");
|
||||
}
|
||||
if (config.deploymentMode === "authenticated") {
|
||||
const {
|
||||
createBetterAuthHandler,
|
||||
|
||||
@@ -43,6 +43,7 @@ export function attentionRoutes(db: Db) {
|
||||
includeDismissed,
|
||||
archived,
|
||||
all,
|
||||
allowUnscopedAll: all,
|
||||
activitySince,
|
||||
activityUntil,
|
||||
queue,
|
||||
|
||||
@@ -47,7 +47,11 @@ import type {
|
||||
import { badRequest } from "../errors.js";
|
||||
import { PRODUCTIVITY_REVIEW_ORIGIN_KIND } from "./productivity-review.js";
|
||||
import { budgetService } from "./budgets.js";
|
||||
import { issueService } from "./issues.js";
|
||||
import {
|
||||
BLOCKER_ATTENTION_MAX_DEPTH,
|
||||
BLOCKER_ATTENTION_MAX_NODES,
|
||||
issueService,
|
||||
} from "./issues.js";
|
||||
import { parseIssueExecutionState } from "./issue-execution-policy.js";
|
||||
import { isProspectiveBlockedTransition } from "./routable-blocked.js";
|
||||
import { decisionQueueService } from "./decision-queues.js";
|
||||
@@ -102,6 +106,13 @@ const OPEN_DECISION_DEFAULT_LIMIT = 500;
|
||||
const OPEN_DECISION_MAX_LIMIT = 1_000;
|
||||
const ATTENTION_PAGE_DEFAULT_LIMIT = 50;
|
||||
const ATTENTION_PAGE_MAX_LIMIT = 100;
|
||||
const ATTENTION_GRAPH_QUERY_CHUNK_SIZE = 500;
|
||||
|
||||
function chunkValues<T>(values: T[], size: number): T[][] {
|
||||
const chunks: T[][] = [];
|
||||
for (let index = 0; index < values.length; index += size) chunks.push(values.slice(index, index + size));
|
||||
return chunks;
|
||||
}
|
||||
|
||||
type IssueSummaryRow = {
|
||||
id: string;
|
||||
@@ -223,10 +234,11 @@ function isPlanDocumentTarget(payload: Record<string, unknown>) {
|
||||
return target.type === "issue_document" && target.key === "plan";
|
||||
}
|
||||
|
||||
function issueContext(issue: IssueSummaryRow | null | undefined) {
|
||||
function issueContext(issue: IssueSummaryRow | IssueSubjectRow | null | undefined) {
|
||||
const summary = issue && "project" in issue ? issue : null;
|
||||
return {
|
||||
project: issue?.project ?? null,
|
||||
workspace: issue?.workspace ?? null,
|
||||
project: summary?.project ?? null,
|
||||
workspace: summary?.workspace ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -405,6 +417,32 @@ function compareAttentionItems(left: AttentionItem, right: AttentionItem) {
|
||||
return left.dedupKey.localeCompare(right.dedupKey);
|
||||
}
|
||||
|
||||
function blockedTaskCount(item: AttentionItem) {
|
||||
return item.sourceKind === "blocker_attention"
|
||||
&& item.detail?.kind === "blocker"
|
||||
&& typeof item.detail.blockedTaskCount === "number"
|
||||
? item.detail.blockedTaskCount
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Preserve the selected desk sort for every row slot while ordering blocker
|
||||
* rows by the amount of work they hold up. */
|
||||
function orderBlockedAttentionByWeight(
|
||||
items: AttentionItem[],
|
||||
fallback: (left: AttentionItem, right: AttentionItem) => number,
|
||||
) {
|
||||
const blockers = items
|
||||
.filter((item) => blockedTaskCount(item) !== null)
|
||||
.sort((left, right) => {
|
||||
const weightDiff = (blockedTaskCount(right) ?? 0) - (blockedTaskCount(left) ?? 0);
|
||||
return weightDiff !== 0 ? weightDiff : fallback(left, right);
|
||||
});
|
||||
if (blockers.length < 2) return items;
|
||||
|
||||
let blockerIndex = 0;
|
||||
return items.map((item) => blockedTaskCount(item) === null ? item : blockers[blockerIndex++]!);
|
||||
}
|
||||
|
||||
function sourceKey(sourceKind: AttentionSourceKind, sourceId: string) {
|
||||
return `${sourceKind}:${sourceId}`;
|
||||
}
|
||||
@@ -454,6 +492,12 @@ function isDecideNow(item: AttentionItem, now: number) {
|
||||
return bucket === 0 && deadline <= endOfUtcDay(now);
|
||||
}
|
||||
|
||||
/** Surfaced today (arrival). Mirrors `attentionIsNewToday` in `ui/src/lib/attention.ts`. */
|
||||
function isNewToday(item: AttentionItem, now: number) {
|
||||
const ts = timestamp(item.createdAt);
|
||||
return ts > 0 && ts >= startOfUtcDay(now);
|
||||
}
|
||||
|
||||
function compareDecideItems(left: AttentionItem, right: AttentionItem, now: number) {
|
||||
const [leftBucket, leftDeadline] = decideOrder(left, now);
|
||||
const [rightBucket, rightDeadline] = decideOrder(right, now);
|
||||
@@ -662,6 +706,32 @@ function interactionVerbs(kind: string, payload: Record<string, unknown>) {
|
||||
);
|
||||
}
|
||||
|
||||
function collapsePendingConfirmationsToNewest<T extends {
|
||||
id: string;
|
||||
issueId: string;
|
||||
kind: string;
|
||||
createdAt: Date;
|
||||
}>(rows: T[]) {
|
||||
const newestByGroup = new Map<string, T>();
|
||||
for (const row of rows) {
|
||||
if (row.kind !== "request_confirmation") continue;
|
||||
const groupKey = `${row.issueId}:${row.kind}`;
|
||||
const newest = newestByGroup.get(groupKey);
|
||||
if (
|
||||
!newest
|
||||
|| row.createdAt.getTime() > newest.createdAt.getTime()
|
||||
|| (row.createdAt.getTime() === newest.createdAt.getTime() && row.id > newest.id)
|
||||
) {
|
||||
newestByGroup.set(groupKey, row);
|
||||
}
|
||||
}
|
||||
|
||||
return rows.filter((row) => (
|
||||
row.kind !== "request_confirmation"
|
||||
|| newestByGroup.get(`${row.issueId}:${row.kind}`)?.id === row.id
|
||||
));
|
||||
}
|
||||
|
||||
function budgetObservedPercent(amountObserved: number, amountLimit: number) {
|
||||
return amountLimit > 0 ? Math.round((amountObserved / amountLimit) * 10_000) / 100 : 0;
|
||||
}
|
||||
@@ -825,6 +895,94 @@ async function blockingIssueMap(db: Db, companyId: string, blockedIssueIds: Arra
|
||||
return map;
|
||||
}
|
||||
|
||||
type BlockedWorkEdge = {
|
||||
fromIssueId: string | null;
|
||||
issueId: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Counts open work held behind each blocker. The walk starts with explicit
|
||||
* dependents, then follows both further dependency edges and issue children.
|
||||
* Per-root visited sets make corrupt cycles harmless; the blocker analyzer's
|
||||
* existing traversal caps bound unusually large graphs.
|
||||
*/
|
||||
async function blockedWorkCountMap(db: Db, companyId: string, blockerIssueIds: string[]) {
|
||||
const rootIds = [...new Set(blockerIssueIds)];
|
||||
const seenByRoot = new Map(rootIds.map((rootId) => [rootId, new Set<string>()]));
|
||||
if (rootIds.length === 0) return new Map<string, number>();
|
||||
|
||||
const loadEdges = async (fromIssueIds: string[], includeChildren: boolean) => {
|
||||
const rows: BlockedWorkEdge[] = [];
|
||||
for (const chunk of chunkValues(fromIssueIds, ATTENTION_GRAPH_QUERY_CHUNK_SIZE)) {
|
||||
const dependentRowsPromise: Promise<BlockedWorkEdge[]> = db
|
||||
.select({
|
||||
fromIssueId: issueRelations.issueId,
|
||||
issueId: issues.id,
|
||||
})
|
||||
.from(issueRelations)
|
||||
.innerJoin(issues, eq(issueRelations.relatedIssueId, issues.id))
|
||||
.where(and(
|
||||
eq(issueRelations.companyId, companyId),
|
||||
eq(issueRelations.type, "blocks"),
|
||||
inArray(issueRelations.issueId, chunk),
|
||||
eq(issues.companyId, companyId),
|
||||
isNull(issues.hiddenAt),
|
||||
notInArray(issues.status, ["done", "cancelled"]),
|
||||
));
|
||||
const childRowsPromise: Promise<BlockedWorkEdge[]> = includeChildren
|
||||
? db
|
||||
.select({
|
||||
fromIssueId: issues.parentId,
|
||||
issueId: issues.id,
|
||||
})
|
||||
.from(issues)
|
||||
.where(and(
|
||||
eq(issues.companyId, companyId),
|
||||
inArray(issues.parentId, chunk),
|
||||
isNull(issues.hiddenAt),
|
||||
notInArray(issues.status, ["done", "cancelled"]),
|
||||
))
|
||||
: Promise.resolve([]);
|
||||
const [dependentRows, childRows] = await Promise.all([dependentRowsPromise, childRowsPromise]);
|
||||
rows.push(...dependentRows, ...childRows);
|
||||
}
|
||||
return rows;
|
||||
};
|
||||
|
||||
let rootsByFrontierId = new Map<string, Set<string>>();
|
||||
for (const edge of await loadEdges(rootIds, false)) {
|
||||
if (!edge.fromIssueId || edge.issueId === edge.fromIssueId) continue;
|
||||
const seen = seenByRoot.get(edge.fromIssueId);
|
||||
if (!seen || seen.size >= BLOCKER_ATTENTION_MAX_NODES || seen.has(edge.issueId)) continue;
|
||||
seen.add(edge.issueId);
|
||||
const roots = rootsByFrontierId.get(edge.issueId) ?? new Set<string>();
|
||||
roots.add(edge.fromIssueId);
|
||||
rootsByFrontierId.set(edge.issueId, roots);
|
||||
}
|
||||
|
||||
for (let depth = 1; rootsByFrontierId.size > 0 && depth < BLOCKER_ATTENTION_MAX_DEPTH; depth += 1) {
|
||||
const nextRootsByFrontierId = new Map<string, Set<string>>();
|
||||
const edges = await loadEdges([...rootsByFrontierId.keys()], true);
|
||||
for (const edge of edges) {
|
||||
if (!edge.fromIssueId) continue;
|
||||
const roots = rootsByFrontierId.get(edge.fromIssueId);
|
||||
if (!roots) continue;
|
||||
for (const rootId of roots) {
|
||||
if (edge.issueId === rootId) continue;
|
||||
const seen = seenByRoot.get(rootId);
|
||||
if (!seen || seen.size >= BLOCKER_ATTENTION_MAX_NODES || seen.has(edge.issueId)) continue;
|
||||
seen.add(edge.issueId);
|
||||
const nextRoots = nextRootsByFrontierId.get(edge.issueId) ?? new Set<string>();
|
||||
nextRoots.add(rootId);
|
||||
nextRootsByFrontierId.set(edge.issueId, nextRoots);
|
||||
}
|
||||
}
|
||||
rootsByFrontierId = nextRootsByFrontierId;
|
||||
}
|
||||
|
||||
return new Map([...seenByRoot].map(([rootId, seen]) => [rootId, seen.size]));
|
||||
}
|
||||
|
||||
/**
|
||||
* The task that blocks `issue` — never `issue` itself.
|
||||
*
|
||||
@@ -967,11 +1125,12 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
inArray(issueThreadInteractions.status, [...PENDING_INTERACTION_STATUSES]),
|
||||
))
|
||||
.orderBy(desc(issueThreadInteractions.updatedAt), desc(issueThreadInteractions.id));
|
||||
const interactionIssueMap = await issueSummaryMap(db, companyId, interactionRows.map((row) => row.issueId));
|
||||
const interactionImageMap = await issueImageMap(db, companyId, interactionRows.map((row) => row.issueId));
|
||||
const interactionPlanDocumentMap = await planDocumentMap(db, companyId, interactionRows.map((row) => row.issueId));
|
||||
const visibleInteractionRows = collapsePendingConfirmationsToNewest(interactionRows);
|
||||
const interactionIssueMap = await issueSummaryMap(db, companyId, visibleInteractionRows.map((row) => row.issueId));
|
||||
const interactionImageMap = await issueImageMap(db, companyId, visibleInteractionRows.map((row) => row.issueId));
|
||||
const interactionPlanDocumentMap = await planDocumentMap(db, companyId, visibleInteractionRows.map((row) => row.issueId));
|
||||
|
||||
for (const interaction of interactionRows) {
|
||||
for (const interaction of visibleInteractionRows) {
|
||||
const issue = interactionIssueMap.get(interaction.issueId) ?? null;
|
||||
const payload = readRecord(interaction.payload);
|
||||
const detail = interactionDetail({
|
||||
@@ -1018,7 +1177,7 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
}));
|
||||
}
|
||||
|
||||
const openDecisions = await db.select({
|
||||
const openDecisionQuery = db.select({
|
||||
id: decisions.id,
|
||||
bundleId: decisions.bundleId,
|
||||
originAgentId: decisions.originAgentId,
|
||||
@@ -1031,8 +1190,10 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
createdAt: decisions.createdAt,
|
||||
updatedAt: decisions.updatedAt,
|
||||
}).from(decisions).where(and(eq(decisions.companyId, companyId), eq(decisions.status, "open")))
|
||||
.orderBy(desc(decisions.updatedAt), desc(decisions.id))
|
||||
.limit(openDecisionLimit);
|
||||
.orderBy(desc(decisions.updatedAt), desc(decisions.id));
|
||||
const openDecisions = options.all
|
||||
? await openDecisionQuery
|
||||
: await openDecisionQuery.limit(openDecisionLimit);
|
||||
const decisionIssueMap = await issueSummaryMap(db, companyId, openDecisions.map((decision) => decision.originIssueId));
|
||||
// Bundle titles let the feed render a single "Agent proposed N decisions"
|
||||
// group header over sibling decisions (v1 still decides each independently).
|
||||
@@ -1251,14 +1412,37 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
}
|
||||
|
||||
const blockedIssues = await issueService(db).list(companyId, { status: "blocked", includeBlockedBy: true });
|
||||
const blockedIssueSummaries = await issueSummaryMap(db, companyId, blockedIssues.map((issue) => issue.id));
|
||||
const blockedImageMap = await issueImageMap(db, companyId, blockedIssues.map((issue) => issue.id));
|
||||
const blockingIssues = await blockingIssueMap(db, companyId, blockedIssues.map((issue) => issue.id));
|
||||
for (const issue of blockedIssues as Array<IssueSubjectRow & {
|
||||
blockerAttention?: { state?: string; sampleStalledBlockerIdentifier?: string | null; sampleBlockerIdentifier?: string | null } | null;
|
||||
type BlockedAttentionIssue = IssueSubjectRow & {
|
||||
blockerAttention?: {
|
||||
state?: string;
|
||||
sampleStalledBlockerIdentifier?: string | null;
|
||||
sampleBlockerIdentifier?: string | null;
|
||||
blockingTreeLive?: boolean;
|
||||
terminalBlockerIssueId?: string | null;
|
||||
} | null;
|
||||
unblockDescriptor?: { owner: { userId: string } | { agentId: string } | "board"; action: string } | null;
|
||||
blockedTransitionAt?: Date | null;
|
||||
}>) {
|
||||
};
|
||||
const typedBlockedIssues = blockedIssues as BlockedAttentionIssue[];
|
||||
const terminalBlockerIssueIds = typedBlockedIssues
|
||||
.map((issue) => issue.blockerAttention?.terminalBlockerIssueId)
|
||||
.filter((issueId): issueId is string => Boolean(issueId));
|
||||
const blockedIssueSummaries = await issueSummaryMap(db, companyId, blockedIssues.map((issue) => issue.id));
|
||||
const terminalBlockerSummaries = await issueSummaryMap(db, companyId, terminalBlockerIssueIds);
|
||||
const blockerImageMap = await issueImageMap(
|
||||
db,
|
||||
companyId,
|
||||
[...blockedIssues.map((issue) => issue.id), ...terminalBlockerIssueIds],
|
||||
);
|
||||
const blockingIssues = await blockingIssueMap(db, companyId, blockedIssues.map((issue) => issue.id));
|
||||
const terminalCandidates = new Map<string, {
|
||||
issue: BlockedAttentionIssue;
|
||||
issueSummary: IssueSummaryRow | null;
|
||||
terminalSummary: IssueSummaryRow | IssueSubjectRow;
|
||||
state: "stalled" | "needs_attention";
|
||||
}>();
|
||||
|
||||
for (const issue of typedBlockedIssues) {
|
||||
const descriptor = issue.unblockDescriptor;
|
||||
const humanOwnerMatches = descriptor?.owner === "board"
|
||||
|| (descriptor?.owner && "userId" in descriptor.owner && descriptor.owner.userId === options.userId);
|
||||
@@ -1286,44 +1470,62 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
detail: {
|
||||
kind: "blocker",
|
||||
blockingIssue: resolveBlockingIssue(issue, blockingIssues.get(issue.id)),
|
||||
images: issueImages(blockedImageMap, issue.id),
|
||||
images: issueImages(blockerImageMap, issue.id),
|
||||
},
|
||||
}));
|
||||
}
|
||||
const blockerAttention = issue.blockerAttention;
|
||||
if (blockerAttention?.state !== "stalled" && blockerAttention?.state !== "needs_attention") continue;
|
||||
if (blockerAttention.blockingTreeLive) continue;
|
||||
const issueSummary = blockedIssueSummaries.get(issue.id) ?? null;
|
||||
const summarizedIssue = issueSummary ?? issue;
|
||||
const sampledBlocker = blockerAttention.sampleStalledBlockerIdentifier ?? blockerAttention.sampleBlockerIdentifier;
|
||||
const blockingIssue = resolveBlockingIssue(issue, blockingIssues.get(issue.id), sampledBlocker);
|
||||
// The dedup key keeps its original fallback chain (including the issue's
|
||||
// own identifier) on purpose: it is the stable identity a dismissal is
|
||||
// recorded against, so narrowing it would resurrect dismissed rows.
|
||||
const sample = sampledBlocker ?? issue.identifier ?? issue.id;
|
||||
const dedupKey = `blocker:${issue.id}:${sample}`;
|
||||
const terminalIssueId = blockerAttention.terminalBlockerIssueId ?? issue.id;
|
||||
const terminalSummary = terminalBlockerSummaries.get(terminalIssueId)
|
||||
?? (terminalIssueId === issue.id ? issueSummary ?? issue : null);
|
||||
if (!terminalSummary) continue;
|
||||
const current = terminalCandidates.get(terminalIssueId);
|
||||
if (!current || issue.updatedAt > current.issue.updatedAt) {
|
||||
terminalCandidates.set(terminalIssueId, {
|
||||
issue,
|
||||
issueSummary,
|
||||
terminalSummary,
|
||||
state: blockerAttention.state,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const blockedWorkCounts = await blockedWorkCountMap(db, companyId, [...terminalCandidates.keys()]);
|
||||
for (const [terminalIssueId, candidate] of terminalCandidates) {
|
||||
const blockedTaskCount = blockedWorkCounts.get(terminalIssueId) ?? 0;
|
||||
const taskLabel = blockedTaskCount === 1 ? "task" : "tasks";
|
||||
const dedupKey = `blocker:${terminalIssueId}`;
|
||||
add(createItem({
|
||||
companyId,
|
||||
sourceKind: "blocker_attention",
|
||||
subject: issueSubject(prefix, summarizedIssue),
|
||||
whyNow: blockerAttention.state === "needs_attention"
|
||||
? "Blocked dependency chain needs human attention."
|
||||
: "Blocked dependency chain is stalled and needs a human to choose the next owner or action.",
|
||||
subject: issueSubject(prefix, candidate.terminalSummary),
|
||||
whyNow: candidate.state === "needs_attention"
|
||||
? `Blocks ${blockedTaskCount} ${taskLabel} and needs human attention.`
|
||||
: `Blocks ${blockedTaskCount} ${taskLabel}; choose the next owner or action.`,
|
||||
decisionVerbs: decisionVerbs(
|
||||
{ id: "unblock", label: "Unblock", description: "Repair or replace the stalled blocker path." },
|
||||
{ id: "reassign", label: "Reassign", description: "Assign the stalled blocker to a live owner." },
|
||||
{ id: "nudge", label: "Nudge", description: "Wake or prompt the current owner." },
|
||||
),
|
||||
inlineResolvable: false,
|
||||
entryRule: `blocked issue has blockerAttention.state = '${blockerAttention.state}'`,
|
||||
exitRule: "Blocker chain is no longer stalled or the issue leaves blocked status.",
|
||||
entryRule: `terminal blocker has a non-live blockerAttention.state = '${candidate.state}'`,
|
||||
exitRule: "The blocking tree becomes live or no open work remains blocked.",
|
||||
dedupKey,
|
||||
severity: "high",
|
||||
activityAt: toIso(issue.updatedAt),
|
||||
createdAt: toIso(issue.createdAt),
|
||||
updatedAt: toIso(issue.updatedAt),
|
||||
relatedIssue: null,
|
||||
...issueContext(issueSummary),
|
||||
detail: { kind: "blocker", blockingIssue, images: issueImages(blockedImageMap, issue.id) },
|
||||
activityAt: toIso(candidate.terminalSummary.updatedAt),
|
||||
createdAt: toIso(candidate.terminalSummary.createdAt),
|
||||
updatedAt: toIso(candidate.terminalSummary.updatedAt),
|
||||
relatedIssue: candidate.issueSummary ? issueSubject(prefix, candidate.issueSummary) : null,
|
||||
...issueContext(candidate.terminalSummary),
|
||||
detail: {
|
||||
kind: "blocker",
|
||||
blockingIssue: null,
|
||||
blockedTaskCount,
|
||||
images: issueImages(blockerImageMap, terminalIssueId),
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -1653,10 +1855,13 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
|
||||
const sort = options.sort ?? "activity";
|
||||
if (sort !== "activity" && sort !== "decide") throw badRequest("sort must be 'activity' or 'decide'");
|
||||
const rankedItems = visibleItems
|
||||
.sort(sort === "decide"
|
||||
? (left, right) => compareDecideItems(left, right, now)
|
||||
: compareAttentionItems)
|
||||
const selectedComparator = sort === "decide"
|
||||
? (left: AttentionItem, right: AttentionItem) => compareDecideItems(left, right, now)
|
||||
: compareAttentionItems;
|
||||
const rankedItems = orderBlockedAttentionByWeight(
|
||||
visibleItems.sort(selectedComparator),
|
||||
selectedComparator,
|
||||
)
|
||||
.map((item, index) => ({ ...item, rank: index + 1 }));
|
||||
let items: AttentionItem[];
|
||||
let nextCursor: string | null;
|
||||
@@ -1726,7 +1931,11 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions
|
||||
companyId,
|
||||
generatedAt: new Date().toISOString(),
|
||||
totalCount: rankedItems.length,
|
||||
decideNowCount: rankedItems.filter((item) => isDecideNow(item, now)).length,
|
||||
// Desk badge: distinct items that surfaced
|
||||
// today OR carry an explicit decide-by deadline due today/past. Counted
|
||||
// over the full ranked set (pre-pagination) so the sidebar badge stays
|
||||
// company-wide accurate even on a small first page.
|
||||
deskBadgeCount: rankedItems.filter((item) => isNewToday(item, now) || isDecideNow(item, now)).length,
|
||||
nextCursor,
|
||||
countsBySourceKind,
|
||||
items,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { and, asc, eq, inArray, isNotNull, isNull } from "drizzle-orm";
|
||||
import { and, asc, desc, eq, inArray, isNotNull, isNull, ne } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
agents,
|
||||
@@ -348,6 +348,14 @@ function buildStaleTargetResult(
|
||||
} as const;
|
||||
}
|
||||
|
||||
function buildSupersededByNewerRequestResult(replacementInteractionId: string) {
|
||||
return {
|
||||
version: 1,
|
||||
outcome: "superseded_by_newer_request",
|
||||
supersededByInteractionId: replacementInteractionId,
|
||||
} as const;
|
||||
}
|
||||
|
||||
function buildAdministrativeOutcomeResult(
|
||||
row: IssueThreadInteractionRow,
|
||||
outcome: "withdrawn" | "issue_closed",
|
||||
@@ -1207,6 +1215,83 @@ export function issueThreadInteractionService(db: Db) {
|
||||
return row ? hydrateInteraction(row) : null;
|
||||
},
|
||||
|
||||
sweepSupersededPendingRequestConfirmations: async () => {
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(issueThreadInteractions)
|
||||
.where(and(
|
||||
eq(issueThreadInteractions.kind, "request_confirmation"),
|
||||
eq(issueThreadInteractions.status, "pending"),
|
||||
isNotNull(issueThreadInteractions.createdByAgentId),
|
||||
))
|
||||
.orderBy(
|
||||
asc(issueThreadInteractions.companyId),
|
||||
asc(issueThreadInteractions.issueId),
|
||||
asc(issueThreadInteractions.kind),
|
||||
asc(issueThreadInteractions.createdByAgentId),
|
||||
desc(issueThreadInteractions.createdAt),
|
||||
desc(issueThreadInteractions.id),
|
||||
);
|
||||
|
||||
const newestByGroup = new Map<string, IssueThreadInteractionRow>();
|
||||
const supersededRows: Array<{
|
||||
row: IssueThreadInteractionRow;
|
||||
replacementInteractionId: string;
|
||||
}> = [];
|
||||
for (const row of rows) {
|
||||
if (!row.createdByAgentId) continue;
|
||||
const groupKey = `${row.companyId}:${row.issueId}:${row.kind}:${row.createdByAgentId}`;
|
||||
const newest = newestByGroup.get(groupKey);
|
||||
if (!newest) {
|
||||
newestByGroup.set(groupKey, row);
|
||||
continue;
|
||||
}
|
||||
supersededRows.push({ row, replacementInteractionId: newest.id });
|
||||
}
|
||||
|
||||
if (supersededRows.length === 0) return { expired: 0 };
|
||||
|
||||
const now = new Date();
|
||||
const expired: IssueThreadInteraction[] = [];
|
||||
for (const { row, replacementInteractionId } of supersededRows) {
|
||||
const updated = await db.transaction(async (tx) => {
|
||||
const [updatedRow] = await tx
|
||||
.update(issueThreadInteractions)
|
||||
.set({
|
||||
status: "expired",
|
||||
result: buildSupersededByNewerRequestResult(replacementInteractionId),
|
||||
resolvedByAgentId: null,
|
||||
resolvedByUserId: null,
|
||||
resolvedAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(and(
|
||||
eq(issueThreadInteractions.id, row.id),
|
||||
eq(issueThreadInteractions.status, "pending"),
|
||||
))
|
||||
.returning();
|
||||
if (!updatedRow) return null;
|
||||
await resolveLinkedToolActionRequests(tx, updatedRow, {
|
||||
status: "expired",
|
||||
fromStatuses: ["pending", "approved"],
|
||||
actor: {},
|
||||
now,
|
||||
});
|
||||
return updatedRow;
|
||||
});
|
||||
if (!updated) continue;
|
||||
expired.push(hydrateInteraction(updated));
|
||||
}
|
||||
|
||||
if (expired.length > 0) {
|
||||
for (const issueId of new Set(expired.map((interaction) => interaction.issueId))) {
|
||||
await touchIssue(db, issueId);
|
||||
}
|
||||
await emitResolvedInteractionsTelemetry(db, expired);
|
||||
}
|
||||
return { expired: expired.length };
|
||||
},
|
||||
|
||||
create: async (
|
||||
issue: { id: string; companyId: string },
|
||||
input: CreateIssueThreadInteraction,
|
||||
@@ -1270,20 +1355,19 @@ export function issueThreadInteractionService(db: Db) {
|
||||
}
|
||||
|
||||
let created: IssueThreadInteractionRow;
|
||||
let superseded: IssueThreadInteractionRow[] = [];
|
||||
try {
|
||||
// A terminal issue must not regain pending actionable cards. FOR SHARE
|
||||
// on the issue row serializes this insert against the terminal status
|
||||
// transition's row lock: either the close committed first and this
|
||||
// read rejects the create, or the insert commits before the close
|
||||
// proceeds and the close's expiry sweep collects the new row.
|
||||
// A terminal issue must not regain pending actionable cards. FOR UPDATE
|
||||
// on the issue row serializes this insert both against terminal status
|
||||
// transitions and against concurrent confirmations on the same issue.
|
||||
// Idempotent reuse above stays allowed so retries of a pre-close
|
||||
// create keep returning the (by now expired) original.
|
||||
created = await db.transaction(async (tx) => {
|
||||
const result = await db.transaction(async (tx) => {
|
||||
const [issueRow] = await tx
|
||||
.select({ status: issues.status })
|
||||
.from(issues)
|
||||
.where(and(eq(issues.id, issue.id), eq(issues.companyId, issue.companyId)))
|
||||
.for("share");
|
||||
.for("update");
|
||||
if (!issueRow || isTerminalIssueStatus(issueRow.status)) {
|
||||
throw conflict("Cannot create an interaction on a closed issue");
|
||||
}
|
||||
@@ -1305,8 +1389,43 @@ export function issueThreadInteractionService(db: Db) {
|
||||
payload: data.payload,
|
||||
})
|
||||
.returning();
|
||||
return row;
|
||||
|
||||
if (data.kind !== "request_confirmation" || !actor.agentId) {
|
||||
return { row, supersededRows: [] };
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const supersededRows = await tx
|
||||
.update(issueThreadInteractions)
|
||||
.set({
|
||||
status: "expired",
|
||||
result: buildSupersededByNewerRequestResult(row.id),
|
||||
resolvedByAgentId: actor.agentId,
|
||||
resolvedByUserId: actor.userId ?? null,
|
||||
resolvedAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(and(
|
||||
eq(issueThreadInteractions.companyId, issue.companyId),
|
||||
eq(issueThreadInteractions.issueId, issue.id),
|
||||
eq(issueThreadInteractions.kind, data.kind),
|
||||
eq(issueThreadInteractions.createdByAgentId, actor.agentId),
|
||||
eq(issueThreadInteractions.status, "pending"),
|
||||
ne(issueThreadInteractions.id, row.id),
|
||||
))
|
||||
.returning();
|
||||
for (const supersededRow of supersededRows) {
|
||||
await resolveLinkedToolActionRequests(tx, supersededRow, {
|
||||
status: "expired",
|
||||
fromStatuses: ["pending", "approved"],
|
||||
actor,
|
||||
now,
|
||||
});
|
||||
}
|
||||
return { row, supersededRows };
|
||||
});
|
||||
created = result.row;
|
||||
superseded = result.supersededRows;
|
||||
} catch (error) {
|
||||
if (!data.idempotencyKey || !isIssueThreadInteractionIdempotencyConflict(error)) {
|
||||
throw error;
|
||||
@@ -1326,6 +1445,9 @@ export function issueThreadInteractionService(db: Db) {
|
||||
}
|
||||
|
||||
await touchIssue(db, issue.id);
|
||||
if (superseded.length > 0) {
|
||||
await emitResolvedInteractionsTelemetry(db, superseded.map(hydrateInteraction));
|
||||
}
|
||||
return hydrateInteraction(created);
|
||||
},
|
||||
|
||||
|
||||
@@ -1879,8 +1879,8 @@ function lowTrustBoundaryIssueCondition(
|
||||
}
|
||||
|
||||
const BLOCKER_ATTENTION_OPEN_RECOVERY_TERMINAL_STATUSES = ["done", "cancelled"];
|
||||
const BLOCKER_ATTENTION_MAX_DEPTH = 8;
|
||||
const BLOCKER_ATTENTION_MAX_NODES = 2000;
|
||||
export const BLOCKER_ATTENTION_MAX_DEPTH = 8;
|
||||
export const BLOCKER_ATTENTION_MAX_NODES = 2000;
|
||||
const BLOCKER_ATTENTION_INVOKABLE_AGENT_STATUSES = new Set(["active", "idle", "running", "error"]);
|
||||
|
||||
type IssueBlockerAttentionNode = {
|
||||
@@ -2049,6 +2049,8 @@ function createIssueBlockerAttention(input: Partial<IssueBlockerAttention> = {})
|
||||
pendingFinalizeBlockerIssueIds: input.pendingFinalizeBlockerIssueIds ?? [],
|
||||
sampleBlockerIdentifier: input.sampleBlockerIdentifier ?? null,
|
||||
sampleStalledBlockerIdentifier: input.sampleStalledBlockerIdentifier ?? null,
|
||||
blockingTreeLive: input.blockingTreeLive ?? false,
|
||||
terminalBlockerIssueId: input.terminalBlockerIssueId ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2534,6 +2536,7 @@ async function listIssueBlockerAttentionMap(
|
||||
stalled: boolean;
|
||||
sampleBlockerIdentifier: string | null;
|
||||
sampleStalledBlockerIdentifier: string | null;
|
||||
terminalBlockerIssueId?: string | null;
|
||||
};
|
||||
const classifyPath = (
|
||||
nodeId: string,
|
||||
@@ -2562,16 +2565,34 @@ async function listIssueBlockerAttentionMap(
|
||||
if (hasWaitingPath) {
|
||||
return { covered: true, stalled: false, sampleBlockerIdentifier: nodeSample, sampleStalledBlockerIdentifier: null };
|
||||
}
|
||||
return { covered: false, stalled: true, sampleBlockerIdentifier: nodeSample, sampleStalledBlockerIdentifier: nodeSample };
|
||||
return {
|
||||
covered: false,
|
||||
stalled: true,
|
||||
sampleBlockerIdentifier: nodeSample,
|
||||
sampleStalledBlockerIdentifier: nodeSample,
|
||||
terminalBlockerIssueId: node.id,
|
||||
};
|
||||
}
|
||||
if (activeIssueIds.has(node.id)) {
|
||||
return { covered: true, stalled: false, sampleBlockerIdentifier: nodeSample, sampleStalledBlockerIdentifier: null };
|
||||
}
|
||||
if (node.status === "cancelled") {
|
||||
return { covered: false, stalled: false, sampleBlockerIdentifier: nodeSample, sampleStalledBlockerIdentifier: null };
|
||||
return {
|
||||
covered: false,
|
||||
stalled: false,
|
||||
sampleBlockerIdentifier: nodeSample,
|
||||
sampleStalledBlockerIdentifier: null,
|
||||
terminalBlockerIssueId: node.id,
|
||||
};
|
||||
}
|
||||
if (node.status === "backlog" && node.assigneeAgentId) {
|
||||
return { covered: false, stalled: false, sampleBlockerIdentifier: nodeSample, sampleStalledBlockerIdentifier: null };
|
||||
return {
|
||||
covered: false,
|
||||
stalled: false,
|
||||
sampleBlockerIdentifier: nodeSample,
|
||||
sampleStalledBlockerIdentifier: null,
|
||||
terminalBlockerIssueId: node.id,
|
||||
};
|
||||
}
|
||||
|
||||
const downstream = (edgesByIssueId.get(node.id) ?? []).filter((edge) => {
|
||||
@@ -2584,13 +2605,16 @@ async function listIssueBlockerAttentionMap(
|
||||
const classified = downstream.map((edge) => classifyPath(edge.blockerIssueId, nextSeen));
|
||||
const stalledChild = classified.find((result) => result.stalled || result.sampleStalledBlockerIdentifier);
|
||||
const sampleStalled = stalledChild?.sampleStalledBlockerIdentifier ?? null;
|
||||
const hardAttention = classified.find((result) => !result.covered && !result.stalled);
|
||||
const hardAttention = classified.find((result) =>
|
||||
!result.covered && !result.stalled && result.terminalBlockerIssueId
|
||||
) ?? classified.find((result) => !result.covered && !result.stalled);
|
||||
if (hardAttention) {
|
||||
return {
|
||||
covered: false,
|
||||
stalled: false,
|
||||
sampleBlockerIdentifier: hardAttention.sampleBlockerIdentifier,
|
||||
sampleStalledBlockerIdentifier: sampleStalled,
|
||||
terminalBlockerIssueId: hardAttention.terminalBlockerIssueId ?? null,
|
||||
};
|
||||
}
|
||||
const stalledEntry = classified.find((result) => result.stalled);
|
||||
@@ -2600,6 +2624,7 @@ async function listIssueBlockerAttentionMap(
|
||||
stalled: true,
|
||||
sampleBlockerIdentifier: stalledEntry.sampleBlockerIdentifier,
|
||||
sampleStalledBlockerIdentifier: sampleStalled,
|
||||
terminalBlockerIssueId: stalledEntry.terminalBlockerIssueId ?? null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
@@ -2613,11 +2638,46 @@ async function listIssueBlockerAttentionMap(
|
||||
if (node.assigneeAgentId) {
|
||||
const assignee = agentsById.get(node.assigneeAgentId);
|
||||
if (!assignee || assignee.companyId !== companyId || !BLOCKER_ATTENTION_INVOKABLE_AGENT_STATUSES.has(assignee.status)) {
|
||||
return { covered: false, stalled: false, sampleBlockerIdentifier: nodeSample, sampleStalledBlockerIdentifier: null };
|
||||
return {
|
||||
covered: false,
|
||||
stalled: false,
|
||||
sampleBlockerIdentifier: nodeSample,
|
||||
sampleStalledBlockerIdentifier: null,
|
||||
terminalBlockerIssueId: node.id,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { covered: false, stalled: false, sampleBlockerIdentifier: nodeSample, sampleStalledBlockerIdentifier: null };
|
||||
return {
|
||||
covered: false,
|
||||
stalled: false,
|
||||
sampleBlockerIdentifier: nodeSample,
|
||||
sampleStalledBlockerIdentifier: null,
|
||||
terminalBlockerIssueId: node.id,
|
||||
};
|
||||
};
|
||||
|
||||
const pathHasLiveWork = (nodeId: string, seen: Set<string>): boolean => {
|
||||
if (seen.has(nodeId)) return false;
|
||||
const node = nodesById.get(nodeId);
|
||||
if (!node || node.companyId !== companyId) return false;
|
||||
if (node.status === "in_progress" || activeIssueIds.has(node.id)) return true;
|
||||
|
||||
const nextSeen = new Set(seen);
|
||||
nextSeen.add(nodeId);
|
||||
return (edgesByIssueId.get(node.id) ?? []).some((edge) => {
|
||||
const blocker = nodesById.get(edge.blockerIssueId);
|
||||
if (blocker?.status === "done" && !pendingFinalizeBlockerIssueIds.has(edge.blockerIssueId)) return false;
|
||||
return pathHasLiveWork(edge.blockerIssueId, nextSeen);
|
||||
});
|
||||
};
|
||||
|
||||
const issueIdForSample = (sample: string | null | undefined) => {
|
||||
if (!sample) return null;
|
||||
for (const node of nodesById.values()) {
|
||||
if (node.id === sample || node.identifier === sample) return node.id;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
for (const root of roots) {
|
||||
@@ -2629,6 +2689,7 @@ async function listIssueBlockerAttentionMap(
|
||||
attentionMap.set(root.id, createIssueBlockerAttention({
|
||||
state: "needs_attention",
|
||||
reason: "attention_required",
|
||||
terminalBlockerIssueId: root.id,
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
@@ -2640,13 +2701,19 @@ async function listIssueBlockerAttentionMap(
|
||||
const coveredBlockerCount = classified.filter((entry) => entry.result.covered).length;
|
||||
const stalledBlockerCount = classified.filter((entry) => entry.result.stalled).length;
|
||||
const attentionBlockerCount = classified.length - coveredBlockerCount - stalledBlockerCount;
|
||||
const hardAttentionEntry = classified.find((entry) => !entry.result.covered && !entry.result.stalled);
|
||||
const stalledEntry = classified.find((entry) => entry.result.stalled);
|
||||
const hardAttentionEntry = classified.find((entry) =>
|
||||
!entry.result.covered && !entry.result.stalled && entry.result.terminalBlockerIssueId
|
||||
) ?? classified.find((entry) => !entry.result.covered && !entry.result.stalled);
|
||||
const stalledEntry = classified.find((entry) => entry.result.stalled && entry.result.terminalBlockerIssueId)
|
||||
?? classified.find((entry) => entry.result.stalled);
|
||||
const sampleEntry = hardAttentionEntry ?? stalledEntry ?? classified[0] ?? null;
|
||||
const sampleNode = sampleEntry ? nodesById.get(sampleEntry.edge.blockerIssueId) : null;
|
||||
const sampleStalledFromChain = classified
|
||||
.map((entry) => entry.result.sampleStalledBlockerIdentifier)
|
||||
.find((value) => value);
|
||||
const sampledTerminalIdentifier = sampleEntry?.result.stalled
|
||||
? sampleEntry.result.sampleStalledBlockerIdentifier ?? sampleEntry.result.sampleBlockerIdentifier
|
||||
: sampleEntry?.result.sampleBlockerIdentifier ?? blockerSampleIdentifier(sampleNode);
|
||||
|
||||
let state: IssueBlockerAttention["state"];
|
||||
let reason: IssueBlockerAttention["reason"];
|
||||
@@ -2676,6 +2743,9 @@ async function listIssueBlockerAttentionMap(
|
||||
sampleBlockerIdentifier: sampleEntry?.result.sampleBlockerIdentifier ?? blockerSampleIdentifier(sampleNode),
|
||||
sampleStalledBlockerIdentifier:
|
||||
stalledEntry?.result.sampleStalledBlockerIdentifier ?? sampleStalledFromChain ?? null,
|
||||
blockingTreeLive: topLevelEdges.some((edge) => pathHasLiveWork(edge.blockerIssueId, new Set([root.id]))),
|
||||
terminalBlockerIssueId:
|
||||
sampleEntry?.result.terminalBlockerIssueId ?? issueIdForSample(sampledTerminalIdentifier),
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user