feat(inbox): route requests to people and record personal outcomes (#20959)

## 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>
This commit is contained in:
authored and GitHub committed 2026-11-11 17:49:39 -08:00
1 parent 9dfdeaad86
commit 8818402e7a
87 files changed
+9600 -332

No files matched your search

@@ -0,0 +1,17 @@
import { describe, expect, it } from "vitest";
import { attentionAudienceReasonText } from "./attention-audience.js";
describe("attention audience reason text", () => {
it("tells the default decision owner why the card came to them", () => {
expect(attentionAudienceReasonText("escalation_owner")).toBe("You are the default decision owner");
});
it("names the project and budget escalation owners", () => {
expect(attentionAudienceReasonText("project_owner")).toBe("You own this project's decisions");
expect(attentionAudienceReasonText("budget_owner")).toBe("You own budget escalation");
});
it("has no line for an unaddressed card", () => {
expect(attentionAudienceReasonText("none")).toBeNull();
});
});
+79
View File
@@ -0,0 +1,79 @@
import type { AttentionAudienceReason, AttentionReceiptOutcome, AttentionStaleReason } from "./types/attention.js";
/**
* The "Why me?" line for each audience reason (PAP-749 plan §1, Rule 4). The UI
* renders this from `AttentionItem.audience.reason`; `none` has no line because
* the card is not addressed to anyone. Exhaustive on purpose, so a new reason
* cannot ship without its copy.
*/
export const ATTENTION_AUDIENCE_REASON_TEXT: Record<AttentionAudienceReason, string | null> = {
addressee: "Sent to you",
conversation: "You started this chat",
reviewer: "You are the reviewer",
assignee: "Assigned to you",
instigator: "You created the original task",
requester: "You requested this",
// Escalation owners (Rule 2 step 5): the project's decision owner comes
// before the company's default decision owner; the budget owner gets budget
// hard stops.
escalation_owner: "You are the default decision owner",
project_owner: "You own this project's decisions",
budget_owner: "You own budget escalation",
none: null,
};
export function attentionAudienceReasonText(reason: AttentionAudienceReason): string | null {
return ATTENTION_AUDIENCE_REASON_TEXT[reason];
}
/**
* The Stale chip text for each stale reason (PAP-749 plan §2, Rule 10, and the
* 7-day Unassigned rule). Exhaustive on purpose, like the "Why me?" copy.
*/
export const ATTENTION_STALE_REASON_TEXT: Record<AttentionStaleReason, string> = {
issue_closed: "Task closed",
aged: "Waiting 30+ days",
decision_expiring: "Expires soon",
unowned: "No owner for 7+ days",
};
export function attentionStaleReasonText(reason: AttentionStaleReason): string {
return ATTENTION_STALE_REASON_TEXT[reason];
}
/**
* The verb of each action (PAP-749 plan §6, Rule 12). Receipts and Decision
* history rows both read it, so one action has one verb everywhere (PAP-767).
* The verbs follow the card's buttons: Approve, Request changes (Reject or
* Revise… on a confirmation), Keep paused, Raise limit. Exhaustive, like the
* copy above.
*/
export const ATTENTION_RECEIPT_OUTCOME_TEXT: Record<AttentionReceiptOutcome, string> = {
answered: "Answered",
approved: "Approved",
rejected: "Rejected",
changes_requested: "Changes requested",
revision_requested: "Revision requested",
decided: "Decided",
withdrawn: "Withdrawn",
skipped: "Skipped",
transferred: "Transferred",
kept_paused: "Kept paused",
limit_raised: "Limit raised",
};
/**
* "Answered by @scott", "Withdrawn by @scott", "Transferred to @riley by
* @scott". Labels are display names without the `@`.
*/
export function attentionReceiptText(input: {
outcome: AttentionReceiptOutcome;
actorLabel: string;
transferredToLabel?: string | null;
}): string {
const verb = ATTENTION_RECEIPT_OUTCOME_TEXT[input.outcome];
if (input.outcome === "transferred" && input.transferredToLabel) {
return `${verb} to @${input.transferredToLabel} by @${input.actorLabel}`;
}
return `${verb} by @${input.actorLabel}`;
}
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
import { attentionCardType, type AttentionItem } from "./index.js";
const card = (sourceKind: AttentionItem["sourceKind"], metadata: Record<string, unknown> = {}) =>
({ sourceKind, subject: { kind: "issue", id: "x", companyId: "c", title: null, identifier: null, status: null, href: null, metadata } }) as Pick<AttentionItem, "sourceKind" | "subject">;
describe("attentionCardType (PAP-775)", () => {
it("picks the interaction design from its kind and what it confirms", () => {
expect(attentionCardType(card("issue_thread_interaction", { kind: "ask_user_questions" }))).toBe("answer_questions");
expect(attentionCardType(card("issue_thread_interaction", { kind: "suggest_tasks" }))).toBe("suggested_tasks");
expect(attentionCardType(card("issue_thread_interaction", { kind: "request_confirmation", isPlanTarget: true }))).toBe("review_plan");
expect(attentionCardType(card("issue_thread_interaction", { kind: "request_confirmation", requestKind: "deliverable" }))).toBe("review_deliverable");
expect(attentionCardType(card("issue_thread_interaction", { kind: "request_confirmation", requestKind: "tool_action" }))).toBe("tool_access");
expect(attentionCardType(card("issue_thread_interaction", { kind: "request_confirmation", requestKind: "connection" }))).toBe("connect_service");
expect(attentionCardType(card("issue_thread_interaction", { kind: "request_confirmation" }))).toBe("confirm");
});
it("maps every other source to its own design", () => {
expect(attentionCardType(card("approval", { type: "hire_agent" }))).toBe("board_approval");
expect(attentionCardType(card("join_request"))).toBe("join_request");
expect(attentionCardType(card("review"))).toBe("review_task");
expect(attentionCardType(card("review", { reviewAttentionState: "stalled" }))).toBe("blocked_task");
expect(attentionCardType(card("blocker_attention"))).toBe("blocked_task");
expect(attentionCardType(card("agent_error_alert"))).toBe("failed_run");
expect(attentionCardType(card("budget_alert"))).toBe("budget_stop");
expect(attentionCardType(card("recovery_action"))).toBe("recovery");
expect(attentionCardType(card("decision"))).toBe("make_choice");
});
});
+2
View File
@@ -16,6 +16,8 @@ const companySnapshotSchema: z.ZodType<Company> = z.object({
budgetMonthlyCents: z.number(),
spentMonthlyCents: z.number(),
defaultResponsibleUserId: z.string().nullable(),
defaultDecisionOwnerUserId: z.string().nullable().default(null),
budgetOwnerUserId: z.string().nullable().default(null),
requireBoardApprovalForNewAgents: z.boolean(),
interactionResolverGovernance: interactionResolverGovernanceSchema,
feedbackDataSharingEnabled: z.boolean(),
+46 -1
View File
@@ -167,30 +167,68 @@ export {
type ResponsibleUserDenialTone,
} from "./responsible-user-denial.js";
export type {
AttentionAudience,
AttentionAudienceKind,
AttentionAudienceReason,
AttentionAlreadyClosedDetails,
AttentionClaimableSourceKind,
AttentionClaimResult,
AttentionCloseInput,
AttentionCloseMode,
AttentionCloseResult,
AttentionDecisionVerb,
AttentionTransferInput,
AttentionTransferResult,
DecisionHistoryItem,
DecisionHistoryOutcomeFilter,
DecisionHistoryQuery,
DecisionHistoryScope,
DecisionHistoryPage,
DecisionHistoryResultOutcome,
DecisionHistoryAction,
AttentionDetailImage,
AttentionFeed,
AttentionSummary,
AttentionTaskIndex,
AttentionFeedView,
AttentionItem,
AttentionItemDetail,
AttentionItemDismissal,
AttentionFeedQuery,
AttentionPersonalView,
AttentionProjectRef,
AttentionQueueRef,
AttentionResolverAudience,
AttentionSeverity,
AttentionSortMode,
AttentionSourceKind,
AttentionStale,
AttentionStaleReason,
AttentionHandledDetails,
AttentionReceipt,
AttentionRequester,
AttentionCardKind,
AttentionCardType,
AttentionRequestKind,
AttentionReceiptOutcome,
AttentionSubject,
AttentionSubjectKind,
AttentionTriageAttribution,
AttentionViewCounts,
AttentionWorkspaceRef,
} from "./types/attention.js";
export { ATTENTION_SOURCE_KINDS } from "./types/attention.js";
export {
ATTENTION_CLAIMABLE_SOURCE_KINDS,
attentionCardKind,
attentionCardType,
ATTENTION_CLOSE_MODES,
ATTENTION_PERSONAL_VIEWS,
ATTENTION_RECEIPT_DAYS,
ATTENTION_RECEIPT_OUTCOMES,
ATTENTION_SOURCE_KINDS,
DECISION_HISTORY_OUTCOME_FILTERS,
DECISION_HISTORY_SCOPES,
} from "./types/attention.js";
export { questionSetToAskUserQuestionsPayload } from "./question-set.js";
export type {
DecisionQueue,
@@ -2159,6 +2197,7 @@ export {
resolveBudgetIncidentSchema,
resolveApprovalSchema,
requestApprovalRevisionSchema,
cancelApprovalSchema,
resubmitApprovalSchema,
addApprovalCommentSchema,
type CreateApproval,
@@ -2166,8 +2205,13 @@ export {
type ResolveBudgetIncident,
type ResolveApproval,
type RequestApprovalRevision,
type CancelApproval,
type ResubmitApproval,
type AddApprovalComment,
attentionCloseSchema,
attentionTransferSchema,
type AttentionClose,
type AttentionTransfer,
envBindingPlainSchema,
envBindingSecretRefSchema,
envBindingUserSecretRefSchema,
@@ -2813,6 +2857,7 @@ export * from "./types/voice-sessions.js";
export * from "./validators/voice-sessions.js";
export * from "./agent-appearance.js";
export * from "./attention-audience.js";
export * from "./ai-connections.js";
export * from "./ai-connection-router.js";
export * from "./ai-connection-usage.js";
+471 -7
View File
@@ -85,6 +85,11 @@ export type AttentionSortMode = "activity" | "decide";
export interface AttentionFeedQuery {
includeDismissed?: boolean;
archived?: boolean;
/**
* Which audience slice to return (PAP-749 plan §1). Defaults to `all`, the
* pre-PAP-749 superset, so omitting it keeps the current user-visible feed.
*/
view?: AttentionFeedView;
/** Return the complete filtered snapshot in one response. */
all?: boolean;
activitySince?: string;
@@ -218,6 +223,344 @@ export interface AttentionResolverAudience {
createdByAgentName: string | null;
}
/**
* Where a card *shows* (PAP-749 plan §1, Rule 2) — distinct from
* {@link AttentionResolverAudience}, which says who may *act*. The server
* computes this once per item from participation facts (an explicit addressee,
* the chat user, the review participant or human assignee, or the instigator
* who created the originating human work) and never from `responsibleUserId`,
* the routine creator, a connected account, the agent owner, or a manual
* routine starter. `kind` drives the three-view switch: `user` belongs in that
* user's "For you" list, `pool` belongs in the claimable "Unassigned" pool, and
* `company` belongs in the operator "Company" view. Audience governs placement
* only; the resolver policy still gates every action.
*/
export type AttentionAudienceKind = "user" | "pool" | "company";
export type AttentionAudienceReason =
| "addressee"
| "conversation"
| "reviewer"
| "assignee"
| "instigator"
| "requester"
/** The company's default decision owner (task 1d-lite). */
| "escalation_owner"
/** The decision owner of the card's project (task 1d). */
| "project_owner"
/** The company's budget owner, on a budget hard stop (task 1d). */
| "budget_owner"
| "none";
export interface AttentionAudience {
kind: AttentionAudienceKind;
userId: string | null;
reason: AttentionAudienceReason;
/**
* A company alert that also has a personal owner (PAP-749 plan §1, Rule 3):
* the card shows in {@link userId}'s "For you" list and in the Company view.
* Only a budget hard stop with a budget owner sets it today.
*/
alsoInCompany?: boolean;
/**
* The person who transferred the card to {@link userId} ("Route to @x"),
* when the addressee came from a transfer (PAP-749 plan §6, Rule 12). The
* "Why me?" line reads "Transferred by @x".
*/
transferredByUserId?: string | null;
}
/**
* Which slice of the attention feed to return. `all` is the default and is a
* superset that preserves the pre-PAP-749 behaviour (no user-visible change);
* `mine`, `unassigned`, and `company` partition the feed by {@link
* AttentionAudience.kind}. `archived` is the requesting person's own hidden
* cards (PAP-749 plan §3): open cards they archived or snoozed, read from
* their `inbox_dismissals`, whatever the card's audience.
*/
export type AttentionFeedView = "mine" | "unassigned" | "company" | "archived" | "all";
/**
* The views the Decisions pages switch between (PAP-749 plan §1, Rule 3; §3):
* For you, Unassigned, Company, the person's own Archived view, and Everyone
* (`all`, every person's cards), which only board members see (PAP-768).
*/
export const ATTENTION_PERSONAL_VIEWS = ["mine", "unassigned", "company", "archived", "all"] as const;
export type AttentionPersonalView = (typeof ATTENTION_PERSONAL_VIEWS)[number];
/**
* Cards in each view for the requesting user (PAP-749 plan §1, Rule 5).
* Counted before the view, date and queue filters and pagination, so every
* surface reads the same numbers whatever it fetched. `mine`, `unassigned`,
* `company` and `all` count current cards without the ones this person
* archived or snoozed; `archived` counts exactly those hidden cards (archived
* plus snoozed). Only `mine` is the badge; the other counts stay on their tabs.
*/
export type AttentionViewCounts = Record<AttentionPersonalView, number>;
/**
* Source kinds whose card names a person through an addressee field, so Claim
* and Transfer can store the new owner there (PAP-749 plan §1, Rule 3; §2,
* Rule 6). Other kinds have no addressee to set yet.
*/
export const ATTENTION_CLAIMABLE_SOURCE_KINDS = ["issue_thread_interaction"] as const;
export type AttentionClaimableSourceKind = (typeof ATTENTION_CLAIMABLE_SOURCE_KINDS)[number];
/** Result of `POST /companies/:companyId/attention/:sourceKind/:sourceId/claim`. */
export interface AttentionClaimResult {
sourceKind: AttentionClaimableSourceKind;
sourceId: string;
claimedByUserId: string;
/** `true` when the caller already owned the card; nothing changed. */
alreadyClaimed: boolean;
}
/**
* The verbs of the Close… menu (PAP-749 plan §2, Rule 6). Each has one effect:
* - `withdraw`: closes the request for everyone because it is out of date. It
* is never an approval or consent, and it tells the agent.
* - `archive`: hides the card for you only, until it changes. The source stays
* open and teammates still see it.
* - `snooze`: hides the card for you only, until a time you pick. It does not
* change a shared deadline.
* Transfer is not a close mode; it has its own endpoint.
*/
export const ATTENTION_CLOSE_MODES = ["withdraw", "archive", "snooze"] as const;
export type AttentionCloseMode = (typeof ATTENTION_CLOSE_MODES)[number];
/** Body of `POST /companies/:companyId/attention/:sourceKind/:sourceId/close`. */
export interface AttentionCloseInput {
mode: AttentionCloseMode;
/** Why the request is out of date. Shown in history and sent to the agent. */
reason?: string | null;
/** Snooze end, ISO timestamp in the future. Required for `snooze` only. */
until?: string | null;
/**
* The card's `changeFingerprint` as the viewer saw it, for `archive` and
* `snooze`. The card returns when its content differs from this version.
* Omitted: the server uses the current version.
*/
fingerprint?: string | null;
}
/** Result of the close endpoint. */
export interface AttentionCloseResult {
sourceKind: AttentionSourceKind;
sourceId: string;
mode: AttentionCloseMode;
closedByUserId: string;
/** The task the card belongs to, when it has one. */
issueId: string | null;
/** Snooze end for `snooze`; `null` otherwise. */
until: string | null;
}
/** Body of `POST /companies/:companyId/attention/:sourceKind/:sourceId/transfer`. */
export interface AttentionTransferInput {
/** The person who gets the card ("Route to @x"). */
userId: string;
reason?: string | null;
}
/** Result of the transfer endpoint. */
export interface AttentionTransferResult {
sourceKind: AttentionClaimableSourceKind;
sourceId: string;
transferredToUserId: string;
/** The person the card was for before the transfer, if any. */
previousAddresseeUserId: string | null;
/** `true` when the card already went to that person; nothing changed. */
alreadyTransferred: boolean;
}
/**
* Details of the 409 that the close, claim and transfer endpoints return when
* a different person already answered or closed the source first (PAP-749
* plan §2, "Two persons answer at the same time"). The UI shows "Already
* answered by @x".
*/
export interface AttentionAlreadyClosedDetails {
code: "attention_already_closed";
sourceKind: AttentionSourceKind;
sourceId: string;
status: string;
resolvedByUserId: string | null;
resolvedByAgentId: string | null;
resolvedAt: string | null;
}
/**
* Why a card is stale (PAP-749 plan §2, Rule 10). A stale card stays open and
* answerable; the label only moves it to the Stale group. The server never
* withdraws a stale card and never treats one as approved.
* - `issue_closed`: its task is done or cancelled and the card is still pending.
* - `aged`: no important change for 30 days ("Waiting 30+ days").
* - `decision_expiring`: a decision with 80% or more of its time limit gone.
* - `unowned`: an Unassigned card with no owner for 7 days ("No owner for 7+
* days"); it moves to the Company view.
*/
export type AttentionStaleReason = "issue_closed" | "aged" | "decision_expiring" | "unowned";
export interface AttentionStale {
reason: AttentionStaleReason;
}
/**
* What a different person did with a card that was for you (PAP-749 plan §6,
* Rule 12). Archive and snooze are personal, so they never make a receipt;
* Claim takes only ownerless cards, so it has no audience person to tell.
* Decision history names the same action with the same value, so a receipt
* and its history row read the same verb (PAP-767).
*/
export const ATTENTION_RECEIPT_OUTCOMES = [
"answered",
"approved",
"rejected",
"changes_requested",
"revision_requested",
"decided",
"withdrawn",
"skipped",
"transferred",
"kept_paused",
"limit_raised",
] as const;
export type AttentionReceiptOutcome = (typeof ATTENTION_RECEIPT_OUTCOMES)[number];
/** A receipt stays at the top of For you this long, or until its person dismisses it. */
export const ATTENTION_RECEIPT_DAYS = 7;
/**
* Stored on the activity entry of the action as `details.receipt`, next to
* `details.handledForUserId` (the card's audience person at the time of the
* action). Present only when that person is not the actor. Receipts and the
* "Handled for me" history filter read these; there is no receipts table.
*/
export interface AttentionHandledDetails {
outcome: AttentionReceiptOutcome;
sourceKind: AttentionSourceKind;
sourceId: string;
issueId: string | null;
/** The card title when the person acted. */
title: string | null;
/** The person who acted. Decisions log as the executor, so it is kept here. */
actorUserId: string;
reason?: string | null;
/** For `transferred`: who got the card. */
transferredToUserId?: string | null;
}
/**
* One receipt at the top of For you: "Answered by @scott", "Withdrawn by
* @scott" with the reason, "Transferred to @riley by @scott". A receipt is not
* a card and is never in the badge count.
*/
export interface AttentionReceipt {
/** The activity entry the receipt comes from. */
id: string;
/** Inbox dismissal key; dismissing it hides the receipt for you. */
dismissalKey: string;
outcome: AttentionReceiptOutcome;
sourceKind: AttentionSourceKind;
sourceId: string;
title: string | null;
reason: string | null;
actorUserId: string;
transferredToUserId: string | null;
issue: { id: string; identifier: string | null; title: string; href: string } | null;
/** Where the source shows now: its task thread, or the approval page. */
href: string | null;
createdAt: string;
/** When the receipt leaves For you on its own. */
expiresAt: string;
}
export interface AttentionRequester {
kind: "agent" | "user";
id: string;
name: string | null;
}
/**
* The two kinds of Needs You card (PAP-775, IA7): a `decision` asks a person
* to choose, answer or approve; a `problem` reports something that broke (a
* failed run, an agent error, a budget stop, a stuck task). Each card is
* exactly one kind.
*/
export type AttentionCardKind = "decision" | "problem";
const ATTENTION_PROBLEM_SOURCE_KINDS: ReadonlySet<AttentionSourceKind> = new Set([
"failed_run",
"agent_error_alert",
"budget_alert",
"blocker_attention",
"recovery_action",
]);
export function attentionCardKind(item: Pick<AttentionItem, "sourceKind" | "subject">): AttentionCardKind {
if (ATTENTION_PROBLEM_SOURCE_KINDS.has(item.sourceKind)) return "problem";
// A review with no reviewer and no way forward is a stuck task.
if (item.sourceKind === "review" && item.subject.metadata?.reviewAttentionState === "stalled") return "problem";
return "decision";
}
/**
* Which of the Needs You card designs a card uses (PAP-775, Paper "A · Compact
* cards"): one design per type of request, each with its own context panel and
* actions. Receipts are the `update` type and never reach this from the feed.
*/
export type AttentionCardType =
| "answer_questions"
| "make_choice"
| "review_plan"
| "confirm"
| "suggested_tasks"
| "review_deliverable"
| "review_items"
| "board_approval"
| "join_request"
| "tool_access"
| "connect_service"
| "review_task"
| "failed_run"
| "budget_stop"
| "blocked_task"
| "recovery";
/**
* What an interaction confirmation is about, read from its payload so the feed
* can pick the card design before the interaction itself loads.
*/
export type AttentionRequestKind = "tool_action" | "secret" | "connection" | "access" | "deliverable";
export function attentionCardType(item: Pick<AttentionItem, "sourceKind" | "subject">): AttentionCardType {
const metadata = item.subject.metadata ?? {};
switch (item.sourceKind) {
case "issue_thread_interaction": {
const requestKind = metadata.requestKind as AttentionRequestKind | null | undefined;
if (requestKind === "tool_action" || requestKind === "secret" || requestKind === "access") return "tool_access";
if (requestKind === "connection") return "connect_service";
if (metadata.kind === "connection_intent") return "connect_service";
if (metadata.kind === "ask_user_questions") return "answer_questions";
if (metadata.kind === "suggest_tasks") return "suggested_tasks";
if (metadata.kind === "request_item_verdicts") return "review_items";
if (metadata.isPlanTarget === true) return "review_plan";
if (requestKind === "deliverable") return "review_deliverable";
return "confirm";
}
case "decision": return "make_choice";
case "approval": return "board_approval";
case "join_request": return "join_request";
case "review": return metadata.reviewAttentionState === "stalled" ? "blocked_task" : "review_task";
case "blocker_attention": return "blocked_task";
case "failed_run":
case "agent_error_alert": return "failed_run";
case "budget_alert": return "budget_stop";
case "recovery_action": return "recovery";
default: return "confirm";
}
}
export interface AttentionItem {
id: string;
companyId: string;
@@ -237,11 +580,57 @@ export interface AttentionItem {
createdAt: string;
updatedAt: string;
relatedIssue: AttentionSubject | null;
/** Where this card shows (PAP-749 plan §1, Rule 2). Placement only; never authority. */
audience: AttentionAudience;
/** Set when the card is stale (PAP-749 plan §2, Rule 10); `null` for a current card. */
stale: AttentionStale | null;
/**
* The card is a required gate: an approval or a governed request that keeps
* its gate until someone answers it (PAP-749 plan §2, Rule 10). A stale
* required card goes to a person; "Withdraw all stale" never closes it. A
* person can still withdraw one from its own Close… menu.
*/
required: boolean;
/**
* Opaque fingerprint of the card's important content for this viewer
* (PAP-749 plan §2, Rule 9). Send it with a dismiss or snooze; the hidden
* card returns only when the fingerprint changes, not on log entries,
* retries, unrelated comments or assignee changes.
*/
changeFingerprint: string;
/**
* The Close… menu verbs the server supports for this card (PAP-749 plan §2,
* Rule 6). `withdraw` is present only when the source has a real withdraw
* or cancel; budget, review, blocker and operator alerts use their own
* actions instead.
*/
closeModes: AttentionCloseMode[];
/**
* One card for each obligation (PAP-749 plan §2, Rule 11). Cards with the
* same key are one obligation: a pending approval with the in-review state of
* its task (`approval:<approvalId>`), a budget hard stop with its override
* approval (`approval:<approvalId>`, the stop leads; PAP-768), or a blocked
* task with the failed run that caused it (`blocked:<issueId>`). The UI shows the lead card and folds
* the others into it as evidence; the feed still returns every card, keeps
* the evidence right after its lead, and shows or hides it with the lead.
* `null` when the card is its own obligation. A configured human review
* stage is an independent quality gate, so it keeps its own card.
*/
obligationKey: string | null;
/** The `id` of the card that leads the obligation; set with `obligationKey`. */
obligationLeadId: string | null;
project: AttentionProjectRef | null;
workspace: AttentionWorkspaceRef | null;
expiresAt: string | null;
ruleKey: string | null;
originAgentName: string | null;
/**
* Who is asking (PAP-775, UI2): the agent or person that created the
* request, so a card can show their avatar and name. `name` is set for an
* agent; a person's name comes from the company directory. `null` for a
* system alert nobody asked for.
*/
requester?: AttentionRequester | null;
queues: AttentionQueueRef[];
shelf: boolean;
retentionDays: number;
@@ -265,15 +654,25 @@ export interface AttentionFeed {
generatedAt: string;
totalCount: number;
/**
* The sidebar badge: distinct items that either surfaced today ("new today")
* or carry an explicit decide-by deadline that is due today/past ("overdue").
* Computed before pagination so a small first page still reflects the
* company-wide load. The desk no longer editorializes about what "can wait".
* The one badge on the sidebar, mobile navigation and Decisions page
* (PAP-749 plan §1, Rule 5): current "For you" cards, the same number as
* `viewCounts.mine`. It does not reset at midnight; an open card stays in the
* count until a person answers it. Unassigned and Company are never in it.
*/
deskBadgeCount: number;
/**
* Per-view counts for the three-view switch and the Unassigned banner. Each
* obligation counts once, so a lead and its evidence are one (Rule 11).
*/
viewCounts: AttentionViewCounts;
nextCursor: string | null;
countsBySourceKind: Record<AttentionSourceKind, number>;
items: AttentionItem[];
/**
* Receipts for the requesting person, newest first (PAP-749 plan §6). Set
* for the For you view (`view=mine`) only; not counted in any badge.
*/
receipts?: AttentionReceipt[];
}
/** Canonical attention counts without downloading the decision cards. */
@@ -283,27 +682,80 @@ export interface AttentionTaskIndex extends AttentionSummary {
taskIds: string[];
}
/** Read-only projection of canonical task decisions; never a second write store. */
/**
* Read-only projection of canonical task decisions and approvals (PAP-749 plan
* §3); never a second write store.
*/
export interface DecisionHistoryItem {
id: string;
sourceKind: "issue_thread_interaction" | "decision";
sourceKind: "issue_thread_interaction" | "decision" | "approval";
sourceId: string;
issueId: string;
/** The task the decision belongs to. `null` for an approval with no linked task. */
issueId: string | null;
issueIdentifier: string | null;
issueTitle: string;
issueTitle: string | null;
agentId: string | null;
agentName: string | null;
projectId: string | null;
projectName: string | null;
title: string;
/** The stored status: `accepted`, `answered`, `cancelled`, `expired`, `approved`, … */
outcome: string;
/**
* The more specific recorded close, when the status alone hides it:
* `withdrawn` (a person or the agent withdrew the request), `skipped` or
* `issue_closed` ("Closed with task"). `null` for an ordinary answer.
*/
resultOutcome?: DecisionHistoryResultOutcome | null;
label: string;
/**
* What the person did, in the receipt's words: the UI renders "Approved by
* @scott" from this and `resolvedByUserId`, like the receipt for the same
* action (PAP-767). `detail` is what the verb leaves out: the chosen option
* of a decision, or the verdict counts of an item review. `null` when no
* person acted (expired, closed with its task, superseded).
*/
action?: DecisionHistoryAction | null;
/** Why the request was withdrawn or skipped, when the person gave a reason. */
reason?: string | null;
resolvedAt: string;
resolvedByUserId: string | null;
resolvedByAgentId: string | null;
/**
* The person the card was for, when a different person answered, withdrew
* or transferred it ("Answered by @x for @y"; PAP-749 plan §6).
*/
handledForUserId?: string | null;
href: string;
target: { kind: "issue_document"; issueId?: string; key: string; revisionId: string } | { kind: "issue_attachment"; attachmentId: string } | null;
}
export type DecisionHistoryResultOutcome = "withdrawn" | "skipped" | "issue_closed";
export interface DecisionHistoryAction {
outcome: AttentionReceiptOutcome;
detail: string | null;
}
/**
* Outcome filters of the Decision history panel (PAP-749 plan §3). Each value
* matches every source that can have it: `withdrawn` covers withdrawn
* interactions and the decisions and approvals a person withdrew; `expired`
* is a time-out or supersede, never a card that closed with its task;
* `issue_closed` is "Closed with task".
*/
export const DECISION_HISTORY_OUTCOME_FILTERS = [
"accepted",
"answered",
"rejected",
"decided",
"withdrawn",
"expired",
"issue_closed",
"cancelled",
] as const;
export type DecisionHistoryOutcomeFilter = (typeof DECISION_HISTORY_OUTCOME_FILTERS)[number];
export interface DecisionHistoryQuery {
cursor?: string;
limit?: number;
@@ -313,8 +765,20 @@ export interface DecisionHistoryQuery {
projectId?: string;
sort?: "newest" | "oldest";
since?: string;
/** "Handled for me": only cards for you that a different person handled (PAP-749 plan §6). */
handledForMe?: boolean;
/**
* Whose history (PAP-768). `mine` is "Handled by me or for me": what you
* answered, withdrew or transferred, what a different person handled for
* you, and the cards whose audience is you. `all` (the default) is every
* person's history. The outcome filters apply within either scope.
*/
scope?: DecisionHistoryScope;
}
export const DECISION_HISTORY_SCOPES = ["mine", "all"] as const;
export type DecisionHistoryScope = (typeof DECISION_HISTORY_SCOPES)[number];
export interface DecisionHistoryPage {
items: DecisionHistoryItem[];
nextCursor: string | null;
+16
View File
@@ -26,6 +26,22 @@ export interface Company {
budgetMonthlyCents: number;
spentMonthlyCents: number;
defaultResponsibleUserId: string | null;
/**
* PAP-749 task 1d-lite: the company's default decision owner. When set,
* ownerless attention cards route to this user's "For you" list; when null
* they stay in the claimable Unassigned pool. Placement only — it never
* grants authority, which the resolver policy still gates. Distinct from
* {@link defaultResponsibleUserId}, which is attribution and is never used
* to route cards.
*/
defaultDecisionOwnerUserId: string | null;
/**
* PAP-749 task 1d: the budget owner. A budget hard stop also goes to this
* user's "For you" list, with Raise limit / Keep paused, while the Company
* view still shows it. `null` leaves the hard stop in Company only.
* Placement only, like {@link defaultDecisionOwnerUserId}.
*/
budgetOwnerUserId: string | null;
requireBoardApprovalForNewAgents: boolean;
interactionResolverGovernance: InteractionResolverGovernance;
feedbackDataSharingEnabled: boolean;
@@ -8,6 +8,8 @@ export interface InboxDismissal {
kind: InboxDismissalKind;
dismissedAt: Date;
snoozedUntil: Date | null;
/** The attention card's `changeFingerprint` when it was hidden; `null` for other inbox items. */
fingerprint: string | null;
createdAt: Date;
updatedAt: Date;
}
+39 -1
View File
@@ -39,30 +39,68 @@ export type {
WriteSummarySlotResponse,
} from "./summary-slot.js";
export type {
AttentionAudience,
AttentionAudienceKind,
AttentionAudienceReason,
AttentionAlreadyClosedDetails,
AttentionClaimableSourceKind,
AttentionClaimResult,
AttentionCloseInput,
AttentionCloseMode,
AttentionCloseResult,
AttentionDecisionVerb,
AttentionTransferInput,
AttentionTransferResult,
DecisionHistoryItem,
DecisionHistoryOutcomeFilter,
DecisionHistoryQuery,
DecisionHistoryScope,
DecisionHistoryPage,
DecisionHistoryResultOutcome,
DecisionHistoryAction,
AttentionDetailImage,
AttentionFeed,
AttentionSummary,
AttentionTaskIndex,
AttentionFeedView,
AttentionItem,
AttentionItemDetail,
AttentionItemDismissal,
AttentionFeedQuery,
AttentionPersonalView,
AttentionProjectRef,
AttentionQueueRef,
AttentionResolverAudience,
AttentionSeverity,
AttentionSortMode,
AttentionSourceKind,
AttentionStale,
AttentionStaleReason,
AttentionHandledDetails,
AttentionReceipt,
AttentionRequester,
AttentionCardKind,
AttentionCardType,
AttentionRequestKind,
AttentionReceiptOutcome,
AttentionSubject,
AttentionSubjectKind,
AttentionTriageAttribution,
AttentionViewCounts,
AttentionWorkspaceRef,
} from "./attention.js";
export { ATTENTION_SOURCE_KINDS } from "./attention.js";
export {
ATTENTION_CLAIMABLE_SOURCE_KINDS,
attentionCardKind,
attentionCardType,
ATTENTION_CLOSE_MODES,
ATTENTION_PERSONAL_VIEWS,
ATTENTION_RECEIPT_DAYS,
ATTENTION_RECEIPT_OUTCOMES,
ATTENTION_SOURCE_KINDS,
DECISION_HISTORY_OUTCOME_FILTERS,
DECISION_HISTORY_SCOPES,
} from "./attention.js";
export type {
DecisionQueue,
DecisionQueueItem,
+7
View File
@@ -143,6 +143,13 @@ export interface Project {
privacyOwnerUserId?: string | null;
status: ProjectStatus;
leadAgentId: string | null;
/**
* PAP-749 task 1d: the project's decision owner. A Needs You card on this
* project's work that names no person goes to this user's "For you" list,
* before the company's default decision owner. Placement only — the resolver
* policy still gates who may act. Omitted by older servers/fixtures.
*/
decisionOwnerUserId?: string | null;
targetDate: string | null;
color: string | null;
icon: string | null;
@@ -23,6 +23,13 @@ export const requestApprovalRevisionSchema = z.object({
export type RequestApprovalRevision = z.infer<typeof requestApprovalRevisionSchema>;
/** Withdraw an open approval because it is out of date. Never an approval. */
export const cancelApprovalSchema = z.object({
reason: z.string().trim().max(4000).optional().nullable(),
}).strict();
export type CancelApproval = z.infer<typeof cancelApprovalSchema>;
export const resubmitApprovalSchema = z.object({
payload: z.record(z.string(), z.unknown()).optional(),
});
@@ -0,0 +1,43 @@
import { z } from "zod";
import { ATTENTION_CLOSE_MODES } from "../types/attention.js";
const reasonSchema = z.string().trim().max(4000).nullish();
/**
* Body of the attention close endpoint (PAP-749 plan §2, Rule 6). Snooze needs
* a future `until`; the other modes must not send one. The fingerprint is
* personal presentation state only, so a wrong value just lets the card return.
*/
export const attentionCloseSchema = z.object({
mode: z.enum(ATTENTION_CLOSE_MODES),
reason: reasonSchema,
until: z.string().trim().datetime({ offset: true }).nullish(),
fingerprint: z.string().trim().min(1).max(200).nullish(),
}).strict().superRefine((value, ctx) => {
if (value.mode !== "snooze") {
if (value.until != null) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["until"], message: "Only snooze takes an until time" });
}
if (value.mode === "withdraw" && value.fingerprint != null) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["fingerprint"], message: "Withdraw does not take a fingerprint" });
}
return;
}
if (value.until == null) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["until"], message: "Snooze requires until" });
return;
}
if (new Date(value.until).getTime() <= Date.now()) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["until"], message: "until must be in the future" });
}
});
export type AttentionClose = z.infer<typeof attentionCloseSchema>;
/** Body of the attention transfer endpoint ("Route to @x"). */
export const attentionTransferSchema = z.object({
userId: z.string().trim().min(1).max(200),
reason: reasonSchema,
}).strict();
export type AttentionTransfer = z.infer<typeof attentionTransferSchema>;
@@ -36,6 +36,12 @@ export const updateCompanySchema = objectWithoutDefaults(
.extend({
status: z.enum(COMPANY_STATUSES).optional(),
spentMonthlyCents: z.number().int().nonnegative().optional(),
// PAP-749 task 1d-lite: the default decision owner (a user). `null` clears
// it, sending ownerless cards back to Unassigned.
defaultDecisionOwnerUserId: z.string().min(1).nullable().optional(),
// PAP-749 task 1d: the budget owner (a user). `null` leaves budget hard
// stops in the Company view only.
budgetOwnerUserId: z.string().min(1).nullable().optional(),
requireBoardApprovalForNewAgents: z.boolean().optional(),
interactionResolverGovernance: interactionResolverGovernanceSchema.optional(),
feedbackDataSharingEnabled: z.boolean().optional(),
+9
View File
@@ -657,15 +657,24 @@ export {
createApprovalSchema,
resolveApprovalSchema,
requestApprovalRevisionSchema,
cancelApprovalSchema,
resubmitApprovalSchema,
addApprovalCommentSchema,
type CreateApproval,
type ResolveApproval,
type RequestApprovalRevision,
type CancelApproval,
type ResubmitApproval,
type AddApprovalComment,
} from "./approval.js";
export {
attentionCloseSchema,
attentionTransferSchema,
type AttentionClose,
type AttentionTransfer,
} from "./attention.js";
export {
envBindingPlainSchema,
envBindingSecretRefSchema,
@@ -115,6 +115,8 @@ const projectFields = {
visibility: z.enum(["open", "private"]).optional().default("open"),
status: z.enum(PROJECT_STATUSES).optional().default("backlog"),
leadAgentId: z.string().guid().optional().nullable(),
// PAP-749 task 1d: the project's decision owner (a user). `null` clears it.
decisionOwnerUserId: z.string().min(1).optional().nullable(),
targetDate: z.string().optional().nullable(),
color: z.string().optional().nullable(),
icon: z.enum(PROJECT_ICON_NAMES).optional().nullable(),