Files
PaperClipAI/server/src/services/heartbeat/task-context.ts
T
43b2d8be22 feat(dashboard): add an experimental areas and responsibilities dashboard (#22069)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The dashboard is the first page a person sees in a company
> - The classic dashboard shows agents, runs, costs and recent tasks
> - It does not show what the person is responsible for, or if that work
goes well
> - People think in areas, such as Fundraising or Customers, and in the
things they own in each area
> - This pull request adds a dashboard built on areas and
responsibilities, behind an experimental setting that is off by default
> - The benefit is that a person sees what they own, how it is going,
and what agents do for it, on one page

## Linked Issues or Issue Description

No public issue exists for this work. The description follows the
feature request template.

**Subsystem affected**

Dashboard, navigation, the task conversation, routines, and the instance
experimental settings.

**Problem or motivation**

The classic dashboard counts agents and tasks. It does not say what a
person owns or if it goes well. People who run a company with agents
want to see their areas, the responsibilities in each area, the bar each
one must meet, and the agents and routines that serve it.

**Proposed solution**

A person owns responsibilities. Each responsibility belongs to an area
and has a bar, a number to reach. Projects, tasks and routines link to a
responsibility, and the page shows its status from those links. An agent
can interview the person and draft the dashboard. The person accepts or
declines each change, and any change can be undone from a saved version.

**Alternatives considered**

Add the same data to the classic dashboard. That page is a fixed set of
cards for company activity, so a second, person-centred page is clearer.
The setting lets a person pick one of the two.

**Roadmap alignment**

This is an experimental feature behind `enableResponsibilities`. It is
off by default and changes nothing for a person who leaves it off.

## What Changed

- Add the setting "Areas & Responsibilities dashboard"
(`enableResponsibilities`, off by default). On, Dashboard in the sidebar
opens the new page, and the classic dashboard link is not shown in the
sidebars or the command palette. Off, nothing changes.
- Add tables and migrations 0492 to 0497 for areas, responsibilities,
links to work, metrics, status reports, saved dashboard versions, and
model-call records for summaries.
- Add the API: areas, responsibilities, links, bars, metrics, status
reports, summaries, runs, automation, and the dashboard conversation
with versions and undo. Each route checks company access and writes to
the activity log.
- Add four task conversations with an agent: about a bar, about an
automation, about a routine, and about the whole dashboard. The agent
proposes a change. Nothing applies until a person accepts it.
- Add standing checks: routines that an agent carries out on its
heartbeat and reports.
- Add the Dashboard page: search, counts, areas that open and close, a
primary New area button, and a message box at the bottom of the page.
Add the responsibility page with its bar, metrics, work and routines.
- Add the Paperclip skill sections and runner API entries that let an
agent use these routes. The runner skill inventory is regenerated (166
to 174 rows).
- Keep the new runner API tests in their own file so
`runner-api.test.ts` stays at 985 lines.
- Onboarding is not changed. The onboarding changes that build on this
work are a separate pull request.

## Verification

- Type checks pass for `packages/db`, `packages/shared`, `server` (all
layers) and `ui`.
- `pnpm --filter @paperclipai/db check:migrations` passes. A new
`drizzle-kit generate` run produces no further change.
- Tests for every changed file pass: 26 server test files (3,009 tests),
116 UI test files (1,991 tests) and 28 shared test files (432 tests).
- The runner capability inventory checks pass.
- I started the app on a local database that already held earlier data.
Master's new migrations and these migrations applied without error. With
the setting on, the Dashboard and a responsibility page loaded with no
console or server errors. The More menu and the command palette show one
Dashboard.
- I did not run `pnpm verify`, the full local suite, or the browser
suites. Required CI covers them.
- The agent conversations are tested with simulated agents. No real
model has run them.

## Risks

- Medium. The change is large, and the setting is off by default. With
it off, the new routes refuse requests and the UI is unchanged.
- Migrations only add tables and columns. Two replace a CHECK
constraint, and one builds an index `CONCURRENTLY`. These two have the
`online_compatible` override with a reason in the file, and the second
one is listed in `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`.
- Master can add migrations before this merges. The migrations then need
new numbers.
- `responsibilities.ts` (1,663 lines), `responsibility-summaries.ts`
(1,239 lines) and one Storybook fixture file (1,305 lines) are new files
over 1,000 lines. They each keep one cohesive unit together: the service
for one table family, the model-call path for summaries, and the
fixtures that the stories share. No existing file crosses 1,000 lines.

> 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

- Anthropic Claude: Claude Fable 5.2 (`claude-fable-5-2`) wrote most of
the change, with Claude Sonnet 5.5 (`claude-sonnet-5-5`) for the final
steps. Both used tool use, code execution and browser checks.

## 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
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Scott Tong <scott@scottsmbpm5max.lan>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-17 20:45:44 -08:00

549 lines
26 KiB
TypeScript

import { createHash } from "node:crypto";
import { eq } from "drizzle-orm";
import { companies } from "@paperclipai/db";
import type { Db, agents, agentTaskSessions, heartbeatRuns } from "@paperclipai/db";
import { AUTOMATION_CONVERSATION_ORIGIN_KIND, FAST_RESPONSE_AGENT_GUIDANCE, ONBOARDING_FIRST_TASK_ORIGIN_KIND, RESPONSIBILITY_BAR_ORIGIN_KIND, RESPONSIBILITY_DASHBOARD_ORIGIN_KIND, RESPONSIBILITY_STATUS_UPDATE_ORIGIN_KIND, fastResponseHistoryBody, isValidIanaTimeZone } from "@paperclipai/shared";
import type { PaperclipTurnContext } from "@paperclipai/adapter-utils/server-utils";
import { parseObject } from "../../adapters/utils.js";
import { isConversation } from "../agent-conversations.js";
import { chatCompletionInstruction } from "../chat-completion-delivery.js";
import { getConversationConfirmationContext } from "../conversation-confirmation-context.js";
import { buildExecutionContinuation } from "../execution-continuation.js";
import { getIssueContinuationSummaryDocument } from "../issue-continuation-summary.js";
import type { issueService } from "../issues.js";
import { createRunSecretRedactionRegistry } from "../run-secret-redaction.js";
import { redactQuarantinedBodyForHigherTrust, sanitizeQuarantinedCommentForHigherTrust } from "../source-trust.js";
import { getTaskPlanContext } from "../task-plan-context.js";
import { loadResponsibilityBarGuidance } from "../responsibility-bar-guidance.js";
import { loadAutomationConversationGuidance } from "../automation-conversation-guidance.js";
import { loadDashboardConversationGuidance } from "../responsibility-dashboard-guidance.js";
import { loadStatusRefreshReminder, loadStatusUpdateGuidance } from "../responsibility-status-guidance.js";
import { loadStandingCheckGuidance } from "../routine-standing-checks.js";
import { caseExecutionMarkdown, getCaseExecutionContext } from "../case-context.js";
import type { TrustPresetResolution } from "../trust-preset-resolver.js";
import { liveVoiceExecutionGuidance } from "../voice/voice-execution-guidance.js";
import { buildPaperclipWakePayload, ConfigurationIncompleteFailure, readHeartbeatWakeComments, PAPERCLIP_WAKE_PAYLOAD_KEY, type createHeartbeatRunPreparation } from "./run-preparation.js";
import { buildPaperclipTaskMarkdown } from "./task-markdown.js";
import { deriveCommentId, extractWakeCommentIds } from "../../modules/run-dispatch/index.js";
import { workspacePreferenceService } from "../workspace-preferences.js";
type RunPreparation = ReturnType<typeof createHeartbeatRunPreparation>;
type IssueContext = NonNullable<Awaited<ReturnType<RunPreparation["getIssueExecutionContext"]>>>;
export interface HeartbeatTaskContextInput {
run: Pick<typeof heartbeatRuns.$inferSelect, "id">;
agent: Pick<typeof agents.$inferSelect, "id" | "companyId" | "adapterType">;
task: {
issueRef: Pick<IssueContext,
"id" | "identifier" | "title" | "status" | "priority" | "workMode" |
"conversationAgentId" | "description" | "projectId"> | null;
issueContext: IssueContext | null;
context: Record<string, unknown>;
taskSession: Pick<typeof agentTaskSessions.$inferSelect, "lastRunId"> | null;
};
policy: {
recovering?: boolean;
trustPreset: Pick<TrustPresetResolution, "kind">;
experimentalInstanceSettings: { enableSimplifiedEnglishInteractions?: boolean; enableCases?: boolean; enableConferenceRoomChat?: boolean; enableStatusCards?: boolean; enableResponsibilities?: boolean };
};
services: {
issuesSvc: Pick<ReturnType<typeof issueService>, "getAncestors">;
getPinnedSkillTestContext: RunPreparation["getPinnedSkillTestContext"];
};
}
function readNonEmptyString(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value : null;
}
/** Rebuilds task prompt fields on the run's context; acquires no execution resources. */
export async function prepareHeartbeatTaskContext(db: Db, input: HeartbeatTaskContextInput) {
const { run, agent } = input;
const { issueRef, issueContext, context, taskSession } = input.task;
const { trustPreset, experimentalInstanceSettings } = input.policy;
const { issuesSvc, getPinnedSkillTestContext } = input.services;
const admittedScope = parseObject(context.paperclipAgentJwtScope);
if (!input.policy.recovering || (admittedScope.kind !== "standard" && admittedScope.kind !== "skill_test")) {
const savedIssue = parseObject(context.paperclipIssue);
const skillTest = input.policy.recovering
? savedIssue.workMode === "skill_test" || Boolean(context.paperclipSkillTest)
: issueRef?.workMode === "skill_test";
context.paperclipAgentJwtScope = skillTest && issueRef
? { kind: "skill_test", issueId: issueRef.id }
: { kind: "standard" };
}
const isSkillTest = parseObject(context.paperclipAgentJwtScope).kind === "skill_test";
const wakeCommentId = deriveCommentId(context, null);
const commentIds = [...new Set([...extractWakeCommentIds(context), ...(wakeCommentId ? [wakeCommentId] : [])])];
const [summary, ancestors, pinnedSkillTestRead, wakeComments] = await Promise.allSettled([
issueRef && !isConversation(issueContext) ? getIssueContinuationSummaryDocument(db, issueRef.id) : Promise.resolve(null),
issueRef ? issuesSvc.getAncestors(issueRef.id) : Promise.resolve([]),
isSkillTest && issueRef ? getPinnedSkillTestContext(agent.companyId, issueRef.id) : Promise.resolve(null),
readHeartbeatWakeComments(db, agent.companyId, readNonEmptyString(context.issueId), commentIds),
]);
if (summary.status === "rejected") throw summary.reason;
if (ancestors.status === "rejected") throw ancestors.reason;
if (pinnedSkillTestRead.status === "rejected") throw pinnedSkillTestRead.reason;
if (wakeComments.status === "rejected") throw wakeComments.reason;
const wakeCommentRows = wakeComments.value;
const selectedWakeComment = issueRef && wakeCommentId ? wakeCommentRows.find(comment => comment.id === wakeCommentId && comment.issueId === issueRef.id) ?? null : null;
const wakeCommentContext = selectedWakeComment ? {
id: selectedWakeComment.id,
body: selectedWakeComment.deletedAt ? "" : selectedWakeComment.body,
authorType: selectedWakeComment.authorType,
authorAgentId: selectedWakeComment.authorAgentId,
authorUserId: selectedWakeComment.authorUserId,
presentation: selectedWakeComment.deletedAt ? null : selectedWakeComment.presentation,
metadata: selectedWakeComment.deletedAt ? null : selectedWakeComment.metadata,
deletedAt: selectedWakeComment.deletedAt,
deletedByType: selectedWakeComment.deletedByType,
deletedByAgentId: selectedWakeComment.deletedByAgentId,
deletedByUserId: selectedWakeComment.deletedByUserId,
deletedByRunId: selectedWakeComment.deletedByRunId,
sourceTrust: selectedWakeComment.sourceTrust,
} : null;
const continuationSummary = summary.value;
const issueAncestors = ancestors.value;
const pinnedSkillTestContext = pinnedSkillTestRead.value;
const exposeLowTrustRaw = trustPreset.kind === "low_trust_review";
const safeContinuationSummary =
continuationSummary && !exposeLowTrustRaw
? redactQuarantinedBodyForHigherTrust(continuationSummary)
: continuationSummary;
const safeWakeCommentContext =
wakeCommentContext && !exposeLowTrustRaw
? sanitizeQuarantinedCommentForHigherTrust(wakeCommentContext)
: wakeCommentContext;
if (continuationSummary) {
context.paperclipContinuationSummary = {
key: safeContinuationSummary!.key,
title: safeContinuationSummary!.title,
body: safeContinuationSummary!.body,
sourceTrust: safeContinuationSummary!.sourceTrust ?? null,
updatedAt: safeContinuationSummary!.updatedAt.toISOString(),
};
} else {
delete context.paperclipContinuationSummary;
}
if (isSkillTest && !pinnedSkillTestContext) {
throw new ConfigurationIncompleteFailure("The skill test's saved version is unavailable.", {
configurationIncomplete: { reason: "skill_unavailable", actionUrl: "/skills" },
});
}
if (pinnedSkillTestContext) {
context.paperclipSkillTest = {
...pinnedSkillTestContext,
directive:
"Use this pinned file inventory as the exact skill revision under test, regardless of synced runtime skills.",
};
} else {
delete context.paperclipSkillTest;
}
const executionContinuation =
issueRef && !isConversation(issueContext) && issueContext?.assigneeAgentId === agent.id
? await buildExecutionContinuation({
db,
companyId: agent.companyId,
issueId: issueRef.id,
agentId: agent.id,
runId: run.id,
context,
previousContextRunId: taskSession?.lastRunId,
summary: safeContinuationSummary?.body ?? null,
exposeLowTrustRaw,
})
: null;
context.executionContinuation = executionContinuation;
const paperclipWakePayload = await buildPaperclipWakePayload({
db,
companyId: agent.companyId,
agentId: agent.id,
runId: run.id,
contextSnapshot: context,
wakeCommentRows,
continuationSummary,
issueSummary: issueRef
? {
id: issueRef.id,
identifier: issueRef.identifier,
title: issueRef.title,
description: issueContext?.description ?? null,
status: issueRef.status,
priority: issueRef.priority,
workMode: issueRef.workMode,
projectId: issueRef.projectId,
executionPolicy: issueContext?.executionPolicy ?? null,
originKind: issueContext?.originKind ?? null,
}
: null,
exposeLowTrustRaw,
simplifiedEnglishInteractions:
experimentalInstanceSettings.enableSimplifiedEnglishInteractions ===
true,
});
if (paperclipWakePayload) {
context[PAPERCLIP_WAKE_PAYLOAD_KEY] = paperclipWakePayload;
} else {
delete context[PAPERCLIP_WAKE_PAYLOAD_KEY];
}
const safeWakeComments = (paperclipWakePayload?.comments ?? []).flatMap(
(comment) =>
typeof comment.id === "string" && typeof comment.body === "string"
? [
{
id: comment.id,
body: fastResponseHistoryBody({ body: comment.body, origin: typeof comment.origin === "string" ? comment.origin : null }),
attachments: Array.isArray(comment.attachments)
? comment.attachments.flatMap((attachment) => {
const descriptor = parseObject(attachment);
const id = readNonEmptyString(descriptor.id);
const filename = readNonEmptyString(
descriptor.filename,
);
const contentType = readNonEmptyString(
descriptor.contentType,
);
const contentPath = readNonEmptyString(
descriptor.contentPath,
);
const byteSize = descriptor.byteSize;
return id &&
filename &&
contentType &&
contentPath &&
typeof byteSize === "number"
? [
{
id,
filename,
contentType,
byteSize,
contentPath,
},
]
: [];
})
: [],
},
]
: [],
);
// Always replace caller-supplied context with the immutable, company-scoped
// conversation snapshot. It belongs only to the endpoint's assigned agent.
const liveVoiceGuidance = issueContext?.chatAssignedAgentId === agent.id && issueContext.chatProvider === "speko"
? await liveVoiceExecutionGuidance(db, { companyId: agent.companyId, issueId: issueContext.id, agentId: agent.id })
: null;
context.paperclipTaskCommunicationGuidance =
issueContext?.chatAssignedAgentId === agent.id
? issueContext.chatCommunicationGuidance
: null;
// Use the standing chat owner's saved preferences, never worker text.
// Recovery retains the admitted choices instead of silently changing its prompt.
const conversationOwnerPreference = isConversation(issueContext) && issueContext?.conversationUserId
&& !input.policy.recovering
? await workspacePreferenceService(db).get(issueContext.conversationUserId)
: null;
const coordinatorWorkspace = agent.adapterType === "paperclip_runner" && isConversation(issueContext)
&& issueContext?.conversationUserId
? input.policy.recovering
? context.paperclipCoordinatorWorkspaceEnabled === true
: conversationOwnerPreference?.coordinatorWorkspaceEnabled === true
: false;
context.paperclipCoordinatorWorkspaceEnabled = Boolean(coordinatorWorkspace);
const savedPersonTimeZone = input.policy.recovering
? readNonEmptyString(context.paperclipConversationTimeZone)
: conversationOwnerPreference?.timeZone ?? null;
const personTimeZone = isConversation(issueContext) && issueContext?.conversationUserId
&& savedPersonTimeZone && isValidIanaTimeZone(savedPersonTimeZone)
? savedPersonTimeZone
: null;
if (personTimeZone) context.paperclipConversationTimeZone = personTimeZone;
else delete context.paperclipConversationTimeZone;
const [chatCompany] = issueRef?.conversationAgentId && !issueRef.identifier
? await db.select({ issuePrefix: companies.issuePrefix }).from(companies).where(eq(companies.id, agent.companyId))
: [];
const taskMarkdownInput = {
companyPrefix: chatCompany?.issuePrefix,
coordinatorWorkspace: Boolean(coordinatorWorkspace),
personTimeZone,
conferenceRoomEnabled: experimentalInstanceSettings.enableConferenceRoomChat === true,
statusCardsEnabled: experimentalInstanceSettings.enableStatusCards === true,
casesEnabled: experimentalInstanceSettings.enableCases === true,
// Work a routine created, the onboarding task, bar and automation conversations and status update requests are never offered as routines.
routineSuggestionsEnabled: experimentalInstanceSettings.enableResponsibilities === true
&& issueContext?.originKind !== "routine_execution"
&& issueContext?.originKind !== ONBOARDING_FIRST_TASK_ORIGIN_KIND
&& issueContext?.originKind !== RESPONSIBILITY_BAR_ORIGIN_KIND
&& issueContext?.originKind !== AUTOMATION_CONVERSATION_ORIGIN_KIND
&& issueContext?.originKind !== RESPONSIBILITY_STATUS_UPDATE_ORIGIN_KIND
&& issueContext?.originKind !== RESPONSIBILITY_DASHBOARD_ORIGIN_KIND,
// The bar conversation's instructions, rebuilt from the responsibility each wake.
responsibilityBarGuidance: experimentalInstanceSettings.enableResponsibilities === true && issueRef && issueContext
&& issueContext.originKind === RESPONSIBILITY_BAR_ORIGIN_KIND
? await loadResponsibilityBarGuidance(db, {
issue: {
id: issueRef.id,
companyId: agent.companyId,
originKind: issueContext.originKind,
originId: issueContext.originId ?? null,
assigneeAgentId: issueContext.assigneeAgentId ?? null,
},
agentId: agent.id,
})
: null,
// The automation conversation's instructions, rebuilt from the task being automated each wake.
automationConversationGuidance: experimentalInstanceSettings.enableResponsibilities === true && issueRef && issueContext
&& issueContext.originKind === AUTOMATION_CONVERSATION_ORIGIN_KIND
? await loadAutomationConversationGuidance(db, {
issue: {
id: issueRef.id,
companyId: agent.companyId,
originKind: issueContext.originKind,
originId: issueContext.originId ?? null,
assigneeAgentId: issueContext.assigneeAgentId ?? null,
},
agentId: agent.id,
})
: null,
// A status update request's instructions, rebuilt from the responsibility each wake.
responsibilityStatusUpdateGuidance: experimentalInstanceSettings.enableResponsibilities === true && issueRef && issueContext
&& issueContext.originKind === RESPONSIBILITY_STATUS_UPDATE_ORIGIN_KIND
? await loadStatusUpdateGuidance(db, {
issue: {
id: issueRef.id,
companyId: agent.companyId,
originKind: issueContext.originKind,
originId: issueContext.originId ?? null,
assigneeAgentId: issueContext.assigneeAgentId ?? null,
},
agentId: agent.id,
runId: run.id,
})
: null,
// The dashboard conversation's instructions, rebuilt from the person's dashboard each wake; they differ by mode.
responsibilityDashboardGuidance: experimentalInstanceSettings.enableResponsibilities === true && issueRef && issueContext
&& issueContext.originKind === RESPONSIBILITY_DASHBOARD_ORIGIN_KIND
? await loadDashboardConversationGuidance(db, {
issue: {
id: issueRef.id,
companyId: agent.companyId,
originKind: issueContext.originKind,
originId: issueContext.originId ?? null,
assigneeAgentId: issueContext.assigneeAgentId ?? null,
},
agentId: agent.id,
})
: null,
// On other work under a responsibility this agent reports on: a short reminder to refresh its status.
responsibilityStatusReminder: experimentalInstanceSettings.enableResponsibilities === true && issueRef && issueContext
&& !isConversation(issueContext) && (issueRef.workMode ?? "standard") === "standard"
&& issueContext.originKind !== RESPONSIBILITY_STATUS_UPDATE_ORIGIN_KIND
? await loadStatusRefreshReminder(db, {
issue: {
id: issueRef.id,
companyId: agent.companyId,
projectId: issueRef.projectId ?? null,
originKind: issueContext.originKind ?? null,
assigneeAgentId: issueContext.assigneeAgentId ?? null,
},
agentId: agent.id,
})
: null,
conversationConfirmations: issueRef && isConversation(issueContext)
? await getConversationConfirmationContext({ db, companyId: agent.companyId, issueId: issueRef.id, agentId: agent.id })
: null,
onboardingChat: issueContext?.originKind === "onboarding_chat",
onboardingGreeting: context.wakeReason === "onboarding_chat_greeting",
issue: issueRef
? {
id: issueRef.id,
identifier: issueRef.identifier,
title: issueRef.title,
titleNeedsGeneration: issueContext?.titleNeedsGeneration,
workMode: issueRef.workMode,
conversationAgentId: issueContext?.conversationAgentId,
executionPolicy: issueContext?.executionPolicy,
description: issueRef.description,
}
: null,
ancestors: issueAncestors,
wakeComment: safeWakeCommentContext,
wakeComments: safeWakeComments,
attachmentOmissions: paperclipWakePayload?.attachmentOmissions,
externalChatProvider: paperclipWakePayload?.externalChatProvider,
slackCommand: issueContext?.chatAssignedAgentId === agent.id
? issueContext.chatSlackCommand
: null,
nativeRunner: agent.adapterType === "paperclip_runner",
interaction: {
kind: readNonEmptyString(context.interactionKind),
status: readNonEmptyString(context.interactionStatus),
},
planReview: paperclipWakePayload?.planReviewContext?.interaction
? {
status: paperclipWakePayload.planReviewContext.interaction.status,
reason: paperclipWakePayload.planReviewContext.interaction.result?.reason,
}
: null,
acceptedPlanContinuation:
readNonEmptyString(context.workspaceRefreshReason) ===
"accepted_plan_confirmation" &&
Object.keys(parseObject(context.acceptedPlanWakeRouting)).length ===
0,
acceptedPlan: (() => {
const accepted = parseObject(
parseObject(context.planReviewInteraction).acceptedTargetRevision,
);
const revisionId = readNonEmptyString(accepted.revisionId);
if (!revisionId) return null;
return {
documentId: readNonEmptyString(accepted.documentId),
revisionId,
revisionNumber:
typeof accepted.revisionNumber === "number"
? accepted.revisionNumber
: null,
};
})(),
};
const taskPlan = issueRef && !isConversation(issueContext)
? await getTaskPlanContext({
db,
companyId: agent.companyId,
issueId: issueRef.id,
approvedRevisionId: taskMarkdownInput.acceptedPlan?.revisionId,
exposeLowTrustRaw,
})
: null;
// Unlike the frozen initial communication preferences, live-call context
// must also reach resumed turns. Rebuild it from server records each wake.
const liveVoiceTaskPrefix = liveVoiceGuidance ? `${liveVoiceGuidance}\n\n` : "";
context.paperclipCasesEnabled = experimentalInstanceSettings.enableCases === true;
const workflowCase = issueRef && experimentalInstanceSettings.enableCases
? await getCaseExecutionContext(db, { companyId: agent.companyId, issueId: issueRef.id, agentId: agent.id, runId: run.id, exposeLowTrustRaw })
: null;
if (workflowCase) context.paperclipCase = workflowCase;
else delete context.paperclipCase;
const assignmentPrefix = liveVoiceTaskPrefix + caseExecutionMarkdown(workflowCase);
// Experimental standing checks (enableResponsibilities): a timer wake with
// no task carries the agent's active standing checks, rebuilt each wake.
const standingChecks = !issueRef && experimentalInstanceSettings.enableResponsibilities === true
&& readNonEmptyString(context.wakeReason) === "heartbeat_timer"
? await loadStandingCheckGuidance(db, { companyId: agent.companyId, agentId: agent.id })
: null;
// A wake with no task builds no task markdown; never let that read as "null".
const markdown = (options: { includeDescription?: boolean; includeWakeComments?: boolean }) =>
assignmentPrefix
+ [buildPaperclipTaskMarkdown({ ...taskMarkdownInput, taskPlan, ...options }), standingChecks].filter(Boolean).join("\n\n")
+ chatCompletionInstruction(context);
let taskMarkdown = markdown({});
let taskMarkdownAssignment = markdown({ includeWakeComments: false });
const taskMarkdownCompact = markdown({ includeDescription: false });
const taskMarkdownAssignmentCompact = markdown({ includeDescription: false, includeWakeComments: false });
if (issueRef) {
context.paperclipIssue = {
id: issueRef.id,
identifier: issueRef.identifier,
title: issueRef.title,
description: isConversation(issueContext) ? null : issueRef.description,
workMode: issueRef.workMode,
};
} else {
delete context.paperclipIssue;
}
if (wakeCommentContext) {
context.paperclipWakeComment = safeWakeCommentContext;
} else {
delete context.paperclipWakeComment;
}
if (taskMarkdown) {
context.paperclipTaskMarkdown = taskMarkdown;
} else {
delete context.paperclipTaskMarkdown;
}
if (taskMarkdownAssignment) {
context.paperclipTaskMarkdownAssignment = taskMarkdownAssignment;
} else {
delete context.paperclipTaskMarkdownAssignment;
}
if (taskMarkdownCompact && taskMarkdownCompact !== taskMarkdown) {
context.paperclipTaskMarkdownCompact = taskMarkdownCompact;
} else {
delete context.paperclipTaskMarkdownCompact;
}
if (taskMarkdownAssignmentCompact && taskMarkdownAssignmentCompact !== taskMarkdownAssignment) {
context.paperclipTaskMarkdownAssignmentCompact = taskMarkdownAssignmentCompact;
} else {
delete context.paperclipTaskMarkdownAssignmentCompact;
}
context.paperclipTaskCommunicationGuidance = [context.paperclipTaskCommunicationGuidance, FAST_RESPONSE_AGENT_GUIDANCE].filter(Boolean).join("\n\n");
if (issueRef) {
const redactedWakeContext = await createRunSecretRedactionRegistry(
db,
).redactForIssue(agent.companyId, issueRef.id, {
paperclipIssue: context.paperclipIssue,
paperclipCase: context.paperclipCase,
paperclipWakeComment: context.paperclipWakeComment,
paperclipTaskCommunicationGuidance: context.paperclipTaskCommunicationGuidance,
paperclipTaskMarkdown: context.paperclipTaskMarkdown,
paperclipTaskMarkdownCompact: context.paperclipTaskMarkdownCompact,
paperclipTaskMarkdownAssignment: context.paperclipTaskMarkdownAssignment,
paperclipTaskMarkdownAssignmentCompact: context.paperclipTaskMarkdownAssignmentCompact,
});
context.paperclipIssue = redactedWakeContext.paperclipIssue;
if (redactedWakeContext.paperclipCase) context.paperclipCase = redactedWakeContext.paperclipCase;
context.paperclipTaskCommunicationGuidance = redactedWakeContext.paperclipTaskCommunicationGuidance;
if (redactedWakeContext.paperclipWakeComment) {
context.paperclipWakeComment =
redactedWakeContext.paperclipWakeComment;
}
if (redactedWakeContext.paperclipTaskMarkdown) {
context.paperclipTaskMarkdown =
redactedWakeContext.paperclipTaskMarkdown;
}
if (redactedWakeContext.paperclipTaskMarkdownCompact) {
context.paperclipTaskMarkdownCompact =
redactedWakeContext.paperclipTaskMarkdownCompact;
}
if (redactedWakeContext.paperclipTaskMarkdownAssignment) {
context.paperclipTaskMarkdownAssignment =
redactedWakeContext.paperclipTaskMarkdownAssignment;
}
if (redactedWakeContext.paperclipTaskMarkdownAssignmentCompact) {
context.paperclipTaskMarkdownAssignmentCompact =
redactedWakeContext.paperclipTaskMarkdownAssignmentCompact;
}
}
if (issueRef) {
const digest = (value: string | null | undefined) =>
value?.trim()
? createHash("sha256")
.update(value.trim().replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ""))
.digest("hex")
: null;
const redactedIssue = parseObject(context.paperclipIssue);
context.paperclipTurnContext = {
version: 1,
assignment: {
owner: "task_markdown",
description: {
id: issueRef.id,
revision: digest(readNonEmptyString(redactedIssue.description)),
},
},
events: {
owner: "wake_prompt",
comments: safeWakeComments.map((comment) => ({
id: comment.id,
revision: digest(comment.body),
})),
},
} satisfies PaperclipTurnContext;
} else {
delete context.paperclipTurnContext;
}
const pinnedSkillTest = pinnedSkillTestContext
? { key: pinnedSkillTestContext.skillKey, versionId: pinnedSkillTestContext.skillVersionId } : null;
return { continuationSummary, executionContinuation, paperclipWakePayload, safeWakeComments, safeWakeCommentContext, pinnedSkillTest };
}