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

+4 -2
View File
@@ -63,8 +63,9 @@ export function approvalRecords(db: Db) {
// Cancel an open (pending/revision_requested) approval without a board
// decision — e.g. when its paired agent is terminated during duplicate
// cleanup. Idempotent: a no-op on already-resolved approvals.
cancel: async (id: string, reason?: string | null) => {
// cleanup, or when a person withdraws it as out of date (PAP-749). It is
// never an approval. Idempotent: a no-op (null) on already-resolved approvals.
cancel: async (id: string, reason?: string | null, options: { cancelledByUserId?: string | null } = {}) => {
const now = new Date();
const [existing] = await db.select({ companyId: approvals.companyId }).from(approvals).where(eq(approvals.id, id));
if (!existing) return null;
@@ -74,6 +75,7 @@ export function approvalRecords(db: Db) {
.set({
status: "cancelled",
decisionNote: reason ?? null,
...(options.cancelledByUserId ? { decidedByUserId: options.cancelledByUserId } : {}),
decidedAt: now,
updatedAt: now,
})
@@ -0,0 +1,27 @@
import type { AttentionAlreadyClosedDetails, AttentionSourceKind } from "@paperclipai/shared";
import { conflict } from "../errors.js";
/**
* The 409 for "a different person answered or closed this first" (PAP-749
* plan §2, special conditions). The first answer wins; the details name who
* resolved the source so the UI can show "Already answered by @x".
*/
export function attentionAlreadyClosedError(input: {
sourceKind: AttentionSourceKind;
sourceId: string;
status: string;
resolvedByUserId?: string | null;
resolvedByAgentId?: string | null;
resolvedAt?: Date | string | null;
}) {
const details: AttentionAlreadyClosedDetails = {
code: "attention_already_closed",
sourceKind: input.sourceKind,
sourceId: input.sourceId,
status: input.status,
resolvedByUserId: input.resolvedByUserId ?? null,
resolvedByAgentId: input.resolvedByAgentId ?? null,
resolvedAt: input.resolvedAt ? new Date(input.resolvedAt).toISOString() : null,
};
return conflict("Already answered", details);
}
@@ -0,0 +1,266 @@
import { describe, expect, it } from "vitest";
import {
audienceMatchesView,
escalateStaleAudience,
resolveAttentionAudience,
type AttentionAudienceInput,
type IssueAudienceContext,
} from "./attention.js";
const EMPTY_CTX: IssueAudienceContext = {
conversationUserId: null,
assigneeUserId: null,
instigatorUserId: null,
};
function input(overrides: Partial<AttentionAudienceInput> = {}): AttentionAudienceInput {
return { issueId: "issue-1", ...overrides };
}
function ctx(overrides: Partial<IssueAudienceContext> = {}): IssueAudienceContext {
return { ...EMPTY_CTX, ...overrides };
}
describe("resolveAttentionAudience — audience steps (PAP-749 plan §1, Rule 2)", () => {
it("routes an explicit user addressee to that user (step 1)", () => {
expect(resolveAttentionAudience(input({ addresseeUserId: "scott" }), ctx({ instigatorUserId: "dotta" })))
.toEqual({ kind: "user", userId: "scott", reason: "addressee" });
});
it("routes an approval to its requester", () => {
expect(resolveAttentionAudience(input({ requestedByUserId: "scott" }), null))
.toEqual({ kind: "user", userId: "scott", reason: "requester" });
});
it("routes a blocker/recovery card to its named user owner", () => {
expect(resolveAttentionAudience(input({ ownerUserId: "scott" }), null))
.toEqual({ kind: "user", userId: "scott", reason: "assignee" });
});
it("routes a chat card to the conversation user (step 2)", () => {
expect(resolveAttentionAudience(input(), ctx({ conversationUserId: "scott" })))
.toEqual({ kind: "user", userId: "scott", reason: "conversation" });
});
it("routes a review to its current human participant (step 3)", () => {
expect(resolveAttentionAudience(input({ reviewParticipantUserId: "scott" }), ctx({ assigneeUserId: "dotta" })))
.toEqual({ kind: "user", userId: "scott", reason: "reviewer" });
});
it("routes to the human assignee when no participant is named (step 3)", () => {
expect(resolveAttentionAudience(input(), ctx({ assigneeUserId: "scott" })))
.toEqual({ kind: "user", userId: "scott", reason: "assignee" });
});
it("routes to the instigator of the originating human work (step 4)", () => {
expect(resolveAttentionAudience(input(), ctx({ instigatorUserId: "scott" })))
.toEqual({ kind: "user", userId: "scott", reason: "instigator" });
});
it("sends company-operations alerts to the Company view", () => {
expect(resolveAttentionAudience(input({ issueId: null, companyScoped: true }), null))
.toEqual({ kind: "company", userId: null, reason: "none" });
});
it("sends a card with no owner to the claimable Unassigned pool (step 6)", () => {
expect(resolveAttentionAudience(input(), EMPTY_CTX))
.toEqual({ kind: "pool", userId: null, reason: "none" });
});
});
describe("resolveAttentionAudience — precedence", () => {
it("an explicit addressee beats every chain signal", () => {
expect(resolveAttentionAudience(
input({ addresseeUserId: "scott", requestedByUserId: "dotta", reviewParticipantUserId: "riley" }),
ctx({ conversationUserId: "dotta", assigneeUserId: "riley", instigatorUserId: "dotta" }),
)).toMatchObject({ userId: "scott", reason: "addressee" });
});
it("the conversation user beats a reviewer, assignee, and instigator", () => {
expect(resolveAttentionAudience(
input({ reviewParticipantUserId: "riley" }),
ctx({ conversationUserId: "scott", assigneeUserId: "riley", instigatorUserId: "dotta" }),
)).toMatchObject({ userId: "scott", reason: "conversation" });
});
it("a reviewer beats the assignee and the instigator", () => {
expect(resolveAttentionAudience(
input({ reviewParticipantUserId: "scott" }),
ctx({ assigneeUserId: "riley", instigatorUserId: "dotta" }),
)).toMatchObject({ userId: "scott", reason: "reviewer" });
});
it("the assignee beats the instigator", () => {
expect(resolveAttentionAudience(
input(),
ctx({ assigneeUserId: "scott", instigatorUserId: "dotta" }),
)).toMatchObject({ userId: "scott", reason: "assignee" });
});
});
describe("resolveAttentionAudience — default decision owner (PAP-749 task 1d-lite, step 5)", () => {
it("routes an ownerless card to the company default decision owner", () => {
expect(resolveAttentionAudience(input(), EMPTY_CTX, { defaultDecisionOwnerUserId: "scott" }))
.toEqual({ kind: "user", userId: "scott", reason: "escalation_owner" });
});
it("falls back to Unassigned when no default decision owner is set", () => {
expect(resolveAttentionAudience(input(), EMPTY_CTX, { defaultDecisionOwnerUserId: null }))
.toEqual({ kind: "pool", userId: null, reason: "none" });
// Omitting the config entirely behaves the same as an unset owner.
expect(resolveAttentionAudience(input(), EMPTY_CTX))
.toEqual({ kind: "pool", userId: null, reason: "none" });
});
it("does not override an earlier chain step with the default owner", () => {
// A card that already resolves to a person keeps that person; the default
// owner only catches cards that would otherwise fall through to the pool.
expect(resolveAttentionAudience(
input({ addresseeUserId: "dotta" }),
ctx({ instigatorUserId: "riley" }),
{ defaultDecisionOwnerUserId: "scott" },
)).toEqual({ kind: "user", userId: "dotta", reason: "addressee" });
expect(resolveAttentionAudience(
input(),
ctx({ instigatorUserId: "riley" }),
{ defaultDecisionOwnerUserId: "scott" },
)).toEqual({ kind: "user", userId: "riley", reason: "instigator" });
});
it("never pulls a company-operations alert onto the default owner", () => {
expect(resolveAttentionAudience(
input({ issueId: null, companyScoped: true }),
null,
{ defaultDecisionOwnerUserId: "scott" },
)).toEqual({ kind: "company", userId: null, reason: "none" });
});
it("the default owner's card lands in that user's `mine` view, not Unassigned", () => {
const audience = resolveAttentionAudience(input(), EMPTY_CTX, { defaultDecisionOwnerUserId: "scott" });
expect(audienceMatchesView(audience, "mine", "scott")).toBe(true);
expect(audienceMatchesView(audience, "unassigned", "scott")).toBe(false);
expect(audienceMatchesView(audience, "company", "scott")).toBe(false);
});
});
describe("resolveAttentionAudience — project and budget owners (PAP-749 task 1d)", () => {
it("routes an ownerless card to its project's decision owner before the company default", () => {
expect(resolveAttentionAudience(input(), ctx({ projectOwnerUserId: "riley" }), { defaultDecisionOwnerUserId: "scott" }))
.toEqual({ kind: "user", userId: "riley", reason: "project_owner" });
});
it("keeps earlier chain steps ahead of the project owner", () => {
expect(resolveAttentionAudience(input(), ctx({ instigatorUserId: "dotta", projectOwnerUserId: "riley" })))
.toEqual({ kind: "user", userId: "dotta", reason: "instigator" });
});
it("falls back to the default decision owner, then Unassigned, without a project owner", () => {
expect(resolveAttentionAudience(input(), ctx({ projectOwnerUserId: null }), { defaultDecisionOwnerUserId: "scott" }))
.toEqual({ kind: "user", userId: "scott", reason: "escalation_owner" });
expect(resolveAttentionAudience(input(), ctx({ projectOwnerUserId: null })))
.toEqual({ kind: "pool", userId: null, reason: "none" });
});
it("gives a budget hard stop to the budget owner and keeps it in Company", () => {
const audience = resolveAttentionAudience(
input({ issueId: null, companyScoped: true, escalatesToBudgetOwner: true }),
null,
{ budgetOwnerUserId: "scott", defaultDecisionOwnerUserId: "dotta" },
);
expect(audience).toEqual({ kind: "user", userId: "scott", reason: "budget_owner", alsoInCompany: true });
expect(audienceMatchesView(audience, "mine", "scott")).toBe(true);
expect(audienceMatchesView(audience, "mine", "dotta")).toBe(false);
// Critical incidents always show in Company, for every operator (Rule 3).
expect(audienceMatchesView(audience, "company", "scott")).toBe(true);
expect(audienceMatchesView(audience, "company", "dotta")).toBe(true);
expect(audienceMatchesView(audience, "unassigned", "dotta")).toBe(false);
});
it("leaves a budget hard stop in Company only when no budget owner is set", () => {
expect(resolveAttentionAudience(
input({ issueId: null, companyScoped: true, escalatesToBudgetOwner: true }),
null,
{ defaultDecisionOwnerUserId: "dotta" },
)).toEqual({ kind: "company", userId: null, reason: "none" });
});
it("never gives other company alerts to the budget owner", () => {
expect(resolveAttentionAudience(
input({ issueId: null, companyScoped: true }),
null,
{ budgetOwnerUserId: "scott" },
)).toEqual({ kind: "company", userId: null, reason: "none" });
});
it("escalates a required card waiting 30 days to its project owner, then the default owner", () => {
const now = Date.parse("2026-10-30T00:00:00Z");
const since = new Date(now - 31 * 86_400_000);
const audience = { kind: "user" as const, userId: "dotta", reason: "requester" as const };
expect(escalateStaleAudience({
audience, since, required: true, now,
companyConfig: { defaultDecisionOwnerUserId: "scott" },
ctx: ctx({ projectOwnerUserId: "riley" }),
})).toEqual({ kind: "user", userId: "riley", reason: "project_owner" });
expect(escalateStaleAudience({
audience, since, required: true, now,
companyConfig: { defaultDecisionOwnerUserId: "scott" },
ctx: ctx(),
})).toEqual({ kind: "user", userId: "scott", reason: "escalation_owner" });
expect(escalateStaleAudience({ audience, since, required: true, now, ctx: ctx() }))
.toEqual({ kind: "company", userId: null, reason: "none" });
});
});
describe("resolveAttentionAudience — forbidden routing signals", () => {
// `responsibleUserId`, the routine creator, the connected account, the agent
// owner, and a manual routine starter are deliberately not inputs, so a card
// whose only human signal would be one of them resolves to Unassigned, never
// to a person (PAP-749 plan §1, Rule 2).
it("does not route a card that has no addressee/owner/participant/instigator", () => {
expect(resolveAttentionAudience(input(), EMPTY_CTX))
.toEqual({ kind: "pool", userId: null, reason: "none" });
});
it("ignores a falsy owner/addressee rather than inventing a user", () => {
expect(resolveAttentionAudience(
input({ addresseeUserId: null, requestedByUserId: null, ownerUserId: null }),
EMPTY_CTX,
)).toEqual({ kind: "pool", userId: null, reason: "none" });
});
});
describe("audienceMatchesView (PAP-749 plan §1, Rule 3)", () => {
const userAudience = { kind: "user" as const, userId: "scott", reason: "addressee" as const };
const otherUserAudience = { kind: "user" as const, userId: "dotta", reason: "instigator" as const };
const poolAudience = { kind: "pool" as const, userId: null, reason: "none" as const };
const companyAudience = { kind: "company" as const, userId: null, reason: "none" as const };
it("`all` keeps every audience (the pre-PAP-749 superset)", () => {
for (const audience of [userAudience, otherUserAudience, poolAudience, companyAudience]) {
expect(audienceMatchesView(audience, "all", "scott")).toBe(true);
}
});
it("`mine` keeps only the requesting user's cards", () => {
expect(audienceMatchesView(userAudience, "mine", "scott")).toBe(true);
expect(audienceMatchesView(otherUserAudience, "mine", "scott")).toBe(false);
expect(audienceMatchesView(poolAudience, "mine", "scott")).toBe(false);
expect(audienceMatchesView(companyAudience, "mine", "scott")).toBe(false);
});
it("`mine` keeps nothing when the requesting user is unknown", () => {
expect(audienceMatchesView(userAudience, "mine", null)).toBe(false);
});
it("`unassigned` keeps only pool cards", () => {
expect(audienceMatchesView(poolAudience, "unassigned", "scott")).toBe(true);
expect(audienceMatchesView(userAudience, "unassigned", "scott")).toBe(false);
expect(audienceMatchesView(companyAudience, "unassigned", "scott")).toBe(false);
});
it("`company` keeps only company-operations cards", () => {
expect(audienceMatchesView(companyAudience, "company", "scott")).toBe(true);
expect(audienceMatchesView(poolAudience, "company", "scott")).toBe(false);
expect(audienceMatchesView(userAudience, "company", "scott")).toBe(false);
});
});
+391
View File
@@ -0,0 +1,391 @@
import { and, desc, eq, gte, inArray, sql } from "drizzle-orm";
import {
activityLog,
agents,
approvals,
budgetIncidents,
companies,
decisions,
inboxDismissals,
issues,
issueThreadInteractions,
type Db,
} from "@paperclipai/db";
import {
ATTENTION_RECEIPT_DAYS,
ATTENTION_RECEIPT_OUTCOMES,
ATTENTION_SOURCE_KINDS,
type AttentionAudience,
type AttentionHandledDetails,
type AttentionReceipt,
type AttentionReceiptOutcome,
type AttentionSourceKind,
type BudgetScopeType,
} from "@paperclipai/shared";
import { logger } from "../middleware/logger.js";
import { evaluateAgentInvokability, type AgentOrgRow } from "./agent-invokability.js";
import { firstApprovalIssueId } from "./approval-visibility.js";
import {
approvalTitle,
escalateStaleAudience,
interactionLabel,
loadCompanyAttentionConfig,
resolveAttentionAudience,
resolveIssueAudienceContextMap,
type AttentionAudienceInput,
} from "./attention.js";
import { approvalReadSqlCondition, issueReadSqlCondition, type AuthorizationActor } from "./authorization.js";
import { budgetScopeName } from "./budgets.js";
import { deferrableInteractionCondition } from "./issue-question-context.js";
/**
* Receipts for the other person (PAP-749 plan §6, Rule 12). When a person
* answers, withdraws or transfers a card that was for a different person, the
* action's activity entry names that person in `details.handledForUserId` and
* describes the card in `details.receipt`. The For you feed reads those
* entries back as receipts; there is no receipts table.
*/
const DAY_MS = 86_400_000;
const RECEIPT_LIMIT = 20;
/** Raw entries read per feed; several entries for one card collapse to one receipt. */
const RECEIPT_SCAN_LIMIT = 200;
export const ATTENTION_RECEIPT_DISMISSAL_PREFIX = "attention:receipt:";
/**
* Sources a person can answer, withdraw or transfer for somebody else. A
* budget card is for a person only when it is a hard stop with a budget owner
* (task 1d).
*/
export type AttentionHandledSourceKind = Extract<
AttentionSourceKind,
"issue_thread_interaction" | "approval" | "decision" | "budget_alert"
>;
/** The card a person is about to act on, and who it is for right now. */
export type AttentionHandledFor = {
userId: string;
actorUserId: string;
sourceKind: AttentionHandledSourceKind;
sourceId: string;
issueId: string | null;
title: string | null;
};
/** The activity `details` fragment of a receipt; empty when there is no other person. */
export type AttentionHandledDetailsFragment =
| { handledForUserId: string; receipt: AttentionHandledDetails }
| Record<string, never>;
/**
* Where one card shows right now, by the same rules as the feed (Rule 2 and
* the Rule 10 escalation), without building the whole feed. `null` when the
* source does not exist or is not a card for a person (an invokable agent's
* request stays with the agent).
*/
export async function resolveAttentionCardAudience(
db: Db,
companyId: string,
source: { sourceKind: AttentionHandledSourceKind; sourceId: string },
now = Date.now(),
): Promise<{ audience: AttentionAudience; issueId: string | null; title: string | null } | null> {
let input: AttentionAudienceInput;
let title: string | null;
let since: Date;
let required: boolean;
if (source.sourceKind === "issue_thread_interaction") {
const [row] = await db
.select({
issueId: issueThreadInteractions.issueId,
kind: issueThreadInteractions.kind,
title: issueThreadInteractions.title,
summary: issueThreadInteractions.summary,
addresseeUserId: issueThreadInteractions.addresseeUserId,
addresseeAgentId: issueThreadInteractions.addresseeAgentId,
createdAt: issueThreadInteractions.createdAt,
required: sql<boolean>`not ${deferrableInteractionCondition()}`,
})
.from(issueThreadInteractions)
.where(and(eq(issueThreadInteractions.companyId, companyId), eq(issueThreadInteractions.id, source.sourceId)))
.limit(1);
if (!row) return null;
if (row.addresseeAgentId && !row.addresseeUserId) {
// A request to an agent that can still run is not a card for anyone.
const companyAgentRows: AgentOrgRow[] = await db
.select({ id: agents.id, companyId: agents.companyId, name: agents.name, reportsTo: agents.reportsTo, status: agents.status })
.from(agents)
.where(eq(agents.companyId, companyId));
const addressee = companyAgentRows.find((agent) => agent.id === row.addresseeAgentId);
if (evaluateAgentInvokability(addressee, companyAgentRows).invokable) return null;
}
input = { issueId: row.issueId, addresseeUserId: row.addresseeUserId };
title = row.title ?? row.summary ?? interactionLabel(row.kind);
since = row.createdAt;
required = row.required === true;
} else if (source.sourceKind === "approval") {
const [row] = await db
.select({
type: approvals.type,
payload: approvals.payload,
requestedByUserId: approvals.requestedByUserId,
issueId: firstApprovalIssueId(),
updatedAt: approvals.updatedAt,
})
.from(approvals)
.where(and(eq(approvals.companyId, companyId), eq(approvals.id, source.sourceId)))
.limit(1);
if (!row) return null;
input = { issueId: row.issueId ?? null, requestedByUserId: row.requestedByUserId };
title = approvalTitle(row.type, row.payload);
since = row.updatedAt;
required = true;
} else if (source.sourceKind === "budget_alert") {
// The budget owner's card is the open hard stop (PAP-749 task 1d). It has
// no issue; everything else about a budget card is a Company alert.
const [row] = await db
.select({
scopeType: budgetIncidents.scopeType,
scopeId: budgetIncidents.scopeId,
thresholdType: budgetIncidents.thresholdType,
status: budgetIncidents.status,
createdAt: budgetIncidents.createdAt,
})
.from(budgetIncidents)
.where(and(eq(budgetIncidents.companyId, companyId), eq(budgetIncidents.id, source.sourceId)))
.limit(1);
if (!row || row.status !== "open") return null;
const hard = row.thresholdType === "hard";
input = { issueId: null, companyScoped: true, escalatesToBudgetOwner: hard };
const scopeName = await budgetScopeName(db, row.scopeType as BudgetScopeType, row.scopeId);
title = `${scopeName} budget ${hard ? "hard stop" : "warning"}`;
since = row.createdAt;
required = false;
} else {
const [row] = await db
.select({ originIssueId: decisions.originIssueId, title: decisions.title, createdAt: decisions.createdAt })
.from(decisions)
.where(and(eq(decisions.companyId, companyId), eq(decisions.id, source.sourceId)))
.limit(1);
if (!row) return null;
input = { issueId: row.originIssueId };
title = row.title;
since = row.createdAt;
required = false;
}
const [contexts, config] = await Promise.all([
resolveIssueAudienceContextMap(db, companyId, [input.issueId]),
loadCompanyAttentionConfig(db, companyId),
]);
const companyConfig = {
defaultDecisionOwnerUserId: config.defaultDecisionOwnerUserId,
budgetOwnerUserId: config.budgetOwnerUserId,
};
const ctx = input.issueId ? contexts.get(input.issueId) ?? null : null;
const audience = escalateStaleAudience({
audience: resolveAttentionAudience(input, ctx, companyConfig),
since,
required,
now,
companyConfig,
ctx,
});
return { audience, issueId: input.issueId, title };
}
/**
* Who a card is for when a person acts on it, read before the action changes
* it. `null` when the actor is no person, the card is for nobody in
* particular, or the actor is that person (no receipt for yourself). Never
* throws: a missing receipt must not block the answer.
*/
export async function attentionHandledFor(
db: Db,
companyId: string,
source: { sourceKind: AttentionHandledSourceKind; sourceId: string },
actorUserId: string | null | undefined,
): Promise<AttentionHandledFor | null> {
if (!actorUserId) return null;
try {
const card = await resolveAttentionCardAudience(db, companyId, source);
if (!card || card.audience.kind !== "user" || !card.audience.userId) return null;
if (card.audience.userId === actorUserId) return null;
return {
userId: card.audience.userId,
actorUserId,
sourceKind: source.sourceKind,
sourceId: source.sourceId,
issueId: card.issueId,
title: card.title,
};
} catch (err) {
logger.warn({ err, companyId, ...source }, "attention receipt audience lookup failed");
return null;
}
}
/** Spread into the action's activity `details`. Empty when there is no other person. */
export function attentionHandledDetails(
handledFor: AttentionHandledFor | null | undefined,
outcome: AttentionReceiptOutcome,
extra: { reason?: string | null; transferredToUserId?: string | null } = {},
): AttentionHandledDetailsFragment {
if (!handledFor) return {};
return {
handledForUserId: handledFor.userId,
receipt: {
outcome,
sourceKind: handledFor.sourceKind,
sourceId: handledFor.sourceId,
issueId: handledFor.issueId,
title: handledFor.title,
actorUserId: handledFor.actorUserId,
...(extra.reason?.trim() ? { reason: extra.reason.trim() } : {}),
...(extra.transferredToUserId ? { transferredToUserId: extra.transferredToUserId } : {}),
},
};
}
export function attentionReceiptDismissalKey(activityId: string) {
return `${ATTENTION_RECEIPT_DISMISSAL_PREFIX}${activityId}`;
}
function readString(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value : null;
}
/** The stored receipt of one activity entry, or `null` when it is malformed. */
export function readAttentionHandledDetails(details: unknown): AttentionHandledDetails | null {
if (!details || typeof details !== "object") return null;
const receipt = (details as Record<string, unknown>).receipt;
if (!receipt || typeof receipt !== "object") return null;
const record = receipt as Record<string, unknown>;
const outcome = readString(record.outcome);
const sourceKind = readString(record.sourceKind);
const sourceId = readString(record.sourceId);
const actorUserId = readString(record.actorUserId);
if (!outcome || !(ATTENTION_RECEIPT_OUTCOMES as readonly string[]).includes(outcome)) return null;
if (!sourceKind || !(ATTENTION_SOURCE_KINDS as readonly string[]).includes(sourceKind)) return null;
if (!sourceId || !actorUserId) return null;
return {
outcome: outcome as AttentionReceiptOutcome,
sourceKind: sourceKind as AttentionSourceKind,
sourceId,
issueId: readString(record.issueId),
title: readString(record.title),
actorUserId,
reason: readString(record.reason),
transferredToUserId: readString(record.transferredToUserId),
};
}
/** SQL: the entry names this person as the one a card was for. */
export function handledForUserCondition(userId: string) {
return sql<boolean>`(${activityLog.details} ->> 'handledForUserId') = ${userId}`;
}
export function attentionReceiptService(db: Db) {
return {
/**
* Receipts for one person, newest first: one per card, from the last
* {@link ATTENTION_RECEIPT_DAYS} days, without the ones they dismissed or
* can no longer read.
*/
list: async (
companyId: string,
options: { userId: string; actor: AuthorizationActor; now?: number },
): Promise<AttentionReceipt[]> => {
const now = options.now ?? Date.now();
const since = new Date(now - ATTENTION_RECEIPT_DAYS * DAY_MS);
const rows = await db
.select({ id: activityLog.id, createdAt: activityLog.createdAt, details: activityLog.details })
.from(activityLog)
.where(and(
eq(activityLog.companyId, companyId),
handledForUserCondition(options.userId),
gte(activityLog.createdAt, since),
))
.orderBy(desc(activityLog.createdAt), desc(activityLog.id))
.limit(RECEIPT_SCAN_LIMIT);
// Withdraw through Needs You writes the source's own entry and
// `attention.closed`; both name the person. Keep the newest per card.
const seen = new Set<string>();
const candidates: Array<{ id: string; createdAt: Date; receipt: AttentionHandledDetails }> = [];
for (const row of rows) {
const receipt = readAttentionHandledDetails(row.details);
if (!receipt || receipt.actorUserId === options.userId) continue;
const key = `${receipt.sourceKind}:${receipt.sourceId}`;
if (seen.has(key)) continue;
seen.add(key);
candidates.push({ id: row.id, createdAt: row.createdAt, receipt });
}
if (candidates.length === 0) return [];
const keys = candidates.map((candidate) => attentionReceiptDismissalKey(candidate.id));
const issueIds = [...new Set(candidates.map((candidate) => candidate.receipt.issueId).filter((id): id is string => Boolean(id)))];
const readCondition = await issueReadSqlCondition(db, options.actor);
const approvalIds = candidates.filter(candidate => candidate.receipt.sourceKind === "approval").map(candidate => candidate.receipt.sourceId);
const approvalRead = await approvalReadSqlCondition(db, options.actor);
const [dismissedRows, issueRows, company, approvalRows] = await Promise.all([
db
.select({ itemKey: inboxDismissals.itemKey })
.from(inboxDismissals)
.where(and(
eq(inboxDismissals.companyId, companyId),
eq(inboxDismissals.userId, options.userId),
inArray(inboxDismissals.itemKey, keys),
)),
issueIds.length > 0
? db
.select({ id: issues.id, identifier: issues.identifier, title: issues.title })
.from(issues)
.where(and(eq(issues.companyId, companyId), inArray(issues.id, issueIds), readCondition))
: Promise.resolve([]),
db.select({ prefix: companies.issuePrefix }).from(companies).where(eq(companies.id, companyId)).then((r) => r[0] ?? null),
approvalIds.length ? db.select({ id: approvals.id }).from(approvals).where(and(
eq(approvals.companyId, companyId), inArray(approvals.id, approvalIds), approvalRead,
)) : Promise.resolve([]),
]);
const dismissed = new Set(dismissedRows.map((row) => row.itemKey));
const readableIssues = new Map(issueRows.map((row) => [row.id, row]));
const readableApprovals = new Set(approvalRows.map(row => row.id));
const prefix = company?.prefix ?? "PAP";
const receipts: AttentionReceipt[] = [];
for (const { id, createdAt, receipt } of candidates) {
const dismissalKey = attentionReceiptDismissalKey(id);
if (dismissed.has(dismissalKey)) continue;
if (receipt.sourceKind === "approval" && !readableApprovals.has(receipt.sourceId)) continue;
const issueRow = receipt.issueId ? readableIssues.get(receipt.issueId) : null;
// A task the person can no longer read takes its receipt with it.
if (receipt.issueId && !issueRow) continue;
const issueHref = issueRow ? `/${prefix}/issues/${issueRow.identifier ?? issueRow.id}` : null;
receipts.push({
id,
dismissalKey,
outcome: receipt.outcome,
sourceKind: receipt.sourceKind,
sourceId: receipt.sourceId,
title: receipt.title,
reason: receipt.reason ?? null,
actorUserId: receipt.actorUserId,
transferredToUserId: receipt.transferredToUserId ?? null,
issue: issueRow && issueHref
? { id: issueRow.id, identifier: issueRow.identifier, title: issueRow.title, href: issueHref }
: null,
href: receipt.sourceKind === "approval"
? `/${prefix}/approvals/${receipt.sourceId}`
: receipt.sourceKind === "budget_alert"
? `/${prefix}/costs`
: issueHref && receipt.sourceKind === "issue_thread_interaction"
? `${issueHref}#interaction-${receipt.sourceId}`
: issueHref,
createdAt: createdAt.toISOString(),
expiresAt: new Date(createdAt.getTime() + ATTENTION_RECEIPT_DAYS * DAY_MS).toISOString(),
});
if (receipts.length >= RECEIPT_LIMIT) break;
}
return receipts;
},
};
}
@@ -48,11 +48,11 @@ export function collapsePendingConfirmationsToNewest<T extends {
addresseeUserId?: string | null;
addresseeAgentId?: string | null;
}>(rows: T[], newestSettledConfirmationAt: ReadonlyMap<string, Date> = new Map()) {
const independent = (row: T) => payloadFlag(row.payload, "qualityReview");
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 = `${row.issueId}:${row.kind}`;
const groupKey = confirmationAudienceKey(row);
const newest = newestByGroup.get(groupKey);
if (
!newest
@@ -65,8 +65,8 @@ export function collapsePendingConfirmationsToNewest<T extends {
return rows.filter((row) => {
if (row.kind !== "request_confirmation" || independent(row)) return true;
if (newestByGroup.get(`${row.issueId}:${row.kind}`)?.id !== row.id) return false;
const settledAt = governedAction(row.payload) ? undefined : newestSettledConfirmationAt.get(confirmationAudienceKey(row));
if (newestByGroup.get(confirmationAudienceKey(row))?.id !== row.id) return false;
const settledAt = newestSettledConfirmationAt.get(confirmationAudienceKey(row));
return !settledAt || settledAt.getTime() <= row.createdAt.getTime();
});
}
File diff suppressed because it is too large. Load diff
+16
View File
@@ -99,6 +99,7 @@ export type AuthorizationAction =
| "agent_instructions:update"
| "skill_config:update"
| "agent:read"
| "attention:route"
| "agent:wake"
| "company_scope:read"
| "decision_queue:manage"
@@ -196,6 +197,7 @@ function permissionForAction(action: AuthorizationAction): PermissionKey | null
return null;
}
if (
action === "attention:route" ||
action === "agent:read" ||
action === "agent:wake" ||
action === "company_scope:read" ||
@@ -2017,6 +2019,11 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
});
}
if (input.action === "attention:route" && input.actor.type !== "board") {
return deny({ action: input.action, reason: "deny_unsupported_action",
explanation: "Only a human routing administrator can reroute another person's request." });
}
if (input.action === "runtime:confirm_owner_stop" && input.actor.type !== "board") {
return deny({ action: input.action, reason: "deny_unsupported_action",
explanation: "Only a deployment administrator can confirm a workspace controller has stopped." });
@@ -2050,6 +2057,15 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
explanation: "Allowed because the actor is an instance admin.",
});
}
if (input.action === "attention:route") {
const membership = await getActiveMembership(companyId, "user", input.actor.userId ?? "");
if (membership?.membershipRole === "owner" || membership?.membershipRole === "admin") {
return allow({ action: input.action, reason: "allow_role_default",
explanation: "Allowed by the active company owner or administrator role." });
}
return deny({ action: input.action, reason: "deny_missing_grant",
explanation: "Only a company owner, company administrator, or instance administrator can reroute another person's request." });
}
if (input.action === "runtime:confirm_owner_stop") {
const membership = await getActiveMembership(companyId, "user", input.actor.userId ?? "");
if (membership?.membershipRole === "owner" || membership?.membershipRole === "admin") {
+10 -2
View File
@@ -187,6 +187,12 @@ async function resolveSummaryScopeRecord(db: Db, companyId: string, scopeType: B
return scope;
}
/** The display name of a budget scope, as budget incidents show it. */
export async function budgetScopeName(db: Db, scopeType: BudgetScopeType, scopeId: string): Promise<string> {
const scope = await resolveScopeRecord(db, scopeType, scopeId);
return normalizeScopeName(scopeType, scope.name);
}
// Keep a large dashboard from filling the database pool with queued reads.
async function mapBudgetReads<T, R>(rows: T[], read: (row: T) => Promise<R>): Promise<R[]> {
const result: R[] = [];
@@ -1012,6 +1018,7 @@ export function budgetServiceInTransaction(db: Db, publications: ActivityPublica
actorUserId: string,
/** The resolving actor's session source, kept for the continuation Retry. */
actorSource?: string | null,
options: { activityDetails?: Record<string, unknown> } = {},
): Promise<BudgetIncident> => {
const incident = await db
.select()
@@ -1123,6 +1130,7 @@ export function budgetServiceInTransaction(db: Db, publications: ActivityPublica
amount: input.amount ?? null,
scopeType: incident.scopeType,
scopeId: incident.scopeId,
...options.activityDetails,
},
});
@@ -1379,11 +1387,11 @@ export function budgetService(db: Db, _hooks: BudgetServiceHooks = {}) {
withBudgetSpan("budget.admission.inspect", () => withAccountingReadSnapshot(db, companyId,
tx => budgetServiceInTransaction(tx).getInvocationBlock(companyId, agentId, context))),
resolveIncident: async (companyId: string, incidentId: string, input: BudgetIncidentResolutionInput, actorUserId: string,
actorSource?: string | null) => {
actorSource?: string | null, options: { activityDetails?: Record<string, unknown> } = {}) => {
const [scope] = await db.select({ scopeType: budgetIncidents.scopeType, scopeId: budgetIncidents.scopeId }).from(budgetIncidents)
.where(and(eq(budgetIncidents.id, incidentId), eq(budgetIncidents.companyId, companyId)));
if (!scope) throw notFound("Budget incident not found");
return mutate(companyId, service => service.resolveIncident(companyId, incidentId, input, actorUserId, actorSource), scope);
return mutate(companyId, service => service.resolveIncident(companyId, incidentId, input, actorUserId, actorSource, options), scope);
},
};
}
@@ -0,0 +1,95 @@
import { and, eq, gte, or, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { issues, issueThreadInteractions } from "@paperclipai/db";
import { logger } from "../middleware/logger.js";
import { logActivity } from "./activity-log.js";
import { historicalQuestionCondition } from "./issue-question-context.js";
import { issueThreadInteractionService } from "./issue-thread-interactions.js";
const SWEEP_SOURCE = "attention.closed_issue_sweep";
/**
* Expire pending cards that still hang on done or cancelled issues (PAP-749
* plan §2). The status transition already runs the terminal-issue expiry, but
* older rows predate it and some write paths skipped it, so those cards kept
* asking for answers on closed work.
*
* Each issue goes through `expirePendingInteractionsForTerminalIssue`, so the
* rules stay in one place: a cancelled issue expires every pending card, and a
* done issue keeps its ordinary historical questions answerable. The candidate
* query uses the same conditions, so a second run finds nothing and changes
* nothing. It runs once per server start; it recovers durable rows and is not
* a polling loop.
*/
export async function expirePendingInteractionsOnClosedIssues(db: Db) {
const candidates = await db
.selectDistinct({
id: issues.id,
companyId: issues.companyId,
identifier: issues.identifier,
status: issues.status,
})
.from(issueThreadInteractions)
.innerJoin(issues, and(
eq(issueThreadInteractions.issueId, issues.id),
eq(issueThreadInteractions.companyId, issues.companyId),
))
.where(and(
eq(issueThreadInteractions.status, "pending"),
or(
eq(issues.status, "cancelled"),
and(eq(issues.status, "done"), sql`not ${historicalQuestionCondition()}`),
),
));
const interactions = issueThreadInteractionService(db);
let expired = 0;
let failed = 0;
for (const issue of candidates) {
const startedAt = new Date();
let rows: Array<{ id: string; kind: string; status: string; result?: unknown }>;
try {
rows = await interactions.expirePendingInteractionsForTerminalIssue(issue, {});
} catch (err) {
// One bad card (e.g. a legacy payload) must not strand the rest; the
// next start retries it. Each card expires in its own transaction, so
// earlier cards on this issue may already be closed: log those too.
failed += 1;
logger.warn({ err, issueId: issue.id }, "closed-issue interaction sweep failed for one issue");
rows = await db
.select({
id: issueThreadInteractions.id,
kind: issueThreadInteractions.kind,
status: issueThreadInteractions.status,
result: issueThreadInteractions.result,
})
.from(issueThreadInteractions)
.where(and(
eq(issueThreadInteractions.companyId, issue.companyId),
eq(issueThreadInteractions.issueId, issue.id),
eq(issueThreadInteractions.status, "expired"),
gte(issueThreadInteractions.resolvedAt, startedAt),
));
}
for (const row of rows) {
await logActivity(db, {
companyId: issue.companyId,
actorType: "system",
actorId: SWEEP_SOURCE,
action: "issue.thread_interaction_expired",
entityType: "issue",
entityId: issue.id,
details: {
identifier: issue.identifier ?? null,
interactionId: row.id,
interactionKind: row.kind,
interactionStatus: row.status,
source: SWEEP_SOURCE,
result: row.result ?? null,
},
});
}
expired += rows.length;
}
return { issues: candidates.length, expired, failed };
}
+2
View File
@@ -127,6 +127,8 @@ export function companyService(db: Db, _budgetHooks: BudgetServiceHooks = {}) {
budgetMonthlyCents: companies.budgetMonthlyCents,
spentMonthlyCents: companies.spentMonthlyCents,
defaultResponsibleUserId: companies.defaultResponsibleUserId,
defaultDecisionOwnerUserId: companies.defaultDecisionOwnerUserId,
budgetOwnerUserId: companies.budgetOwnerUserId,
requireBoardApprovalForNewAgents: companies.requireBoardApprovalForNewAgents,
interactionResolverGovernance: companies.interactionResolverGovernance,
feedbackDataSharingEnabled: companies.feedbackDataSharingEnabled,
+337 -19
View File
@@ -1,8 +1,13 @@
import { and, asc, desc, eq, ilike, inArray, isNotNull, notInArray, or, sql, type SQL } from "drizzle-orm";
import { agents, companies, decisions, decisionTargetIssues, issues, issueThreadInteractions, projects, type Db } from "@paperclipai/db";
import type { DecisionHistoryItem, DecisionHistoryPage, DecisionHistoryQuery } from "@paperclipai/shared";
import { issueReadSqlCondition, type AuthorizationActor } from "./authorization.js";
import { and, asc, desc, eq, ilike, inArray, isNotNull, isNull, notInArray, or, sql, type SQL } from "drizzle-orm";
import { alias } from "drizzle-orm/pg-core";
import { activityLog, agents, approvals, budgetIncidents, companies, decisions, decisionTargetIssues, issues, issueThreadInteractions, projects, type Db } from "@paperclipai/db";
import { ATTENTION_RECEIPT_OUTCOME_TEXT, type DecisionHistoryAction, type DecisionHistoryItem, type DecisionHistoryPage, type DecisionHistoryQuery, type DecisionHistoryResultOutcome } from "@paperclipai/shared";
import { approvalReadSqlCondition, issueReadSqlCondition, type AuthorizationActor } from "./authorization.js";
import { badRequest } from "../errors.js";
import { firstApprovalIssueId } from "./approval-visibility.js";
import { approvalTitle, MAX_INSTIGATOR_CHAIN_DEPTH } from "./attention.js";
import { readAttentionHandledDetails } from "./attention-receipts.js";
import { humanCreatedIssueCondition } from "./issue-participation.js";
type HistoryOptions = DecisionHistoryQuery & { actor: AuthorizationActor; userId: string; issueIds?: string[] };
type Cursor = { at: string; id: string; sort: "newest" | "oldest" };
@@ -18,11 +23,112 @@ export function itemVerdictsHistoryLabel(result: unknown): string | null {
counts.defer ? `${counts.defer} deferred` : null].filter(Boolean).join(" · ") || "Review recorded";
}
function readRecordValue(value: unknown, key: string) {
return value && typeof value === "object" && !Array.isArray(value) && key in value
? (value as Record<string, unknown>)[key]
: undefined;
}
/**
* History labels by outcome. An interaction's `result.outcome` is more
* specific than its status: a withdrawn, skipped or task-closed card is stored
* as `cancelled` or `expired` (PAP-749 plan §2, Data and §3). A withdraw by a
* person reads `withdrawn_by_user`; one by the agent itself stays `withdrawn`.
*/
const HISTORY_OUTCOME_LABELS: Record<string, string> = {
accepted: "Approved", rejected: "Changes requested", answered: "Answers recorded", cancelled: "Cancelled",
expired: "Expired", failed: "Failed", stale_target: "Superseded", superseded_by_newer_request: "Superseded",
superseded_by_comment: "Answered in task", withdrawn: "Withdrawn", withdrawn_by_user: "Withdrawn by user",
skipped: "Skipped", issue_closed: "Closed with task",
};
/** Approval labels by status (PAP-749 plan §3: approvals in history). */
const APPROVAL_OUTCOME_LABELS: Record<string, string> = {
approved: "Approved", rejected: "Rejected", revision_requested: "Revision requested", cancelled: "Cancelled",
};
/** History outcome filters that read `result.outcome`, not the status. */
const RESULT_OUTCOME_FILTERS = new Set(["withdrawn", "withdrawn_by_user", "skipped", "issue_closed"]);
const RESULT_OUTCOMES: ReadonlySet<string> = new Set<DecisionHistoryResultOutcome>(["withdrawn", "skipped", "issue_closed"]);
/** The specific close an interaction result records, for the history filters and UI. */
export function interactionHistoryResultOutcome(result: unknown): DecisionHistoryResultOutcome | null {
const outcome = readRecordValue(result, "outcome");
return typeof outcome === "string" && RESULT_OUTCOMES.has(outcome) ? outcome as DecisionHistoryResultOutcome : null;
}
/**
* A budget hard stop's approval closes through the budget card: Raise limit
* approves it and Keep paused rejects it (`budgets.resolveIncident`).
*/
const BUDGET_APPROVAL_ACTIONS: Record<string, DecisionHistoryAction["outcome"]> = {
approved: "limit_raised", rejected: "kept_paused",
};
const APPROVAL_ACTIONS: Record<string, DecisionHistoryAction["outcome"]> = {
approved: "approved", rejected: "rejected", revision_requested: "revision_requested", cancelled: "withdrawn",
};
/** An approval's history label: a cancel by a person is a withdraw (PAP-749 plan §2, Rule 6). */
export function approvalHistoryLabel(row: { status: string; decidedByUserId: string | null; type?: string }) {
if (row.status === "cancelled" && row.decidedByUserId) return HISTORY_OUTCOME_LABELS.withdrawn_by_user!;
const budgetAction = row.type === "budget_override_required" ? BUDGET_APPROVAL_ACTIONS[row.status] : undefined;
if (budgetAction) return ATTENTION_RECEIPT_OUTCOME_TEXT[budgetAction];
return APPROVAL_OUTCOME_LABELS[row.status] ?? "Decision recorded";
}
/**
* What the person did, in the receipt's words (PAP-767): the UI renders
* "Kept paused by @dotta" from this, so a history row and the receipt for the
* same action read the same verb. `null` when no person acted.
*/
export function approvalHistoryAction(row: { status: string; decidedByUserId: string | null; type: string }): DecisionHistoryAction | null {
if (!row.decidedByUserId) return null;
const budgetAction = row.type === "budget_override_required" ? BUDGET_APPROVAL_ACTIONS[row.status] : undefined;
if (budgetAction) return { outcome: budgetAction, detail: null };
const outcome = APPROVAL_ACTIONS[row.status];
return outcome ? { outcome, detail: null } : null;
}
export function interactionHistoryAction(row: { kind: string; status: string; result: unknown; resolvedByUserId: string | null }): DecisionHistoryAction | null {
if (!row.resolvedByUserId) return null;
const resultOutcome = interactionHistoryResultOutcome(row.result);
if (resultOutcome === "withdrawn" || resultOutcome === "skipped") return { outcome: resultOutcome, detail: null };
if (resultOutcome) return null;
if (row.status === "accepted") return { outcome: "approved", detail: null };
if (row.status === "rejected") return { outcome: "changes_requested", detail: null };
if (row.status === "answered") {
return { outcome: "answered", detail: row.kind === "request_item_verdicts" ? itemVerdictsHistoryLabel(row.result) : null };
}
return null;
}
export function decisionHistoryAction(row: { status: string; resolvedByUserId: string | null; chosenLabel: string | null }): DecisionHistoryAction | null {
if (!row.resolvedByUserId) return null;
if (row.status === "decided") return { outcome: "decided", detail: row.chosenLabel };
if (row.status === "cancelled") return { outcome: "withdrawn", detail: null };
return null;
}
export function interactionHistoryLabel(row: { kind: string; status: string; result: unknown; resolvedByUserId: string | null }) {
const resultOutcome = readRecordValue(row.result, "outcome");
const outcome = typeof resultOutcome === "string" ? resultOutcome : row.status;
const key = outcome === "withdrawn" && row.resolvedByUserId ? "withdrawn_by_user" : outcome;
return (row.kind === "request_item_verdicts" ? itemVerdictsHistoryLabel(row.result) : null)
?? HISTORY_OUTCOME_LABELS[key] ?? HISTORY_OUTCOME_LABELS[row.status] ?? "Decision recorded";
}
/** The reason a person gave when they withdrew, skipped or cancelled the request. */
export function interactionHistoryReason(result: unknown): string | null {
const reason = readRecordValue(result, "reason") ?? readRecordValue(result, "cancellationReason");
return typeof reason === "string" && reason.trim() ? reason : null;
}
export function decodeDecisionHistoryCursor(value: string | undefined, sort: Cursor["sort"]): Cursor | null {
if (!value) return null;
try {
const parsed = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
if (parsed.sort !== sort || typeof parsed.id !== "string" || !/^(decision|issue_thread_interaction):[0-9a-f-]{36}$/i.test(parsed.id)
if (parsed.sort !== sort || typeof parsed.id !== "string" || !/^(decision|issue_thread_interaction|approval):[0-9a-f-]{36}$/i.test(parsed.id)
|| typeof parsed.at !== "string" || !Number.isFinite(Date.parse(parsed.at))) throw new Error();
return parsed;
} catch { throw badRequest("Invalid decision history cursor"); }
@@ -62,6 +168,116 @@ export function pageDecisionHistory(items: DecisionHistoryItem[], limit: number,
? Buffer.from(JSON.stringify({ at: last.resolvedAt, id: last.id, sort })).toString("base64url") : null };
}
type HistorySourceId = SQL | typeof decisions.id | typeof issueThreadInteractions.id | typeof approvals.id;
/**
* A receipt on an action's activity entry that names this source and matches
* `person` (PAP-749 plan §6). Receipts exist only when the actor was not the
* card's person, so they record "handled for" and "handled by" across people.
*/
function receiptSourceCondition(companyId: string, person: SQL, sourceKind: DecisionHistoryItem["sourceKind"], sourceId: HistorySourceId) {
// A budget hard stop is answered on its budget card, so the receipt names
// the incident; history lists the incident's approval (PAP-767).
const budgetReceipt = sourceKind === "approval"
? sql`or (${activityLog.details} -> 'receipt' ->> 'sourceKind' = 'budget_alert'
and ${activityLog.details} -> 'receipt' ->> 'sourceId' in (
select ${budgetIncidents.id}::text from ${budgetIncidents}
where ${budgetIncidents.companyId} = ${companyId} and ${budgetIncidents.approvalId} = ${sourceId}))`
: sql``;
return sql<boolean>`exists (
select 1 from ${activityLog}
where ${activityLog.companyId} = ${companyId}
and ${person}
and ((${activityLog.details} -> 'receipt' ->> 'sourceKind' = ${sourceKind}
and ${activityLog.details} -> 'receipt' ->> 'sourceId' = ${sourceId}::text)
${budgetReceipt})
)`;
}
/**
* "Handled for me" (PAP-749 plan §6): a different person answered, withdrew
* or transferred this card while it was for `userId`.
*/
function handledForUserSourceCondition(companyId: string, userId: string, sourceKind: DecisionHistoryItem["sourceKind"], sourceId: HistorySourceId) {
return receiptSourceCondition(companyId, sql`(${activityLog.details} ->> 'handledForUserId') = ${userId}`, sourceKind, sourceId);
}
/** `userId` handled this card for someone else, or someone else handled it for `userId` (a transfer included). */
function handledByOrForUserSourceCondition(companyId: string, userId: string, sourceKind: DecisionHistoryItem["sourceKind"], sourceId: HistorySourceId) {
return receiptSourceCondition(companyId, sql`((${activityLog.details} ->> 'handledForUserId') = ${userId}
or (${activityLog.details} -> 'receipt' ->> 'actorUserId') = ${userId})`, sourceKind, sourceId);
}
/**
* The tasks `userId` instigated: the ones they created by hand, and the agent
* or routine work under them up to the next hand-made task, the same walk as
* the live audience (`resolveIssueAudienceContextMap`). One walk down from the
* person's own tasks over the (company, parent) index, not one per row.
*/
function instigatedIssueIdsSql(companyId: string, userId: string) {
const root = alias(issues, "history_instigator_root");
const child = alias(issues, "history_instigator_child");
return sql`with recursive history_instigated(id, depth) as (
select ${root.id}, 0 from ${issues} ${sql.identifier("history_instigator_root")}
where ${root.companyId} = ${companyId} and ${root.createdByUserId} = ${userId} and ${humanCreatedIssueCondition(root)}
union all
select ${child.id}, history_instigated.depth + 1 from ${issues} ${sql.identifier("history_instigator_child")}
inner join history_instigated on ${child.parentId} = history_instigated.id
where ${child.companyId} = ${companyId} and not ${humanCreatedIssueCondition(child)}
and history_instigated.depth < ${MAX_INSTIGATOR_CHAIN_DEPTH}
) select id from history_instigated`;
}
/**
* The card's task makes it `userId`'s (PAP-749 plan §1, Rule 2): the chat
* user, else the human assignee, else the instigator. Read from the task as it
* is now. Escalation owners are left out: a card that reached its project's
* or the company's decision owner is in their history once they handle it.
*/
function issueAudienceIsUserCondition(companyId: string, userId: string) {
return or(
eq(issues.conversationUserId, userId),
and(isNull(issues.conversationUserId), eq(issues.assigneeUserId, userId)),
and(isNull(issues.conversationUserId), isNull(issues.assigneeUserId),
sql`${issues.id} in (${instigatedIssueIdsSql(companyId, userId)})`),
);
}
/**
* The person each answered card was for, when someone else answered it
* ("Answered by @x for @y"). A transfer is not the answer, so it is skipped.
*/
async function handledForBySource(db: Db, companyId: string, items: Array<Pick<DecisionHistoryItem, "sourceKind" | "sourceId">>) {
const result = new Map<string, string>();
if (items.length === 0) return result;
// A budget hard stop's receipt names the incident, not its approval (PAP-767).
const approvalIds = items.filter((item) => item.sourceKind === "approval").map((item) => item.sourceId);
const incidentRows = approvalIds.length === 0 ? [] : await db
.select({ id: budgetIncidents.id, approvalId: budgetIncidents.approvalId })
.from(budgetIncidents)
.where(and(eq(budgetIncidents.companyId, companyId), inArray(budgetIncidents.approvalId, approvalIds)));
const approvalByIncident = new Map(incidentRows.map((row) => [row.id, row.approvalId!]));
const sourceIds = [...items.map((item) => item.sourceId), ...approvalByIncident.keys()];
const rows = await db
.select({ details: activityLog.details, createdAt: activityLog.createdAt })
.from(activityLog)
.where(and(
eq(activityLog.companyId, companyId),
sql`(${activityLog.details} ->> 'handledForUserId') IS NOT NULL`,
inArray(sql<string>`${activityLog.details} -> 'receipt' ->> 'sourceId'`, sourceIds),
))
.orderBy(desc(activityLog.createdAt));
for (const row of rows) {
const receipt = readAttentionHandledDetails(row.details);
const userId = (row.details as Record<string, unknown> | null)?.handledForUserId;
if (!receipt || receipt.outcome === "transferred" || typeof userId !== "string") continue;
const budgetApprovalId = receipt.sourceKind === "budget_alert" ? approvalByIncident.get(receipt.sourceId) : undefined;
const key = budgetApprovalId ? `approval:${budgetApprovalId}` : `${receipt.sourceKind}:${receipt.sourceId}`;
if (!result.has(key)) result.set(key, userId);
}
return result;
}
export function decisionHistoryService(db: Db) {
return { async list(companyId: string, options: HistoryOptions): Promise<DecisionHistoryPage> {
if (options.issueIds?.length === 0) return { items: [], nextCursor: null };
@@ -78,18 +294,76 @@ export function decisionHistoryService(db: Db) {
// ordering to that same precision; the canonical source key breaks ties.
const interactionTime = sql<Date>`date_trunc('milliseconds', ${issueThreadInteractions.resolvedAt})`;
const decisionTime = sql<Date>`date_trunc('milliseconds', coalesce(${decisions.decidedAt}, ${decisions.updatedAt}))`;
const approvalTime = sql<Date>`date_trunc('milliseconds', coalesce(${approvals.decidedAt}, ${approvals.updatedAt}))`;
const interactionKey = sql<string>`'issue_thread_interaction:' || ${issueThreadInteractions.id}`;
const decisionKey = sql<string>`'decision:' || ${decisions.id}`;
const approvalKey = sql<string>`'approval:' || ${approvals.id}`;
// Same fallback as the card title (`approvalTitle`), so search finds what the person sees.
const approvalTitleSql = sql<string>`coalesce(nullif(btrim(${approvals.payload}->>'title'), ''), nullif(btrim(${approvals.payload}->>'summary'), ''), replace(${approvals.type}, '_', ' '))`;
const approvalIssueId = firstApprovalIssueId();
const completedItemReview = and(eq(issueThreadInteractions.kind, "request_item_verdicts"),
eq(issueThreadInteractions.status, "answered"), sql`${issueThreadInteractions.result}->>'outcome' = 'resolved'`);
// Item reviews retain their canonical answered status, but outcome filters
// describe the recorded verdicts. A mixed review can match both outcomes.
const resultOutcomeFilter = options.outcome && RESULT_OUTCOME_FILTERS.has(options.outcome)
? options.outcome === "withdrawn_by_user" ? "withdrawn" : options.outcome
: null;
const withdrawnFilter = options.outcome === "withdrawn" || options.outcome === "withdrawn_by_user";
const interactionOutcome = options.outcome === "accepted" || options.outcome === "rejected"
? or(eq(issueThreadInteractions.status, options.outcome), and(completedItemReview,
sql`${issueThreadInteractions.result} @> ${JSON.stringify({ items: [{ verdict: options.outcome === "accepted" ? "approve" : "reject" }] })}::jsonb`))
: options.outcome === "answered"
? and(eq(issueThreadInteractions.status, "answered"), sql`${issueThreadInteractions.kind} <> 'request_item_verdicts'`)
: options.outcome ? eq(issueThreadInteractions.status, options.outcome) : undefined;
: resultOutcomeFilter
? and(sql`${issueThreadInteractions.result}->>'outcome' = ${resultOutcomeFilter}`,
options.outcome === "withdrawn_by_user" ? isNotNull(issueThreadInteractions.resolvedByUserId) : undefined)
// "Expired" is a time-out or supersede; a card that closed with its
// task is stored as expired too but has its own filter (plan §3).
: options.outcome === "expired"
? and(eq(issueThreadInteractions.status, "expired"),
sql`coalesce(${issueThreadInteractions.result}->>'outcome', '') <> 'issue_closed'`)
: options.outcome ? eq(issueThreadInteractions.status, options.outcome) : undefined;
// A decision a person withdrew is a cancelled decision with its closer
// recorded; skipped and task-closed outcomes do not exist for decisions.
const decisionOutcome = withdrawnFilter
? and(eq(decisions.status, "cancelled"), isNotNull(decisions.decidedByUserId))
: resultOutcomeFilter
? sql`false`
: options.outcome ? eq(decisions.status, options.outcome) : undefined;
// Approvals use their own statuses. Approved and rejected map to the
// shared Approved and Changes requested filters; a cancel by a person is
// a withdraw. Approvals never expire, answer, decide or close with a task.
const approvalStatusByFilter: Record<string, string> = { accepted: "approved", rejected: "rejected" };
const approvalOutcome = withdrawnFilter
? and(eq(approvals.status, "cancelled"), isNotNull(approvals.decidedByUserId))
: resultOutcomeFilter || options.outcome === "answered" || options.outcome === "decided" || options.outcome === "expired"
? sql`false`
: options.outcome ? eq(approvals.status, approvalStatusByFilter[options.outcome] ?? options.outcome) : undefined;
// "Handled by me or for me" (PAP-768): what the person answered, withdrew
// or transferred, what a different person handled for them, and the cards
// whose audience is them: the addressee or requester, else the task's person.
const mine = options.scope === "mine";
const userId = options.userId;
const interactionScope = mine ? or(
eq(issueThreadInteractions.resolvedByUserId, userId),
eq(issueThreadInteractions.addresseeUserId, userId),
and(isNull(issueThreadInteractions.addresseeUserId), issueAudienceIsUserCondition(companyId, userId)),
handledByOrForUserSourceCondition(companyId, userId, "issue_thread_interaction", issueThreadInteractions.id),
) : undefined;
const decisionScope = mine ? or(
eq(decisions.decidedByUserId, userId),
issueAudienceIsUserCondition(companyId, userId),
handledByOrForUserSourceCondition(companyId, userId, "decision", decisions.id),
) : undefined;
const approvalScope = mine ? or(
eq(approvals.decidedByUserId, userId),
eq(approvals.requestedByUserId, userId),
and(isNull(approvals.requestedByUserId), isNotNull(issues.id), issueAudienceIsUserCondition(companyId, userId)),
// A hard stop's override approval is folded into the budget owner's card.
and(eq(approvals.type, "budget_override_required"),
sql`exists (select 1 from ${companies} where ${companies.id} = ${companyId} and ${companies.budgetOwnerUserId} = ${userId})`),
handledByOrForUserSourceCondition(companyId, userId, "approval", approvals.id),
) : undefined;
const conditions = (time: SQL, key: SQL, title: SQL | typeof decisions.title | typeof issueThreadInteractions.title) => [
options.issueIds ? inArray(issues.id, options.issueIds) : undefined,
options.projectId ? eq(issues.projectId, options.projectId) : undefined,
@@ -98,9 +372,10 @@ export function decisionHistoryService(db: Db) {
cursor ? sql`(${time}, ${key}) ${sql.raw(sort === "oldest" ? ">" : "<")} (${cursor.at}::timestamptz, ${cursor.id})` : undefined,
];
const order = sort === "oldest" ? asc : desc;
// Two bounded queries, keyset-paginated before materializing payloads. Every
// task and every Decisions-v1 target passes the same task-read predicate.
const [interactionRows, decisionRows] = await Promise.all([
// Three bounded queries, keyset-paginated before materializing payloads.
// Every task and every Decisions-v1 target passes the same task-read
// predicate; an approval linked to a task needs that task to be readable.
const [interactionRows, decisionRows, approvalRows] = await Promise.all([
db.select({ sourceId: issueThreadInteractions.id, issueId: issues.id, issueIdentifier: issues.identifier, issueTitle: issues.title,
agentId: agents.id, agentName: agents.name, projectId: projects.id, projectName: projects.name,
title: issueThreadInteractions.title, outcome: issueThreadInteractions.status, resolvedAt: issueThreadInteractions.resolvedAt,
@@ -111,38 +386,81 @@ export function decisionHistoryService(db: Db) {
.leftJoin(projects, and(eq(projects.id, issues.projectId), eq(projects.companyId, companyId)))
.where(and(eq(issueThreadInteractions.companyId, companyId), readable, isNotNull(issueThreadInteractions.resolvedAt),
notInArray(issueThreadInteractions.status, ["pending"]),
interactionOutcome,
interactionOutcome, interactionScope,
options.handledForMe ? handledForUserSourceCondition(companyId, options.userId, "issue_thread_interaction", issueThreadInteractions.id) : undefined,
options.agentId ? eq(issueThreadInteractions.createdByAgentId, options.agentId) : undefined,
...conditions(interactionTime, interactionKey, issueThreadInteractions.title)))
.orderBy(order(interactionTime), order(interactionKey)).limit(limit + 1),
db.select({ sourceId: decisions.id, issueId: issues.id, issueIdentifier: issues.identifier, issueTitle: issues.title,
agentId: agents.id, agentName: agents.name, projectId: projects.id, projectName: projects.name,
title: decisions.title, outcome: decisions.status, resolvedAt: decisionTime,
resolvedByUserId: decisions.decidedByUserId, chosenOptionId: decisions.chosenOptionId, options: decisions.options })
resolvedByUserId: decisions.decidedByUserId, chosenOptionId: decisions.chosenOptionId, options: decisions.options,
metadata: decisions.metadata })
.from(decisions).innerJoin(issues, and(eq(issues.id, decisions.originIssueId), eq(issues.companyId, companyId)))
.leftJoin(agents, and(eq(agents.id, decisions.originAgentId), eq(agents.companyId, companyId)))
.leftJoin(projects, and(eq(projects.id, issues.projectId), eq(projects.companyId, companyId)))
.where(and(eq(decisions.companyId, companyId), readable, notInArray(decisions.status, ["open"]),
sql`not exists (select 1 from ${decisionTargetIssues} where ${decisionTargetIssues.decisionId} = ${decisions.id} and (${decisionTargetIssues.companyId} <> ${companyId} or ${decisionTargetIssues.issueId} not in (${readableIssues})))`,
options.outcome ? eq(decisions.status, options.outcome) : undefined,
decisionOutcome, decisionScope,
options.handledForMe ? handledForUserSourceCondition(companyId, options.userId, "decision", decisions.id) : undefined,
options.agentId ? eq(decisions.originAgentId, options.agentId) : undefined,
...conditions(decisionTime, decisionKey, decisions.title)))
.orderBy(order(decisionTime), order(decisionKey)).limit(limit + 1),
db.select({ sourceId: approvals.id, issueId: issues.id, issueIdentifier: issues.identifier, issueTitle: issues.title,
agentId: agents.id, agentName: agents.name, projectId: projects.id, projectName: projects.name,
type: approvals.type, payload: approvals.payload, outcome: approvals.status, resolvedAt: approvalTime,
resolvedByUserId: approvals.decidedByUserId, decisionNote: approvals.decisionNote })
.from(approvals).leftJoin(issues, and(eq(issues.id, approvalIssueId), eq(issues.companyId, companyId)))
.leftJoin(agents, and(eq(agents.id, approvals.requestedByAgentId), eq(agents.companyId, companyId)))
.leftJoin(projects, and(eq(projects.id, issues.projectId), eq(projects.companyId, companyId)))
.where(and(eq(approvals.companyId, companyId), await approvalReadSqlCondition(db, options.actor), notInArray(approvals.status, ["pending"]),
or(sql`${approvalIssueId} is null`, and(isNotNull(issues.id), readable)),
approvalOutcome, approvalScope,
options.handledForMe ? handledForUserSourceCondition(companyId, options.userId, "approval", approvals.id) : undefined,
options.agentId ? eq(approvals.requestedByAgentId, options.agentId) : undefined,
...conditions(approvalTime, approvalKey, approvalTitleSql)))
.orderBy(order(approvalTime), order(approvalKey)).limit(limit + 1),
]);
const interactionItems: DecisionHistoryItem[] = interactionRows.map(({ kind, payload, result, ...row }) => {
const target = decisionHistoryTarget(payload);
const resultOutcome = result && "outcome" in result ? String(result.outcome) : row.outcome;
const labels: Record<string, string> = { accepted: "Approved", rejected: "Changes requested", answered: "Answers recorded", cancelled: "Cancelled", expired: "Expired", failed: "Failed", stale_target: "Superseded", superseded_by_newer_request: "Superseded", superseded_by_comment: "Answered in task" };
return { ...row, title: row.title ?? row.issueTitle, resolvedAt: new Date(row.resolvedAt!).toISOString(),
id: `issue_thread_interaction:${row.sourceId}`, sourceKind: "issue_thread_interaction", label: (kind === "request_item_verdicts" ? itemVerdictsHistoryLabel(result) : null) ?? labels[resultOutcome] ?? labels[row.outcome] ?? "Decision recorded", target,
id: `issue_thread_interaction:${row.sourceId}`, sourceKind: "issue_thread_interaction",
label: interactionHistoryLabel({ kind, status: row.outcome, result, resolvedByUserId: row.resolvedByUserId }),
action: interactionHistoryAction({ kind, status: row.outcome, result, resolvedByUserId: row.resolvedByUserId }),
resultOutcome: interactionHistoryResultOutcome(result),
reason: interactionHistoryReason(result), target,
href: decisionHistoryHref(company.prefix, row.issueIdentifier ?? row.issueId, "issue_thread_interaction", row.sourceId, target) };
});
const decisionItems: DecisionHistoryItem[] = decisionRows.map(({ chosenOptionId, options: choices, ...row }) => ({
const decisionItems: DecisionHistoryItem[] = decisionRows.map(({ chosenOptionId, options: choices, metadata, ...row }) => {
const chosenLabel = choices.find((choice) => choice.id === chosenOptionId)?.label ?? null;
return {
...row, id: `decision:${row.sourceId}`, sourceKind: "decision", resolvedByAgentId: null,
resolvedAt: new Date(row.resolvedAt).toISOString(), target: null,
label: choices.find((choice) => choice.id === chosenOptionId)?.label ?? (row.outcome === "expired" ? "Expired" : row.outcome === "cancelled" ? "Cancelled" : "Decision recorded"),
label: chosenLabel ?? (row.outcome === "expired" ? "Expired"
: row.outcome === "cancelled" ? HISTORY_OUTCOME_LABELS[row.resolvedByUserId ? "withdrawn_by_user" : "cancelled"] : "Decision recorded"),
action: decisionHistoryAction({ status: row.outcome, resolvedByUserId: row.resolvedByUserId, chosenLabel }),
resultOutcome: row.outcome === "cancelled" && row.resolvedByUserId ? "withdrawn" : null,
reason: interactionHistoryReason({ reason: metadata.cancelReason }),
href: decisionHistoryHref(company.prefix, row.issueIdentifier ?? row.issueId, "decision", row.sourceId, null),
}));
return pageDecisionHistory([...interactionItems, ...decisionItems], limit, sort);
};
});
const approvalItems: DecisionHistoryItem[] = approvalRows.map(({ type, payload, decisionNote, ...row }) => {
const withdrawn = row.outcome === "cancelled" && row.resolvedByUserId != null;
return {
...row, id: `approval:${row.sourceId}`, sourceKind: "approval", resolvedByAgentId: null,
title: approvalTitle(type, payload), resolvedAt: new Date(row.resolvedAt).toISOString(), target: null,
label: approvalHistoryLabel({ status: row.outcome, decidedByUserId: row.resolvedByUserId, type }),
action: approvalHistoryAction({ status: row.outcome, decidedByUserId: row.resolvedByUserId, type }),
resultOutcome: withdrawn ? "withdrawn" : null,
// The decision note is the withdraw reason only for a cancel.
reason: row.outcome === "cancelled" ? interactionHistoryReason({ reason: decisionNote }) : null,
// An approval's own page lists its linked tasks and the full decision.
href: `/${encodeURIComponent(company.prefix)}/approvals/${encodeURIComponent(row.sourceId)}`,
};
});
const page = pageDecisionHistory([...interactionItems, ...decisionItems, ...approvalItems], limit, sort);
const handledFor = await handledForBySource(db, companyId, page.items);
for (const item of page.items) item.handledForUserId = handledFor.get(item.id) ?? null;
return page;
} };
}
+15 -5
View File
@@ -703,7 +703,9 @@ export function decisionService(db: Db, options: DecisionServiceOptions) {
}
async function decide(input: { id: string; optionId: string; inputValues?: Record<string, string>; idempotencyKey?: string | null; decidedByUserId: string;
userActor: AuthorizationActor; dismissed?: boolean; dismissReason?: string | null }) {
userActor: AuthorizationActor; dismissed?: boolean; dismissReason?: string | null;
/** Extra activity details, e.g. the receipt for the person the card was for (PAP-749 plan §6). */
activityDetails?: Record<string, unknown> }) {
const current = await get(input.id); if (!current) throw notFound("Decision not found");
const metadata = current.metadata as Record<string, unknown>;
if (!verifyDecisionSpec(spec({ id: current.id, options: current.options, targetSnapshots: current.targetSnapshots as Record<string, Snapshot> }), current.signedSpec)) throw forbidden("Decision signature verification failed");
@@ -735,21 +737,29 @@ export function decisionService(db: Db, options: DecisionServiceOptions) {
await logActivity(db, { companyId: claimed.companyId, actorType: "system", actorId: "decision-executor", agentId: claimed.originAgentId, runId: claimed.originRunId,
responsibleUserIdOverride: input.decidedByUserId, action: input.dismissed ? "decision.dismissed" : "decision.decided", entityType: "decision", entityId: claimed.id,
details: { chosenOptionId: input.optionId, decidedByUserId: input.decidedByUserId, originResponsibleUserId: run?.responsibleUserId ?? null,
...(input.dismissed ? { dismissed: true, dismissReason: input.dismissReason ?? null } : {}) } });
...(input.dismissed ? { dismissed: true, dismissReason: input.dismissReason ?? null } : {}), ...input.activityDetails } });
return resumeDecision(claimed, input.userActor);
}
async function cancel(id: string, actor: { actorType: "agent" | "user"; actorId: string; runId?: string | null }) {
async function cancel(id: string, actor: { actorType: "agent" | "user"; actorId: string; runId?: string | null },
options: { reason?: string | null; activityDetails?: Record<string, unknown> } = {}) {
const current = await get(id); if (!current) throw notFound("Decision not found");
if (actor.actorType === "agent" && actor.actorId !== current.originAgentId) throw forbidden("Only the origin agent may cancel");
if (current.status === "cancelled") {
await continuations.deliver(current.id);
return (await get(id))!;
}
const [updated] = await writeDecisionChange(db, async tx => tx.update(decisions).set({ status: "cancelled", updatedAt: new Date(), metadata: { ...current.metadata,
// A person who withdraws an out-of-date decision (PAP-749) is recorded as
// its closer, with the reason, so history can say who withdrew it.
const reason = options.reason?.trim() || null;
const byUser = actor.actorType === "user" ? { decidedByUserId: actor.actorId, decidedAt: new Date() } : {};
const [updated] = await writeDecisionChange(db, async tx => tx.update(decisions).set({ status: "cancelled", ...byUser, updatedAt: new Date(), metadata: { ...current.metadata,
...(reason ? { cancelReason: reason } : {}),
...(current.continuationPolicy === "wake_origin_agent" ? { continuationPending: true } : {}) } }).where(and(eq(decisions.id, id), eq(decisions.status, "open"))).returning(), { companyId: current.companyId, sourceId: id });
if (!updated) throw conflict("decision_already_resolved", { code: "decision_already_resolved" });
await logActivity(db, { companyId: updated.companyId, actorType: actor.actorType, actorId: actor.actorId, runId: actor.runId, action: "decision.cancelled", entityType: "decision", entityId: id });
const details = { ...(reason ? { reason } : {}), ...options.activityDetails };
await logActivity(db, { companyId: updated.companyId, actorType: actor.actorType, actorId: actor.actorId, runId: actor.runId, action: "decision.cancelled", entityType: "decision", entityId: id,
...(Object.keys(details).length > 0 ? { details } : {}) });
await continuations.deliver(updated.id);
return (await get(id))!;
}
+10 -3
View File
@@ -8,11 +8,14 @@ export function inboxDismissalService(db: Db) {
companyId: string,
userId: string,
itemKey: string,
input: { kind: InboxDismissalKind; dismissedAt?: Date; snoozedUntil?: Date | null },
input: { kind: InboxDismissalKind; dismissedAt?: Date; snoozedUntil?: Date | null; fingerprint?: string | null },
) {
const now = new Date();
const dismissedAt = input.dismissedAt ?? now;
const snoozedUntil = input.kind === "snooze" ? input.snoozedUntil ?? null : null;
// A re-hide without a fingerprint clears the old one, so the row never
// compares against content the user did not see.
const fingerprint = input.fingerprint ?? null;
const [row] = await db
.insert(inboxDismissals)
.values({
@@ -22,6 +25,7 @@ export function inboxDismissalService(db: Db) {
kind: input.kind,
dismissedAt,
snoozedUntil,
fingerprint,
updatedAt: now,
})
.onConflictDoUpdate({
@@ -30,6 +34,7 @@ export function inboxDismissalService(db: Db) {
kind: input.kind,
dismissedAt,
snoozedUntil,
fingerprint,
updatedAt: now,
},
})
@@ -50,7 +55,8 @@ export function inboxDismissalService(db: Db) {
userId: string,
itemKey: string,
dismissedAt: Date = new Date(),
) => upsert(companyId, userId, itemKey, { kind: "dismiss", dismissedAt }),
fingerprint: string | null = null,
) => upsert(companyId, userId, itemKey, { kind: "dismiss", dismissedAt, fingerprint }),
snooze: async (
companyId: string,
@@ -58,7 +64,8 @@ export function inboxDismissalService(db: Db) {
itemKey: string,
snoozedUntil: Date,
dismissedAt: Date = new Date(),
) => upsert(companyId, userId, itemKey, { kind: "snooze", dismissedAt, snoozedUntil }),
fingerprint: string | null = null,
) => upsert(companyId, userId, itemKey, { kind: "snooze", dismissedAt, snoozedUntil, fingerprint }),
restore: async (companyId: string, userId: string, itemKey: string) => {
const [row] = await db
+1
View File
@@ -43,6 +43,7 @@ export {
type IssueListOptions,
} from "./issues.js";
export { issueThreadInteractionService } from "./issue-thread-interactions.js";
export { expirePendingInteractionsOnClosedIssues } from "./closed-issue-interaction-sweep.js";
export { githubConnectionEventService, type GitHubConnectionEventPollResult } from "./github-connection-events.js";
export {
assertIssueReviewVerdictActorAllowed,
+12 -4
View File
@@ -1,4 +1,5 @@
import { sql, type SQL } from "drizzle-orm";
import type { AnyPgColumn } from "drizzle-orm/pg-core";
import { activityLog, chatConversations, chatMessageLinks, issueComments, issues, issueThreadInteractions } from "@paperclipai/db";
import { HUMAN_TASK_ORIGIN_KINDS } from "@paperclipai/shared";
import { activeIssueInteractionCondition } from "./issue-question-context.js";
@@ -71,11 +72,18 @@ export function automaticReadRecoveryCleanupCondition() {
)`;
}
export function humanCreatedIssueCondition() {
/**
* A task a person created by hand. `table` is `issues` or an alias of it, for a
* query that reads the same rule on another row (PAP-768: the instigator walk
* of the personal decision history).
*/
export function humanCreatedIssueCondition(
table: { createdByAgentId: AnyPgColumn; createdByUserId: AnyPgColumn; originKind: AnyPgColumn } = issues,
) {
return sql<boolean>`(
${issues.createdByAgentId} IS NULL
AND ${issues.createdByUserId} IS NOT NULL
AND ${issues.originKind} IN (${sql.join(HUMAN_TASK_ORIGIN_KINDS.map((kind) => sql`${kind}`), sql`, `)})
${table.createdByAgentId} IS NULL
AND ${table.createdByUserId} IS NOT NULL
AND ${table.originKind} IN (${sql.join(HUMAN_TASK_ORIGIN_KINDS.map((kind) => sql`${kind}`), sql`, `)})
)`;
}
+13 -4
View File
@@ -9,15 +9,24 @@ export function ordinaryQuestionCondition() {
and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization']))`;
}
/** Deferring conversation input cannot authorize an action or a plan. */
export function deferredInteractionCondition() {
return sql<boolean>`(${issueThreadInteractions.dismissedAt} is not null
and ${issueThreadInteractions.kind} in ('ask_user_questions', 'request_confirmation', 'request_checkbox_confirmation', 'request_item_verdicts', 'suggest_tasks')
/**
* Conversation input that a person may defer. Everything else is a governed
* request (an approval-bearing action, credential, connection, governed clamp
* or document target) that keeps its gate until someone answers it.
*/
export function deferrableInteractionCondition() {
return sql<boolean>`(${issueThreadInteractions.kind} in ('ask_user_questions', 'request_confirmation', 'request_checkbox_confirmation', 'request_item_verdicts', 'suggest_tasks')
and ${issueThreadInteractions.effectiveResolverPolicySource} = 'requested'
and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization'])
and coalesce(${issueThreadInteractions.payload}->'target'->>'type', '') <> 'issue_document')`;
}
/** Deferring conversation input cannot authorize an action or a plan. */
export function deferredInteractionCondition() {
return sql<boolean>`(${issueThreadInteractions.dismissedAt} is not null
and ${deferrableInteractionCondition()})`;
}
/** Historical questions remain answerable, including after task completion. */
export function historicalQuestionCondition() {
return sql`(${ordinaryQuestionCondition()} and (${deferredInteractionCondition()} or exists (
@@ -834,6 +834,57 @@ function isTerminalIssueStatus(status: string) {
return status === "done" || status === "cancelled";
}
/**
* Throws 422 unless `userId` is a person who may answer requests on this task.
* Interaction create (an explicit addressee) and attention transfer ("Route to
* @x") both use it, so a card never goes to someone who cannot answer it.
*/
export async function assertInteractionAddresseeUserAvailable(
db: Db,
issue: { id: string; companyId: string },
issueRow: Record<string, unknown> | undefined,
userId: string,
) {
const [user] = await db.select({ id: authUsers.id }).from(authUsers)
.where(eq(authUsers.id, userId));
const cloudManaged = isCloudManagedInstance();
// No-login installs have an implicit board, which need not have an
// auth row. Never infer this authority in authenticated/Cloud mode.
const localImplicit = userId === "local-board"
&& !cloudManaged && resolveDeploymentMode() === "local_trusted";
// Use the normal board mutation policy, including viewer restrictions,
// local/instance-admin eligibility and Cloud's no-stale-admin rule.
const decision = user || localImplicit ? await authorizationService(db).decide({
actor: {
type: "board",
userId,
source: localImplicit ? "local_implicit" : cloudManaged ? "cloud_tenant" : "session",
},
action: "issue:mutate",
resource: { type: "issue", companyId: issue.companyId, issueId: issue.id, ...issueRow },
}) : null;
if (!decision?.allowed) {
throw unprocessable("addresseeUserId must identify a user authorized to respond in this company", {
code: "interaction_addressee_user_unavailable",
});
}
}
/** Routing changes the resolver addressee. Call under the task and interaction
* row locks, and validate the proposed recipient with the resolution owner's
* canonical audience and review-policy checks before changing that field. */
export async function assertInteractionRoutingRecipientAllowed(
db: Db,
issue: IssueResolutionContext,
interaction: IssueThreadInteractionRow,
userId: string,
) {
await assertInteractionAddresseeUserAvailable(db, issue, issue, userId);
await assertRequestConfirmationResolutionAllowedUnderLock(db, issue, {
...interaction, addresseeUserId: userId, addresseeAgentId: null,
}, { userId });
}
function interactionNotFoundError() {
return notFound("Interaction not found", { code: "interaction_not_found" });
}
@@ -4004,29 +4055,7 @@ export function issueThreadInteractionService(
throw conflict("Cannot create an interaction on a closed issue");
}
if (data.addresseeUserId) {
const [user] = await tx.select({ id: authUsers.id }).from(authUsers)
.where(eq(authUsers.id, data.addresseeUserId));
const cloudManaged = isCloudManagedInstance();
// No-login installs have an implicit board, which need not have an
// auth row. Never infer this authority in authenticated/Cloud mode.
const localImplicit = data.addresseeUserId === "local-board"
&& !cloudManaged && resolveDeploymentMode() === "local_trusted";
// Use the normal board mutation policy, including viewer restrictions,
// local/instance-admin eligibility and Cloud's no-stale-admin rule.
const decision = user || localImplicit ? await authorizationService(tx).decide({
actor: {
type: "board",
userId: data.addresseeUserId,
source: localImplicit ? "local_implicit" : cloudManaged ? "cloud_tenant" : "session",
},
action: "issue:mutate",
resource: { type: "issue", companyId: issue.companyId, issueId: issue.id, ...issueRow },
}) : null;
if (!decision?.allowed) {
throw unprocessable("addresseeUserId must identify a user authorized to respond in this company", {
code: "interaction_addressee_user_unavailable",
});
}
await assertInteractionAddresseeUserAvailable(tx as unknown as Db, issue, issueRow, data.addresseeUserId);
}
if (
data.kind === "ask_user_questions" &&
@@ -5461,13 +5490,22 @@ export function issueThreadInteractionService(
},
withdrawInteraction: async (
issue: { id: string; companyId: string },
issue: { id: string; companyId: string; status?: string },
interactionId: string,
input: WithdrawIssueThreadInteraction,
actor: InteractionActor,
mutationOptions: InteractionResolutionMutationOptions = {},
mutationOptions: InteractionResolutionMutationOptions & {
/**
* Let a person withdraw a card that outlived its closed task (PAP-749
* plan §2, Rule 10). This is cleanup only: a closed task is never woken.
*/
allowClosedIssueForHuman?: boolean;
} = {},
) => {
assertIssueOpenForInteractionResolution(issue);
const humanActor = Boolean(actor.userId) && !actor.agentId && !actor.runId && !actor.systemId;
if (!(mutationOptions.allowClosedIssueForHuman && humanActor)) {
assertIssueOpenForInteractionResolution(issue);
}
const data = withdrawIssueThreadInteractionSchema.parse(input);
const current = await db
.select()
@@ -5495,6 +5533,19 @@ export function issueThreadInteractionService(
// request must not outlive a withdrawn card.
const updated = await db.transaction(async (tx) => {
await assertInteractionRunWriteAllowed(tx as unknown as Db, issue, actor, [JSON.stringify(input)]);
const [lockedIssue] = await tx.select({
id: issues.id, companyId: issues.companyId, status: issues.status,
reviewPolicy: issues.reviewPolicy, createdByAgentId: issues.createdByAgentId, createdByUserId: issues.createdByUserId,
}).from(issues).where(and(eq(issues.id, issue.id), eq(issues.companyId, issue.companyId))).for("update");
if (!lockedIssue) throw notFound("Issue not found");
if (!(mutationOptions.allowClosedIssueForHuman && humanActor)) assertIssueOpenForInteractionResolution(lockedIssue);
if (lockedIssue.status === "in_review" && isRequestConfirmationLikeKind(current.kind)
&& await isIssueReviewVerdictInteraction(tx as unknown as Db, { issue: lockedIssue, interaction: current })) {
const verdictActor = actor.agentId ? { type: "agent" as const, id: actor.agentId }
: actor.userId ? { type: "user" as const, id: actor.userId } : null;
if (!verdictActor) throw forbidden("A review withdrawal requires an authenticated agent or user");
await assertIssueReviewVerdictActorAllowed(tx as unknown as Db, { issue: lockedIssue, actor: verdictActor });
}
await notifyChatConfirmationResolution(tx, current);
if (["ask_user_questions", "request_confirmation"].includes(current.kind)) await notifyChatRunMilestones(tx, current);
else await notifyIssueReviewState(tx, current);
+19 -1
View File
@@ -3047,7 +3047,8 @@ function unreadForUserCondition(companyId: string, userId: string) {
OR ${issueComments.authorUserId} <> ${userId}
)
AND ${issueComments.createdAt} > ${myLastTouchAt}
) OR ${pendingUserRequestCondition(companyId, userId, myLastRequestReadAt)})
) OR ${pendingUserRequestCondition(companyId, userId, myLastRequestReadAt)}
OR ${withdrawnForUserCondition(companyId, userId, myLastRequestReadAt)})
)
`;
}
@@ -3082,6 +3083,23 @@ function mineParticipationIssueIds(db: Db, companyId: string, userId: string) {
return db.selectDistinct({ id: participationSources.id }).from(participationSources).as("mine_participants");
}
/**
* A different person withdrew a request on this task that was for this user
* after they last read it (PAP-749 plan §6, Rule 12): the task shows unread in
* their Mine list. Reads the receipt on the activity entry; no extra state.
*/
function withdrawnForUserCondition(companyId: string, userId: string, readAt: SQL) {
return sql<boolean>`EXISTS (
SELECT 1
FROM ${activityLog}
WHERE ${activityLog.companyId} = ${companyId}
AND (${activityLog.details} ->> 'handledForUserId') = ${userId}
AND ${activityLog.details} -> 'receipt' ->> 'outcome' = 'withdrawn'
AND ${activityLog.details} -> 'receipt' ->> 'issueId' = ${issues.id}::text
AND ${activityLog.createdAt} > ${readAt}
)`;
}
function inboxVisibleForUserCondition(companyId: string, userId: string) {
return sql<boolean>`
NOT EXISTS (