Files
PaperClipAI/server/src/routes/approvals.ts
T
8818402e7a 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>
2026-11-11 17:49:39 -08:00

736 lines
28 KiB
TypeScript

import { Router, type Request } from "express";
import { eq } from "drizzle-orm";
import { heartbeatRuns, type Db } from "@paperclipai/db";
import {
addApprovalCommentSchema,
cancelApprovalSchema,
createApprovalSchema,
requestApprovalRevisionSchema,
resolveApprovalSchema,
resubmitApprovalSchema,
} from "@paperclipai/shared";
import { notFound, unprocessable } from "../errors.js";
import { resolvableApprovalStatuses } from "../lib/approval-records.js";
import { attentionAlreadyClosedError } from "../services/attention-already-closed.js";
import { attentionHandledDetails, attentionHandledFor, type AttentionHandledFor } from "../services/attention-receipts.js";
import { validate } from "../middleware/validate.js";
import { logger } from "../middleware/logger.js";
import {
approvalService,
accessService,
heartbeatService,
issueApprovalService,
logActivity,
secretService,
} from "../services/index.js";
import { assertBoard, assertCompanyAccess, getAccessibleResource, getActorInfo, hasCompanyAccess } from "./authz.js";
import { redactEventPayload } from "../redaction.js";
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
import { issueService } from "../services/issues.js";
import { approvalReadSqlCondition, canActorReadApproval } from "../services/authorization.js";
import { REVIEW_PATH_RECOVERY_INSTRUCTION } from "../services/recovery/review-path-recovery.js";
function redactApprovalPayload<T extends { payload: Record<string, unknown> }>(approval: T): T {
return {
...approval,
payload: redactEventPayload(approval.payload) ?? {},
};
}
function isStatusOnlyRecoveryContext(contextSnapshot: unknown) {
if (!contextSnapshot || typeof contextSnapshot !== "object" || Array.isArray(contextSnapshot)) return false;
const context = contextSnapshot as Record<string, unknown>;
return context.recoveryIntent === "status_only" &&
context.allowDeliverableWork === false &&
context.allowDocumentUpdates === false &&
context.resumeRequiresNormalModel === true;
}
/**
* Review-path wakes after an approval leaves `pending`: a linked task in review
* may have no other waiting path left, so its assignee is woken to choose one.
* Approve, reject and cancel share these.
*/
function approvalReviewPathWakes(db: Db, heartbeat: ReturnType<typeof heartbeatService>) {
const issueApprovalsSvc = issueApprovalService(db);
const issuesSvc = issueService(db);
async function lostReviewPathIssueIds(
companyId: string,
linkedIssues: Awaited<ReturnType<typeof issueApprovalsSvc.listIssuesForApproval>>,
) {
const attention = await issuesSvc.listReviewAttention(companyId, linkedIssues);
return new Set(linkedIssues
.filter((issue) => attention.get(issue.id)?.state === "stalled")
.map((issue) => issue.id));
}
function approvalReviewPathContext(approvalId: string) {
return {
reviewPathLost: true,
reviewPathConsumedRef: approvalId,
reviewPathInstruction: REVIEW_PATH_RECOVERY_INSTRUCTION,
};
}
async function queueAdditionalApprovalReviewPathWakes(input: {
approvalId: string;
approvalStatus: string;
companyId: string;
linkedIssues: Awaited<ReturnType<typeof issueApprovalsSvc.listIssuesForApproval>>;
lostIssueIds: Set<string>;
alreadyWoken?: { agentId: string; issueId: string } | null;
requestedByUserId: string;
}) {
for (const issue of input.linkedIssues) {
if (!input.lostIssueIds.has(issue.id) || !issue.assigneeAgentId) continue;
if (
input.alreadyWoken?.agentId === issue.assigneeAgentId
&& input.alreadyWoken.issueId === issue.id
) continue;
const wakeReason = `approval_${input.approvalStatus}`;
try {
const wakeRun = await heartbeat.wakeup(issue.assigneeAgentId, {
source: "automation",
triggerDetail: "system",
reason: wakeReason,
idempotencyKey: `approval-review-path:${input.approvalId}:${issue.id}:${input.approvalStatus}`,
payload: {
approvalId: input.approvalId,
approvalStatus: input.approvalStatus,
issueId: issue.id,
...approvalReviewPathContext(input.approvalId),
},
requestedByActorType: "user",
requestedByActorId: input.requestedByUserId,
contextSnapshot: {
source: `approval.${input.approvalStatus}`,
approvalId: input.approvalId,
approvalStatus: input.approvalStatus,
issueId: issue.id,
taskId: issue.id,
wakeReason,
...approvalReviewPathContext(input.approvalId),
},
});
await logActivity(db, {
companyId: input.companyId,
actorType: "user",
actorId: input.requestedByUserId,
action: "approval.review_path_wakeup_queued",
entityType: "approval",
entityId: input.approvalId,
details: {
approvalStatus: input.approvalStatus,
issueId: issue.id,
assigneeAgentId: issue.assigneeAgentId,
wakeRunId: wakeRun?.id ?? null,
},
});
} catch (err) {
logger.warn(
{ err, approvalId: input.approvalId, issueId: issue.id, agentId: issue.assigneeAgentId },
"failed to queue review-path wake after approval resolution",
);
await logActivity(db, {
companyId: input.companyId,
actorType: "user",
actorId: input.requestedByUserId,
action: "approval.review_path_wakeup_failed",
entityType: "approval",
entityId: input.approvalId,
details: {
approvalStatus: input.approvalStatus,
issueId: issue.id,
assigneeAgentId: issue.assigneeAgentId,
error: err instanceof Error ? err.message : String(err),
},
});
}
}
}
return { approvalReviewPathContext, lostReviewPathIssueIds, queueAdditionalApprovalReviewPathWakes };
}
/**
* Withdraw an open approval because it is out of date (PAP-749 plan §2, Rule
* 6). It is never an approval: the gate stays closed. It records who withdrew
* it and why, logs `approval.cancelled`, and tells the requesting agent. The
* approval route and the attention close endpoint share this one path. Callers
* authorize a board user first.
*/
export async function cancelApprovalAndNotify(input: {
db: Db;
heartbeat: ReturnType<typeof heartbeatService>;
approvalId: string;
userId: string;
reason?: string | null;
/** Who the card was for, read before the cancel (PAP-749 plan §6). Omitted: read here. */
handledFor?: AttentionHandledFor | null;
}) {
const { db, heartbeat, userId } = input;
const svc = approvalService(db);
const existing = await svc.getById(input.approvalId);
if (!existing) throw notFound("Approval not found");
if (existing.type === "hire_agent") {
// Cancelling a hire would leave the pending agent with no decision.
throw unprocessable("Reject this hire request instead of withdrawing it.", { code: "approval_cancel_unsupported" });
}
const alreadyClosed = (approval: typeof existing) => attentionAlreadyClosedError({
sourceKind: "approval",
sourceId: approval.id,
status: approval.status,
resolvedByUserId: approval.decidedByUserId,
resolvedAt: approval.decidedAt,
});
if (!(resolvableApprovalStatuses as readonly string[]).includes(existing.status)) throw alreadyClosed(existing);
const reason = input.reason?.trim() || null;
const handledFor = input.handledFor !== undefined
? input.handledFor
: await attentionHandledFor(db, existing.companyId, { sourceKind: "approval", sourceId: existing.id }, userId);
const approval = await svc.cancel(existing.id, reason, { cancelledByUserId: userId });
if (!approval) {
// A different person resolved it between the read and the write.
throw alreadyClosed((await svc.getById(existing.id)) ?? existing);
}
const reviewPath = approvalReviewPathWakes(db, heartbeat);
const linkedIssues = await issueApprovalService(db).listIssuesForApproval(approval.id);
const linkedIssueIds = linkedIssues.map((issue) => issue.id);
const primaryIssueId = linkedIssueIds[0] ?? null;
const lostReviewIssueIds = await reviewPath.lostReviewPathIssueIds(approval.companyId, linkedIssues);
await logActivity(db, {
companyId: approval.companyId,
actorType: "user",
actorId: userId,
action: "approval.cancelled",
entityType: "approval",
entityId: approval.id,
details: {
type: approval.type,
reason,
requestedByAgentId: approval.requestedByAgentId,
linkedIssueIds,
...attentionHandledDetails(handledFor, "withdrawn", { reason }),
},
});
let primaryReviewPathWakeCovered = false;
if (approval.requestedByAgentId) {
const primaryReviewPathContext = primaryIssueId && lostReviewIssueIds.has(primaryIssueId)
? reviewPath.approvalReviewPathContext(approval.id)
: null;
try {
const wakeRun = await heartbeat.wakeup(approval.requestedByAgentId, {
source: "automation",
triggerDetail: "system",
reason: "approval_cancelled",
payload: {
approvalId: approval.id,
approvalStatus: approval.status,
reason,
issueId: primaryIssueId,
issueIds: linkedIssueIds,
...(primaryReviewPathContext ?? {}),
},
requestedByActorType: "user",
requestedByActorId: userId,
contextSnapshot: {
source: "approval.cancelled",
approvalId: approval.id,
approvalStatus: approval.status,
issueId: primaryIssueId,
issueIds: linkedIssueIds,
taskId: primaryIssueId,
wakeReason: "approval_cancelled",
...(primaryReviewPathContext ?? {}),
},
});
primaryReviewPathWakeCovered = Boolean(wakeRun && primaryReviewPathContext);
await logActivity(db, {
companyId: approval.companyId,
actorType: "user",
actorId: userId,
action: "approval.requester_wakeup_queued",
entityType: "approval",
entityId: approval.id,
details: { requesterAgentId: approval.requestedByAgentId, wakeRunId: wakeRun?.id ?? null, linkedIssueIds },
});
} catch (err) {
logger.warn(
{ err, approvalId: approval.id, requestedByAgentId: approval.requestedByAgentId },
"failed to queue requester wakeup after approval cancel",
);
await logActivity(db, {
companyId: approval.companyId,
actorType: "user",
actorId: userId,
action: "approval.requester_wakeup_failed",
entityType: "approval",
entityId: approval.id,
details: {
requesterAgentId: approval.requestedByAgentId,
linkedIssueIds,
error: err instanceof Error ? err.message : String(err),
},
});
}
}
await reviewPath.queueAdditionalApprovalReviewPathWakes({
approvalId: approval.id,
approvalStatus: approval.status,
companyId: approval.companyId,
linkedIssues,
lostIssueIds: lostReviewIssueIds,
alreadyWoken: primaryReviewPathWakeCovered && approval.requestedByAgentId && primaryIssueId
? { agentId: approval.requestedByAgentId, issueId: primaryIssueId }
: null,
requestedByUserId: userId,
});
return { approval, issueId: primaryIssueId };
}
export function approvalRoutes(
db: Db,
options: { pluginWorkerManager?: PluginWorkerManager } = {},
) {
const router = Router();
router.param("id", async (req, res, next, id) => {
try {
if (!(await canActorReadApproval(db, req.actor, id))) {
res.status(404).json({ error: "Approval not found" });
return;
}
next();
} catch (error) { next(error); }
});
const svc = approvalService(db);
const access = accessService(db);
const heartbeat = heartbeatService(db, {
pluginWorkerManager: options.pluginWorkerManager,
});
const issueApprovalsSvc = issueApprovalService(db);
const secretsSvc = secretService(db);
const strictSecretsMode = process.env.PAPERCLIP_SECRETS_STRICT_MODE === "true";
const { approvalReviewPathContext, lostReviewPathIssueIds, queueAdditionalApprovalReviewPathWakes } =
approvalReviewPathWakes(db, heartbeat);
/** Who an approval card is for, read before a person decides it (PAP-749 plan §6). */
async function approvalHandledFor(id: string, userId: string | null | undefined) {
const approval = await svc.getById(id);
return approval
? attentionHandledFor(db, approval.companyId, { sourceKind: "approval", sourceId: id }, userId)
: null;
}
async function requireApprovalAccess(req: Request, id: string) {
const approval = await svc.getById(id);
if (!approval || !hasCompanyAccess(req, approval.companyId)) {
return null;
}
assertCompanyAccess(req, approval.companyId);
return approval;
}
async function assertApprovalAccessAllowed(req: Request, res: any, companyId: string) {
const decision = await access.decide({
actor: req.actor,
action: "company_scope:read",
resource: { type: "company", companyId },
});
if (decision.allowed) return true;
res.status(403).json({ error: "Approvals are outside this actor's authorization boundary" });
return false;
}
async function assertApprovalMutationAllowedByRunContext(req: Request, res: any, companyId: string) {
if (req.actor.type !== "agent") return true;
const runId = req.actor.runId?.trim();
if (!runId || !req.actor.agentId) return true;
const run = await db
.select({
id: heartbeatRuns.id,
companyId: heartbeatRuns.companyId,
agentId: heartbeatRuns.agentId,
contextSnapshot: heartbeatRuns.contextSnapshot,
})
.from(heartbeatRuns)
.where(eq(heartbeatRuns.id, runId))
.then((rows) => rows[0] ?? null);
if (!run || run.companyId !== companyId || run.agentId !== req.actor.agentId) return true;
if (!isStatusOnlyRecoveryContext(run.contextSnapshot)) return true;
res.status(403).json({
error: "Status-only recovery runs cannot create or modify approvals",
details: {
companyId,
runId: run.id,
recoveryIntent: "status_only",
resumeRequiresNormalModel: true,
},
});
return false;
}
router.get("/companies/:companyId/approvals", async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
if (!(await assertApprovalAccessAllowed(req, res, companyId))) return;
const status = req.query.status as string | undefined;
const result = await svc.list(companyId, status, await approvalReadSqlCondition(db, req.actor));
res.json(result.map((approval) => redactApprovalPayload(approval)));
});
router.get("/approvals/:id", async (req, res) => {
const id = req.params.id as string;
const approval = await getAccessibleResource(req, res, svc.getById(id), "Approval not found");
if (!approval) return;
if (!(await assertApprovalAccessAllowed(req, res, approval.companyId))) return;
res.json(redactApprovalPayload(approval));
});
router.post("/companies/:companyId/approvals", validate(createApprovalSchema), async (req, res) => {
const companyId = req.params.companyId as string;
assertCompanyAccess(req, companyId);
if (!(await assertApprovalAccessAllowed(req, res, companyId))) return;
if (!(await assertApprovalMutationAllowedByRunContext(req, res, companyId))) return;
const rawIssueIds = req.body.issueIds;
const issueIds = Array.isArray(rawIssueIds)
? rawIssueIds.filter((value: unknown): value is string => typeof value === "string")
: [];
const uniqueIssueIds = Array.from(new Set(issueIds));
const { issueIds: _issueIds, ...approvalInput } = req.body;
const normalizedPayload =
approvalInput.type === "hire_agent"
? await secretsSvc.normalizeHireApprovalPayloadForPersistence(
companyId,
approvalInput.payload,
{ strictMode: strictSecretsMode },
)
: approvalInput.payload;
const actor = getActorInfo(req);
const approval = await svc.create(companyId, {
...approvalInput,
payload: normalizedPayload,
requestedByUserId: actor.actorType === "user" ? actor.actorId : null,
requestedByAgentId:
approvalInput.requestedByAgentId ?? (actor.actorType === "agent" ? actor.actorId : null),
status: "pending",
decisionNote: null,
decidedByUserId: null,
decidedAt: null,
updatedAt: new Date(),
});
if (uniqueIssueIds.length > 0) {
await issueApprovalsSvc.linkManyForApproval(approval.id, uniqueIssueIds, {
agentId: actor.agentId,
userId: actor.actorType === "user" ? actor.actorId : null,
});
}
await logActivity(db, {
companyId,
actorType: actor.actorType,
actorId: actor.actorId,
agentId: actor.agentId,
action: "approval.created",
entityType: "approval",
entityId: approval.id,
details: { type: approval.type, issueIds: uniqueIssueIds },
});
res.status(201).json(redactApprovalPayload(approval));
});
router.get("/approvals/:id/issues", async (req, res) => {
const id = req.params.id as string;
const approval = await getAccessibleResource(req, res, svc.getById(id), "Approval not found");
if (!approval) return;
if (!(await assertApprovalAccessAllowed(req, res, approval.companyId))) return;
const issues = await issueApprovalsSvc.listIssuesForApproval(id);
res.json(issues);
});
router.post("/approvals/:id/approve", validate(resolveApprovalSchema), async (req, res) => {
assertBoard(req);
const id = req.params.id as string;
if (!(await requireApprovalAccess(req, id))) {
res.status(404).json({ error: "Approval not found" });
return;
}
const decidedByUserId = req.actor.userId ?? "board";
// Who the card was for, read before the decision (PAP-749 plan §6).
const handledFor = await approvalHandledFor(id, req.actor.userId);
const { approval, applied } = await svc.approve(id, decidedByUserId, req.body.decisionNote);
if (applied) {
const linkedIssues = await issueApprovalsSvc.listIssuesForApproval(approval.id);
const linkedIssueIds = linkedIssues.map((issue) => issue.id);
const primaryIssueId = linkedIssueIds[0] ?? null;
const lostReviewIssueIds = await lostReviewPathIssueIds(approval.companyId, linkedIssues);
const primaryReviewPathContext = primaryIssueId && lostReviewIssueIds.has(primaryIssueId)
? approvalReviewPathContext(approval.id)
: null;
await logActivity(db, {
companyId: approval.companyId,
actorType: "user",
actorId: req.actor.userId ?? "board",
action: "approval.approved",
entityType: "approval",
entityId: approval.id,
details: {
type: approval.type,
requestedByAgentId: approval.requestedByAgentId,
linkedIssueIds,
...attentionHandledDetails(handledFor, "approved"),
},
});
let primaryReviewPathWakeCovered = false;
if (approval.requestedByAgentId) {
try {
const wakeRun = await heartbeat.wakeup(approval.requestedByAgentId, {
source: "automation",
triggerDetail: "system",
reason: "approval_approved",
payload: {
approvalId: approval.id,
approvalStatus: approval.status,
issueId: primaryIssueId,
issueIds: linkedIssueIds,
...(primaryReviewPathContext ?? {}),
},
requestedByActorType: "user",
requestedByActorId: req.actor.userId ?? "board",
contextSnapshot: {
source: "approval.approved",
approvalId: approval.id,
approvalStatus: approval.status,
issueId: primaryIssueId,
issueIds: linkedIssueIds,
taskId: primaryIssueId,
wakeReason: "approval_approved",
...(primaryReviewPathContext ?? {}),
},
});
primaryReviewPathWakeCovered = Boolean(wakeRun && primaryReviewPathContext);
await logActivity(db, {
companyId: approval.companyId,
actorType: "user",
actorId: req.actor.userId ?? "board",
action: "approval.requester_wakeup_queued",
entityType: "approval",
entityId: approval.id,
details: {
requesterAgentId: approval.requestedByAgentId,
wakeRunId: wakeRun?.id ?? null,
linkedIssueIds,
},
});
} catch (err) {
logger.warn(
{
err,
approvalId: approval.id,
requestedByAgentId: approval.requestedByAgentId,
},
"failed to queue requester wakeup after approval",
);
await logActivity(db, {
companyId: approval.companyId,
actorType: "user",
actorId: req.actor.userId ?? "board",
action: "approval.requester_wakeup_failed",
entityType: "approval",
entityId: approval.id,
details: {
requesterAgentId: approval.requestedByAgentId,
linkedIssueIds,
error: err instanceof Error ? err.message : String(err),
},
});
}
}
await queueAdditionalApprovalReviewPathWakes({
approvalId: approval.id,
approvalStatus: approval.status,
companyId: approval.companyId,
linkedIssues,
lostIssueIds: lostReviewIssueIds,
alreadyWoken: primaryReviewPathWakeCovered && approval.requestedByAgentId && primaryIssueId
? { agentId: approval.requestedByAgentId, issueId: primaryIssueId }
: null,
requestedByUserId: req.actor.userId ?? "board",
});
}
res.json(redactApprovalPayload(approval));
});
router.post("/approvals/:id/reject", validate(resolveApprovalSchema), async (req, res) => {
assertBoard(req);
const id = req.params.id as string;
if (!(await requireApprovalAccess(req, id))) {
res.status(404).json({ error: "Approval not found" });
return;
}
const decidedByUserId = req.actor.userId ?? "board";
const handledFor = await approvalHandledFor(id, req.actor.userId);
const { approval, applied } = await svc.reject(id, decidedByUserId, req.body.decisionNote);
if (applied) {
const linkedIssues = await issueApprovalsSvc.listIssuesForApproval(approval.id);
const lostReviewIssueIds = await lostReviewPathIssueIds(approval.companyId, linkedIssues);
await logActivity(db, {
companyId: approval.companyId,
actorType: "user",
actorId: req.actor.userId ?? "board",
action: "approval.rejected",
entityType: "approval",
entityId: approval.id,
details: { type: approval.type, ...attentionHandledDetails(handledFor, "rejected", { reason: req.body.decisionNote }) },
});
await queueAdditionalApprovalReviewPathWakes({
approvalId: approval.id,
approvalStatus: approval.status,
companyId: approval.companyId,
linkedIssues,
lostIssueIds: lostReviewIssueIds,
requestedByUserId: req.actor.userId ?? "board",
});
}
res.json(redactApprovalPayload(approval));
});
router.post(
"/approvals/:id/request-revision",
validate(requestApprovalRevisionSchema),
async (req, res) => {
assertBoard(req);
const id = req.params.id as string;
if (!(await requireApprovalAccess(req, id))) {
res.status(404).json({ error: "Approval not found" });
return;
}
const decidedByUserId = req.actor.userId ?? "board";
const handledFor = await approvalHandledFor(id, req.actor.userId);
const approval = await svc.requestRevision(id, decidedByUserId, req.body.decisionNote);
await logActivity(db, {
companyId: approval.companyId,
actorType: "user",
actorId: req.actor.userId ?? "board",
action: "approval.revision_requested",
entityType: "approval",
entityId: approval.id,
details: {
type: approval.type,
...attentionHandledDetails(handledFor, "revision_requested", { reason: req.body.decisionNote }),
},
});
res.json(redactApprovalPayload(approval));
},
);
// Withdraw an out-of-date approval (PAP-749 plan §2, Rule 6). Board users
// only; it never approves. 409 when it was already resolved.
router.post("/approvals/:id/cancel", validate(cancelApprovalSchema), async (req, res) => {
assertBoard(req);
const id = req.params.id as string;
if (!(await requireApprovalAccess(req, id))) {
res.status(404).json({ error: "Approval not found" });
return;
}
if (!req.actor.userId) {
res.status(403).json({ error: "Board user context required" });
return;
}
const { approval } = await cancelApprovalAndNotify({
db, heartbeat, approvalId: id, userId: req.actor.userId, reason: req.body.reason,
});
res.json(redactApprovalPayload(approval));
});
router.post("/approvals/:id/resubmit", validate(resubmitApprovalSchema), async (req, res) => {
const id = req.params.id as string;
const existing = await getAccessibleResource(req, res, svc.getById(id), "Approval not found");
if (!existing) return;
if (!(await assertApprovalMutationAllowedByRunContext(req, res, existing.companyId))) return;
if (req.actor.type === "agent" && req.actor.agentId !== existing.requestedByAgentId) {
res.status(403).json({ error: "Only requesting agent can resubmit this approval" });
return;
}
const normalizedPayload = req.body.payload
? existing.type === "hire_agent"
? await secretsSvc.normalizeHireApprovalPayloadForPersistence(
existing.companyId,
req.body.payload,
{ strictMode: strictSecretsMode },
)
: req.body.payload
: undefined;
const approval = await svc.resubmit(id, normalizedPayload);
const actor = getActorInfo(req);
await logActivity(db, {
companyId: approval.companyId,
actorType: actor.actorType,
actorId: actor.actorId,
agentId: actor.agentId,
action: "approval.resubmitted",
entityType: "approval",
entityId: approval.id,
details: { type: approval.type },
});
res.json(redactApprovalPayload(approval));
});
router.get("/approvals/:id/comments", async (req, res) => {
const id = req.params.id as string;
const approval = await getAccessibleResource(req, res, svc.getById(id), "Approval not found");
if (!approval) return;
const comments = await svc.listComments(id);
res.json(comments);
});
router.post("/approvals/:id/comments", validate(addApprovalCommentSchema), async (req, res) => {
const id = req.params.id as string;
const approval = await getAccessibleResource(req, res, svc.getById(id), "Approval not found");
if (!approval) return;
if (!(await assertApprovalMutationAllowedByRunContext(req, res, approval.companyId))) return;
const actor = getActorInfo(req);
const comment = await svc.addComment(id, req.body.body, {
agentId: actor.agentId ?? undefined,
userId: actor.actorType === "user" ? actor.actorId : undefined,
});
await logActivity(db, {
companyId: approval.companyId,
actorType: actor.actorType,
actorId: actor.actorId,
agentId: actor.agentId,
action: "approval.comment_added",
entityType: "approval",
entityId: approval.id,
details: { commentId: comment.id },
});
res.status(201).json(comment);
});
return router;
}