Files
PaperClipAI/ui/src/lib/activity-format.ts
T
ad961227f5 feat(secrets): add user-specific runtime secrets (#8825)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agent runs often need provider credentials, API tokens, and other
environment-bound secrets.
> - Company-level secrets work for shared credentials, but they do not
model values that should differ by human operator.
> - Without a user-scoped model, a run can dispatch without knowing
whether the responsible human has supplied the needed value.
> - Paperclip also needs run attribution to make those user-scoped
runtime checks deterministic and auditable.
> - This pull request adds user-specific secret definitions, per-user
values, environment bindings, responsible-user attribution, and runtime
resolution gates.
> - The benefit is that teams can define the secret once, let each user
provide their own value, and block runs before dispatch when required
user secrets or active definitions are unavailable.

## Linked Issues or Issue Description

Refs #224
Refs #6057

This PR implements user-specific secret support as a core
secret-management capability rather than a one-off adapter setting. It
is related to existing public work on company secrets UI and runtime
secret refs, but is distinct because the value is owned by the
responsible user and resolved at run dispatch time.

Related PR search before opening found existing secrets work such as
#1550, #8256, #8614, #8634, and #8647; none of those add the full
user-secret definition/value/runtime gate covered here.

## What Changed

- Added user-secret definitions and per-user "My secrets" values,
keeping stored values out of access metadata.
- Added `user_secret_ref` environment bindings and UI affordances to
pick them alongside existing secret refs.
- Added responsible-user runtime resolution so user-secret refs resolve
against the human responsible for the run.
- Added pre-dispatch missing-secret gates so runs fail before adapter
dispatch when required user values are absent or definitions are
inactive.
- Added low-trust allowlist hardening for user-secret runtime access.
- Added issue, routine, run, and agent API key responsible-user
attribution and fail-closed dispatch behavior when attribution cannot be
resolved.
- Added denial-copy mapping so responsible-user authorization failures
surface as actionable run outcomes instead of opaque setup failures.
- Added OpenAPI documentation for the user-secret routes.
- Rebases cleanly on current `master`; migrations were renumbered
incrementally as `0128_user_specific_secrets`,
`0129_agent_api_key_responsible_user`, and
`0130_run_responsible_user_invariant` after upstream `0126`/`0127`
migrations.
- Removed previously committed local design screenshots so the PR
contains code/docs/tests only.

## Verification

- PASS: PR head `2527febd106bcf3ca264ca0da7fca491084192d6` is based on
`paperclipai/paperclip:master`.
- PASS: `git diff --check`
- PASS: `git diff --name-only public/master...HEAD | rg
'^(pnpm-lock\\.yaml|\\.github/workflows/|screenshots/)' || true`
produced no files.
- PASS: migration journal audit confirmed unique indexes through `130`
with tail entries `0126_issue_comment_derived_attribution`,
`0127_environment_custom_images_instance_scoped`,
`0128_user_specific_secrets`, `0129_agent_api_key_responsible_user`, and
`0130_run_responsible_user_invariant`.
- PASS: `pnpm --filter @paperclipai/ui typecheck`
- PASS: `pnpm --filter @paperclipai/server typecheck`
- PASS: `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/heartbeat-responsible-user-invariant.test.ts`
- PASS: `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/heartbeat-active-run-output-watchdog.test.ts
src/__tests__/heartbeat-stale-queue-invalidation.test.ts
src/__tests__/heartbeat-workspace-finalize-branch.test.ts
src/__tests__/issue-monitor-scheduler.test.ts`
- PASS: `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/heartbeat-comment-wake-batching.test.ts
src/__tests__/heartbeat-retry-scheduling.test.ts
src/__tests__/heartbeat-accepted-plan-workspace-refresh.test.ts
src/__tests__/heartbeat-plugin-environment.test.ts`
- PASS: `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/low-trust-red-team-routes.test.ts`
- PASS: `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/secrets-service.test.ts` (55 tests)
- PASS: `pnpm vitest run server/src/__tests__/secrets-routes.test.ts
server/src/__tests__/secrets-service.test.ts` (89 tests after final
Greptile cleanup fixes)
- PASS: `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/heartbeat-issue-liveness-escalation.test.ts` (17 tests
after the final rebase CI fix)
- PASS: focused server Vitest batches covering heartbeat recovery,
project env, plugin env, routines, low-trust, pipelines, monitors,
watchdog, and stale queue paths.
- PASS: GitHub checks are green on
`2527febd106bcf3ca264ca0da7fca491084192d6`, including Typecheck +
Release Registry, Build, General tests, serialized server suites, e2e,
Canary Dry Run, verify, security checks, and Greptile Review.
- PASS: Greptile Review completed successfully on
`2527febd106bcf3ca264ca0da7fca491084192d6` with Confidence Score 5/5,
and GraphQL review-thread audit returned zero unresolved non-outdated
threads.

## Risks

- Runtime behavior now depends on a run having a correct responsible
user; missing or incorrect responsibility assignment can block runs
before adapter dispatch.
- `user_secret_ref` bindings intentionally expose metadata without
values, but UI/API callers may need to handle the new binding kind
explicitly.
- External secret providers and IAM policies are not automatically
provisioned by this PR; operators still need to configure provider-side
access for non-local vaults.
- The PR is broad across db/shared/server/UI/runtime paths, so release
validation should include both API and UI secret workflows before merge.
- The migration renumbering is intentionally incremental after upstream
migrations; the branch migrations use guarded
column/table/index/constraint creation so users who tested the older
draft numbering should not hit duplicate DDL for the existing objects.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

OpenAI Codex, GPT-5-based coding agent (`gpt-5`), Codex local adapter
with shell/tool use and code execution. Context window and internal
reasoning mode are not exposed by the runtime.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 05:58:20 -05:00

400 lines
16 KiB
TypeScript

import type { Agent } from "@paperclipai/shared";
import type { CompanyUserProfile } from "./company-members";
type ActivityDetails = Record<string, unknown> | null | undefined;
type ActivityParticipant = {
type: "agent" | "user";
agentId?: string | null;
userId?: string | null;
};
type ActivityIssueReference = {
id?: string | null;
identifier?: string | null;
title?: string | null;
};
interface ActivityFormatOptions {
agentMap?: Map<string, Agent>;
userProfileMap?: Map<string, CompanyUserProfile>;
currentUserId?: string | null;
}
const ACTIVITY_ROW_VERBS: Record<string, string> = {
"issue.created": "created",
"issue.updated": "updated",
"issue.checked_out": "checked out",
"issue.released": "released",
"issue.comment_added": "commented on",
"issue.comment_cancelled": "cancelled a queued comment on",
"issue.comment_deleted": "deleted a comment on",
"issue.attachment_added": "attached file to",
"issue.attachment_removed": "removed attachment from",
"issue.document_created": "created document for",
"issue.document_updated": "updated document on",
"issue.document_locked": "locked document on",
"issue.document_unlocked": "unlocked document on",
"issue.document_deleted": "deleted document from",
"issue.monitor_scheduled": "scheduled monitor on",
"issue.monitor_triggered": "triggered monitor for",
"issue.monitor_cleared": "cleared monitor on",
"issue.monitor_skipped": "skipped monitor for",
"issue.monitor_exhausted": "exhausted monitor on",
"issue.monitor_recovery_wake_queued": "queued monitor recovery for",
"issue.monitor_recovery_issue_created": "created monitor recovery for",
"issue.monitor_escalated_to_board": "escalated monitor for",
"issue.commented": "commented on",
"issue.deleted": "deleted",
"issue.successful_run_handoff_required": "flagged missing next step on",
"issue.successful_run_handoff_resolved": "recorded next step chosen on",
"issue.successful_run_handoff_escalated": "escalated missing next step on",
"issue.accepted_plan_decomposition_updated": "updated accepted-plan decomposition on",
"issue.recovery_action_opened": "opened a recovery action on",
"issue.recovery_action_resolved": "resolved the recovery action on",
"issue.recovery_action_escalated": "escalated the recovery action on",
"agent.created": "created",
"agent.updated": "updated",
"agent.paused": "paused",
"agent.resumed": "resumed",
"agent.error_cleared": "cleared error on",
"agent.terminated": "terminated",
"agent.key_created": "created API key for",
"agent.budget_updated": "updated budget for",
"agent.runtime_session_reset": "reset session for",
"heartbeat.invoked": "invoked heartbeat for",
"heartbeat.cancelled": "cancelled heartbeat for",
"heartbeat.output_stale_source_resolved": "system-folded stale run on",
"heartbeat.output_stale_recovery_recursion_refused": "refused recovery-on-recovery for",
"approval.created": "requested approval",
"approval.approved": "approved",
"approval.rejected": "rejected",
"project.created": "created",
"project.updated": "updated",
"project.deleted": "deleted",
"goal.created": "created",
"goal.updated": "updated",
"goal.deleted": "deleted",
"cost.reported": "reported cost for",
"cost.recorded": "recorded cost for",
"company.created": "created company",
"company.updated": "updated company",
"company.archived": "archived",
"company.reactivated": "reactivated",
"company.budget_updated": "updated budget for",
};
const ISSUE_ACTIVITY_LABELS: Record<string, string> = {
"issue.created": "created the issue",
"issue.updated": "updated the issue",
"issue.checked_out": "checked out the issue",
"issue.released": "released the issue",
"issue.comment_added": "added a comment",
"issue.comment_cancelled": "cancelled a queued comment",
"issue.comment_deleted": "deleted a comment",
"issue.feedback_vote_saved": "saved feedback on an AI output",
"issue.attachment_added": "added an attachment",
"issue.attachment_removed": "removed an attachment",
"issue.document_created": "created a document",
"issue.document_updated": "updated a document",
"issue.document_locked": "locked a document",
"issue.document_unlocked": "unlocked a document",
"issue.document_deleted": "deleted a document",
"issue.monitor_scheduled": "scheduled a monitor",
"issue.monitor_triggered": "triggered a monitor",
"issue.monitor_cleared": "cleared a monitor",
"issue.monitor_skipped": "skipped a monitor",
"issue.monitor_exhausted": "exhausted a monitor",
"issue.monitor_recovery_wake_queued": "queued a monitor recovery wake",
"issue.monitor_recovery_issue_created": "created a monitor recovery issue",
"issue.monitor_escalated_to_board": "escalated a monitor to the board",
"issue.deleted": "deleted the issue",
"issue.successful_run_handoff_required": "Run finished without a clear next step",
"issue.successful_run_handoff_resolved": "Next step chosen",
"issue.successful_run_handoff_escalated": "Run finished without a next step - recovery escalated",
"issue.recovery_action_opened": "Opened a source-scoped recovery action",
"issue.recovery_action_resolved": "Resolved the recovery action",
"issue.recovery_action_escalated": "Escalated the recovery action",
"issue.accepted_plan_decomposition_updated": "updated the accepted-plan decomposition",
"agent.created": "created an agent",
"agent.updated": "updated the agent",
"agent.paused": "paused the agent",
"agent.resumed": "resumed the agent",
"agent.error_cleared": "cleared the agent error",
"agent.terminated": "terminated the agent",
"heartbeat.invoked": "invoked a heartbeat",
"heartbeat.cancelled": "cancelled a heartbeat",
"heartbeat.output_stale_source_resolved": "System folded a stale run",
"heartbeat.output_stale_recovery_recursion_refused": "Refused recovery-on-recovery escalation",
"approval.created": "requested approval",
"approval.approved": "approved",
"approval.rejected": "rejected",
};
function asRecord(value: unknown): Record<string, unknown> | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
return value as Record<string, unknown>;
}
function humanizeValue(value: unknown): string {
if (typeof value !== "string") return String(value ?? "none");
return value.replace(/_/g, " ");
}
function isActivityParticipant(value: unknown): value is ActivityParticipant {
const record = asRecord(value);
if (!record) return false;
return record.type === "agent" || record.type === "user";
}
function isActivityIssueReference(value: unknown): value is ActivityIssueReference {
return asRecord(value) !== null;
}
function readParticipants(details: ActivityDetails, key: string): ActivityParticipant[] {
const value = details?.[key];
if (!Array.isArray(value)) return [];
return value.filter(isActivityParticipant);
}
function readIssueReferences(details: ActivityDetails, key: string): ActivityIssueReference[] {
const value = details?.[key];
if (!Array.isArray(value)) return [];
return value.filter(isActivityIssueReference);
}
function formatUserLabel(userId: string | null | undefined, options: ActivityFormatOptions = {}): string {
if (!userId || userId === "local-board") return "Board";
if (options.currentUserId && userId === options.currentUserId) return "You";
const profile = options.userProfileMap?.get(userId);
if (profile) return profile.label;
return `user ${userId.slice(0, 5)}`;
}
function formatParticipantLabel(participant: ActivityParticipant, options: ActivityFormatOptions): string {
if (participant.type === "agent") {
const agentId = participant.agentId ?? "";
return options.agentMap?.get(agentId)?.name ?? "agent";
}
return formatUserLabel(participant.userId, options);
}
function formatIssueReferenceLabel(reference: ActivityIssueReference): string {
if (reference.identifier) return reference.identifier;
if (reference.title) return reference.title;
if (reference.id) return reference.id.slice(0, 8);
return "task";
}
function formatChangedEntityLabel(
singular: string,
plural: string,
labels: string[],
): string {
if (labels.length <= 0) return plural;
if (labels.length === 1) return `${singular} ${labels[0]}`;
return `${labels.length} ${plural}`;
}
function readNumber(value: unknown): number | null {
if (typeof value === "number" && Number.isFinite(value)) return value;
return null;
}
function readStringArrayLength(value: unknown): number {
if (!Array.isArray(value)) return 0;
return value.filter((entry) => typeof entry === "string" && entry.length > 0).length;
}
function formatAcceptedPlanDecompositionDetail(details: ActivityDetails): string | null {
if (!details) return null;
const status = typeof details.status === "string" ? details.status : null;
const requested = readNumber(details.requestedChildCount);
const totalChildren = readStringArrayLength(details.childIssueIds);
const newlyCreated = readStringArrayLength(details.newlyCreatedChildIssueIds);
const reused = Math.max(0, totalChildren - newlyCreated);
const parts: string[] = [];
if (newlyCreated > 0) parts.push(`created ${newlyCreated} new`);
if (reused > 0) parts.push(`reused ${reused} existing`);
if (parts.length === 0 && requested !== null) parts.push(`${requested} requested`);
const summary = parts.length > 0 ? parts.join(", ") : null;
if (status === "completed" && summary) return `decomposition completed (${summary})`;
if (status === "completed") return "decomposition completed";
if (status === "in_flight" && summary) return `decomposition in flight (${summary})`;
return summary;
}
function formatIssueUpdatedVerb(details: ActivityDetails): string | null {
if (!details) return null;
const previous = asRecord(details._previous) ?? {};
if (details.status !== undefined) {
const from = previous.status;
return from
? `changed status from ${humanizeValue(from)} to ${humanizeValue(details.status)} on`
: `changed status to ${humanizeValue(details.status)} on`;
}
if (details.priority !== undefined) {
const from = previous.priority;
return from
? `changed priority from ${humanizeValue(from)} to ${humanizeValue(details.priority)} on`
: `changed priority to ${humanizeValue(details.priority)} on`;
}
return null;
}
function formatAssigneeName(details: ActivityDetails, options: ActivityFormatOptions): string | null {
if (!details) return null;
const agentId = details.assigneeAgentId;
const userId = details.assigneeUserId;
if (typeof agentId === "string" && agentId) {
return options.agentMap?.get(agentId)?.name ?? "agent";
}
if (typeof userId === "string" && userId) {
return formatUserLabel(userId, options);
}
return null;
}
function formatIssueUpdatedAction(details: ActivityDetails, options: ActivityFormatOptions = {}): string | null {
if (!details) return null;
const previous = asRecord(details._previous) ?? {};
const parts: string[] = [];
if (details.status !== undefined) {
const from = previous.status;
parts.push(
from
? `changed the status from ${humanizeValue(from)} to ${humanizeValue(details.status)}`
: `changed the status to ${humanizeValue(details.status)}`,
);
}
if (details.priority !== undefined) {
const from = previous.priority;
parts.push(
from
? `changed the priority from ${humanizeValue(from)} to ${humanizeValue(details.priority)}`
: `changed the priority to ${humanizeValue(details.priority)}`,
);
}
if (details.assigneeAgentId !== undefined || details.assigneeUserId !== undefined) {
const assigneeName = formatAssigneeName(details, options);
parts.push(assigneeName ? `made ${assigneeName} responsible for the task` : "cleared the responsible");
}
if (details.title !== undefined) parts.push("updated the title");
if (details.description !== undefined) parts.push("updated the description");
return parts.length > 0 ? parts.join(", ") : null;
}
function formatStructuredIssueChange(input: {
action: string;
details: ActivityDetails;
options: ActivityFormatOptions;
forIssueDetail: boolean;
}): string | null {
const details = input.details;
if (!details) return null;
if (input.action === "issue.blockers_updated") {
const added = readIssueReferences(details, "addedBlockedByIssues").map(formatIssueReferenceLabel);
const removed = readIssueReferences(details, "removedBlockedByIssues").map(formatIssueReferenceLabel);
if (added.length > 0 && removed.length === 0) {
const changed = formatChangedEntityLabel("blocker", "blockers", added);
return input.forIssueDetail ? `added ${changed}` : `added ${changed} to`;
}
if (removed.length > 0 && added.length === 0) {
const changed = formatChangedEntityLabel("blocker", "blockers", removed);
return input.forIssueDetail ? `removed ${changed}` : `removed ${changed} from`;
}
return input.forIssueDetail ? "updated blockers" : "updated blockers on";
}
if (input.action === "issue.reviewers_updated" || input.action === "issue.approvers_updated") {
const added = readParticipants(details, "addedParticipants").map((participant) => formatParticipantLabel(participant, input.options));
const removed = readParticipants(details, "removedParticipants").map((participant) => formatParticipantLabel(participant, input.options));
const singular = input.action === "issue.reviewers_updated" ? "reviewer" : "approver";
const plural = input.action === "issue.reviewers_updated" ? "reviewers" : "approvers";
if (added.length > 0 && removed.length === 0) {
const changed = formatChangedEntityLabel(singular, plural, added);
return input.forIssueDetail ? `added ${changed}` : `added ${changed} to`;
}
if (removed.length > 0 && added.length === 0) {
const changed = formatChangedEntityLabel(singular, plural, removed);
return input.forIssueDetail ? `removed ${changed}` : `removed ${changed} from`;
}
return input.forIssueDetail ? `updated ${plural}` : `updated ${plural} on`;
}
return null;
}
export function formatActivityVerb(
action: string,
details?: Record<string, unknown> | null,
options: ActivityFormatOptions = {},
): string {
if (action === "issue.updated") {
const issueUpdatedVerb = formatIssueUpdatedVerb(details);
if (issueUpdatedVerb) return issueUpdatedVerb;
}
const structuredChange = formatStructuredIssueChange({
action,
details,
options,
forIssueDetail: false,
});
if (structuredChange) return structuredChange;
return ACTIVITY_ROW_VERBS[action] ?? action.replace(/[._]/g, " ");
}
export function formatIssueActivityAction(
action: string,
details?: Record<string, unknown> | null,
options: ActivityFormatOptions = {},
): string {
if (action === "issue.updated") {
const issueUpdatedAction = formatIssueUpdatedAction(details, options);
if (issueUpdatedAction) return issueUpdatedAction;
}
const structuredChange = formatStructuredIssueChange({
action,
details,
options,
forIssueDetail: true,
});
if (structuredChange) return structuredChange;
if (action === "issue.accepted_plan_decomposition_updated") {
const detail = formatAcceptedPlanDecompositionDetail(details);
if (detail) return detail;
}
if (action.startsWith("issue.monitor_") && details) {
const serviceName = typeof details.serviceName === "string" && details.serviceName.trim()
? details.serviceName.trim()
: null;
const base = ISSUE_ACTIVITY_LABELS[action] ?? action.replace(/[._]/g, " ");
return serviceName ? `${base} for ${serviceName}` : base;
}
if (
(
action === "issue.document_created" ||
action === "issue.document_updated" ||
action === "issue.document_locked" ||
action === "issue.document_unlocked" ||
action === "issue.document_deleted"
) &&
details
) {
const key = typeof details.key === "string" ? details.key : "document";
const title = typeof details.title === "string" && details.title ? ` (${details.title})` : "";
return `${ISSUE_ACTIVITY_LABELS[action] ?? action} ${key}${title}`;
}
return ISSUE_ACTIVITY_LABELS[action] ?? action.replace(/[._]/g, " ");
}