mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-17 13:01:05 +01:00
## Thinking Path > - Paperclip helps people manage AI agents and their work. > - The inbox collects requests that need a human decision. > - Teams need to know who owns each request and who may act on it. > - A shared close operation must differ from hiding a card for one person. > - This pull request adds personal routing and durable outcomes to the existing attention service. > - People can claim or transfer work and inspect what another person did for them. > - Domain permissions still decide who may resolve each request. ## Linked Issues or Issue Description **Subsystem affected** Server, shared contracts, and database. This is the routing foundation for a stacked inbox UI change. **Problem or motivation** A company-wide attention feed does not give teams a clear personal queue. Archive, withdrawal, transfer, and decisions by another person need distinct scopes and records. **Proposed solution** Resolve a request audience from its addressee, task participants, and configured owners. Provide personal, unassigned, company, all-assignee, and archived views. Add claim, transfer, personal archive and snooze, shared withdrawal, receipts, and personal history. **Alternatives considered** A single shared inbox leaves ownership and personal hiding ambiguous. The service keeps one canonical request and projects its audience instead of copying requests for each person. **Roadmap alignment** This extends the existing Multiple Human Users and Agent Reviews and Approvals capabilities in ROADMAP.md. **Additional context** Refs #19363 and #19520 for the current inbox navigation and confirmation replacement rules. Refs #20268 for related actionable-request work. That PR filters actionability; this stack adds audience routing and personal outcomes. This is part 1 of a two-PR stack. The inbox UI PR #20961 targets this branch. ## What Changed - Add nullable company and project decision owners and a company budget owner. - Add audience views and personal badge counts to the canonical attention projections. - Add claim, transfer, withdrawal, personal archive, snooze, and restore operations with permission checks and activity records. Lock addressed transfers to the current addressee or routing administrators, and validate the recipient against canonical resolution policies. - Add receipts and scoped history for work handled by another person. - Keep closed-task requests and replaced confirmations out of current cards. - Add an idempotent migration and a concurrent receipt-history index. - Update typed fixtures so the existing UI remains compatible with the new contracts. ## Verification - Server layered typechecking passes, including all three test-tree partitions. - Seven routing and interaction-resolution suites pass all 249 tests against a dedicated external PostgreSQL test database on `4caecc21d8`. Six new regressions failed before the repair; they cover takeover followed by approval, legitimate delegation, excluded creators/review requesters, and unauthorized claims. - Prior focused verification covers private approval history and receipts, transfer visibility, audience escalation, withdrawal governance, hidden-card counts, per-recipient confirmation replacement, and SDK source contracts. - A synthetic three-person company passed 37 routing and lifecycle acceptance checks. The UI stack adds browser acceptance for the shared controls. - The complete [GitHub Actions CI matrix](https://github.com/paperclipai/paperclip/actions/runs/43134997331) passes on `4caecc21d891677323a7335f23b1a015cce24c13` (Linux/Node 24: typecheck, build, general and serialized tests, Runner support, browser shards, and aggregate gates). Greptile is 5/5 on that exact head with no open findings. The fresh security scan passes after explicitly rechecking the addressee-transfer repair. - `pnpm verify` reports exit 2 because a CI-global script changed; full CI supplies that broader coverage. Embedded PostgreSQL could not start on this Mac because shared-memory slots were exhausted, so local database checks use a separate external test database. Linux CI covers the embedded setup. ## Risks - Personal badge counts change to the viewer's assigned requests. Accessible feed totals and task membership keep their existing scope. - The migration adds nullable owner fields and a dismissal fingerprint. Its index runs outside a transaction. The migration is classified and rerunnable. - Routing changes the addressee used by resolution authorization. The current addressee or a routing administrator must authorize an addressed transfer; the recipient must satisfy writer access, canonical resolver exclusions, and task review policy under row locks. - The shared validator export barrel crosses 1,000 lines because it exports the new attention schemas. Schema implementation stays in the dedicated attention validator module. ## Model Used OpenAI GPT-6 through Codex. Used repository tools, code execution, and browser checks. This session does not expose a more specific runtime model ID or its context-window size. ## 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 described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal Paperclip ticket id - [x] I have run focused tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes (OpenAPI contracts and docs/api/attention.md) - [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: Scott Tong <scott@scottsmbpm5max.lan> Co-authored-by: Paperclip <noreply@paperclip.ing>
173 lines
8.6 KiB
TypeScript
173 lines
8.6 KiB
TypeScript
import { and, eq, gt, inArray, sql, type SQL } from "drizzle-orm";
|
|
import { heartbeatRuns, issueRecoveryActions, issueThreadInteractions, type Db } from "@paperclipai/db";
|
|
|
|
export const HUMAN_RECOVERY_OWNER_TYPES = ["user", "board"] as const;
|
|
const OPEN_RECOVERY_ATTENTION_STATUSES = ["active", "escalated"] as const;
|
|
|
|
export function recoveryActionAttentionCondition() {
|
|
return and(inArray(issueRecoveryActions.status, [...OPEN_RECOVERY_ATTENTION_STATUSES]),
|
|
inArray(issueRecoveryActions.ownerType, [...HUMAN_RECOVERY_OWNER_TYPES]))!;
|
|
}
|
|
export const ATTENTION_BUDGET_WARNING_PERCENT = 85;
|
|
export const ATTENTION_AGENT_ERROR_STATUS = "error";
|
|
|
|
function confirmationAudienceKey(row: { issueId: string; addresseeUserId?: string | null; addresseeAgentId?: string | null }) {
|
|
return `${row.issueId}:${row.addresseeUserId ?? ""}:${row.addresseeAgentId ?? ""}`;
|
|
}
|
|
|
|
function payloadFlag(payload: unknown, key: string) {
|
|
return Boolean(payload && typeof payload === "object" && key in payload && (payload as Record<string, unknown>)[key]);
|
|
}
|
|
|
|
/** Payload keys that bind a confirmation to one specific action (tool call, secret, app connection). */
|
|
const GOVERNED_CONFIRMATION_PAYLOAD_KEYS = ["toolAction", "secretProposal", "connectionAuthorization"] as const;
|
|
|
|
/** Governed confirmations gate one action; answering one never answers an ordinary ask, and vice versa. */
|
|
function governedAction(payload: unknown) {
|
|
// Truthy, not key presence: the summary read projects absent keys as JSON null.
|
|
return GOVERNED_CONFIRMATION_PAYLOAD_KEYS.some((key) => payloadFlag(payload, key));
|
|
}
|
|
|
|
/**
|
|
* A pending confirmation is superseded once the same issue has a newer
|
|
* ordinary confirmation — pending, or already answered/expired. Without the
|
|
* settled case, answering the newest card (from chat or anywhere else)
|
|
* resurfaces the older ask it replaced. Quality approvals stay
|
|
* independent; tool-action, secret-proposal and app-connection approvals gate
|
|
* one specific action, so they neither hide nor are hidden by a settled
|
|
* confirmation.
|
|
* Only an ask to the same recipient settles it, so one person's answer never
|
|
* hides a request addressed to someone else.
|
|
*/
|
|
export function collapsePendingConfirmationsToNewest<T extends {
|
|
id: string;
|
|
issueId: string;
|
|
kind: string;
|
|
createdAt: Date;
|
|
payload: unknown;
|
|
addresseeUserId?: string | null;
|
|
addresseeAgentId?: string | null;
|
|
}>(rows: T[], newestSettledConfirmationAt: ReadonlyMap<string, Date> = new Map()) {
|
|
const independent = (row: T) => payloadFlag(row.payload, "qualityReview") || governedAction(row.payload);
|
|
const newestByGroup = new Map<string, T>();
|
|
for (const row of rows) {
|
|
if (row.kind !== "request_confirmation" || independent(row)) continue;
|
|
const groupKey = confirmationAudienceKey(row);
|
|
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) => {
|
|
if (row.kind !== "request_confirmation" || independent(row)) return true;
|
|
if (newestByGroup.get(confirmationAudienceKey(row))?.id !== row.id) return false;
|
|
const settledAt = newestSettledConfirmationAt.get(confirmationAudienceKey(row));
|
|
return !settledAt || settledAt.getTime() <= row.createdAt.getTime();
|
|
});
|
|
}
|
|
|
|
// Cancelled/failed replacements do not settle the ask, so an older card returns.
|
|
const SETTLED_CONFIRMATION_STATUSES = ["accepted", "rejected", "answered", "expired"] as const;
|
|
|
|
/** Newest answered/expired ordinary confirmation per issue and recipient (see the collapse above). */
|
|
export async function loadNewestSettledConfirmationAt(db: Db, companyId: string, issueIds: string[]) {
|
|
const ids = [...new Set(issueIds)];
|
|
if (ids.length === 0) return new Map<string, Date>();
|
|
const rows = await db.select({
|
|
issueId: issueThreadInteractions.issueId,
|
|
addresseeUserId: issueThreadInteractions.addresseeUserId,
|
|
addresseeAgentId: issueThreadInteractions.addresseeAgentId,
|
|
createdAt: sql<string>`max(${issueThreadInteractions.createdAt})::text`,
|
|
}).from(issueThreadInteractions).where(and(
|
|
eq(issueThreadInteractions.companyId, companyId),
|
|
inArray(issueThreadInteractions.issueId, ids),
|
|
eq(issueThreadInteractions.kind, "request_confirmation"),
|
|
inArray(issueThreadInteractions.status, [...SETTLED_CONFIRMATION_STATUSES]),
|
|
sql`jsonb_typeof(${issueThreadInteractions.payload}->'qualityReview') is distinct from 'object'`,
|
|
sql`not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization'])`,
|
|
)).groupBy(issueThreadInteractions.issueId, issueThreadInteractions.addresseeUserId, issueThreadInteractions.addresseeAgentId);
|
|
return new Map(rows.map((row) => [confirmationAudienceKey(row), new Date(row.createdAt)]));
|
|
}
|
|
|
|
export function readRunIssueId(contextSnapshot: Record<string, unknown> | null) {
|
|
const issueId = contextSnapshot?.issueId ?? contextSnapshot?.taskId;
|
|
return typeof issueId === "string" && issueId.length > 0 ? issueId : null;
|
|
}
|
|
|
|
type FailedRunProbe = { id: string; agentId: string; issueId: string | null; createdAt: Date };
|
|
|
|
const FAILED_RUN_PROBE_BATCH_SIZE = 1000;
|
|
|
|
export async function listFailedRunsWithNewerRun(db: Db, companyId: string, failedRuns: FailedRunProbe[]) {
|
|
const withNewerRun = new Set<string>();
|
|
const keyed = failedRuns.filter(run => run.issueId !== null);
|
|
for (let start = 0; start < keyed.length; start += FAILED_RUN_PROBE_BATCH_SIZE) {
|
|
const batch = keyed.slice(start, start + FAILED_RUN_PROBE_BATCH_SIZE);
|
|
for (const id of await listFailedRunBatchWithNewerRun(db, companyId, batch)) withNewerRun.add(id);
|
|
}
|
|
const unkeyed = failedRuns.filter(run => run.issueId === null);
|
|
if (unkeyed.length === 0) return withNewerRun;
|
|
const agentIds = [...new Set(unkeyed.map(run => run.agentId))];
|
|
const oldestCreatedAt = unkeyed.reduce((oldest, run) => run.createdAt < oldest ? run.createdAt : oldest,
|
|
unkeyed[0]!.createdAt);
|
|
const latestByAgent = new Map<string, Date>();
|
|
for (let start = 0; start < agentIds.length; start += FAILED_RUN_PROBE_BATCH_SIZE) {
|
|
const rows = await db.select({
|
|
agentId: heartbeatRuns.agentId,
|
|
createdAt: sql<Date>`max(${heartbeatRuns.createdAt})`.mapWith(heartbeatRuns.createdAt),
|
|
}).from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, companyId),
|
|
inArray(heartbeatRuns.agentId, agentIds.slice(start, start + FAILED_RUN_PROBE_BATCH_SIZE)),
|
|
gt(heartbeatRuns.createdAt, oldestCreatedAt),
|
|
sql`coalesce(${heartbeatRuns.contextSnapshot} ->> 'issueId', ${heartbeatRuns.contextSnapshot} ->> 'taskId', '') = ''`,
|
|
)).groupBy(heartbeatRuns.agentId);
|
|
for (const row of rows) latestByAgent.set(row.agentId, row.createdAt);
|
|
}
|
|
for (const run of unkeyed) {
|
|
if ((latestByAgent.get(run.agentId)?.getTime() ?? 0) > run.createdAt.getTime()) withNewerRun.add(run.id);
|
|
}
|
|
return withNewerRun;
|
|
}
|
|
|
|
async function listFailedRunBatchWithNewerRun(db: Db, companyId: string, failedRuns: FailedRunProbe[]) {
|
|
if (failedRuns.length === 0) return [];
|
|
const failed = sql.join(
|
|
failedRuns.map((run) => sql`(${run.id}::uuid, ${run.agentId}::uuid, ${run.issueId}::text, ${new Date(run.createdAt.getTime() + 1).toISOString()}::timestamptz)`),
|
|
sql`, `,
|
|
);
|
|
const runIssueId = sql`(${heartbeatRuns.contextSnapshot} ->> 'issueId')`;
|
|
const runTaskId = sql`(${heartbeatRuns.contextSnapshot} ->> 'taskId')`;
|
|
const newerRunExists = (match: SQL) => sql`exists (
|
|
select 1 from ${heartbeatRuns}
|
|
where ${heartbeatRuns.companyId} = ${companyId}
|
|
and ${heartbeatRuns.agentId} = failed.agent_id
|
|
and ${heartbeatRuns.createdAt} >= failed.newer_from
|
|
and ${match}
|
|
)`;
|
|
const rows = await db.execute(sql`
|
|
select failed.id
|
|
from (values ${failed}) as failed (id, agent_id, issue_id, newer_from)
|
|
where ${newerRunExists(sql`${runIssueId} = failed.issue_id`)}
|
|
or ${newerRunExists(sql`${runTaskId} = failed.issue_id and ${runIssueId} is null`)}
|
|
`) as unknown as Array<{ id: string }>;
|
|
return rows.map((row) => row.id);
|
|
}
|
|
|
|
|
|
export function requiresReviewAttention(input: {
|
|
hasHumanParticipant: boolean; hasUserAssignee: boolean; hasPendingApproval: boolean; stalled: boolean;
|
|
}) {
|
|
return input.hasHumanParticipant || input.hasUserAssignee || input.hasPendingApproval || input.stalled;
|
|
}
|
|
|
|
export function terminalBlockerRequiresAttention<T extends { state?: string; blockingTreeLive?: boolean }>(
|
|
attention: T | null | undefined,
|
|
): attention is T & { state: "stalled" | "needs_attention" } {
|
|
return Boolean(attention && !attention.blockingTreeLive && ["stalled", "needs_attention"].includes(attention.state ?? ""));
|
|
}
|