Add recovery handoff system notices (#5289)

## Thinking Path

> - Paperclip orchestrates AI agents for zero-human companies.
> - Agent runs can end productively while the source issue still lacks a
durable final disposition.
> - That leaves the control plane unsure whether to resume, escalate, or
close the work.
> - Issue comments also need a presentation contract so system-authored
recovery notices can render as first-class thread messages without
overloading normal comments.
> - This pull request adds successful-run handoff recovery, comment
presentation metadata, and system notice rendering.
> - The benefit is stricter task liveness with clearer operator-facing
recovery state.

## What Changed

- Added successful-run handoff decisions, wake payloads, escalation
behavior, and recovery tests.
- Added issue comment presentation metadata with migration
`0078_white_darwin.sql` and shared/server/company portability support.
- Rendered recovery/system notices in issue chat with dedicated UI
components, fixtures, tests, and storybook/lab coverage.
- Included the current recovery model-profile hint patch so automatic
recovery follow-ups use the cheap profile.

## Verification

- `pnpm install --frozen-lockfile`
- `pnpm exec vitest run
server/src/services/recovery/successful-run-handoff.test.ts
ui/src/components/SystemNotice.test.tsx
ui/src/lib/system-notice-comment.test.ts
ui/src/components/IssueChatThreadSystemNotice.test.tsx`

## Risks

- Migration-bearing PR: merge this before any other branch that might
later add a migration.
- The branch touches both recovery services and issue-thread rendering,
so review should pay attention to recovery wake idempotency and comment
metadata compatibility.

## Model Used

- OpenAI GPT-5 Codex via Paperclip `codex_local` adapter, with
shell/git/GitHub CLI tool use.

## 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 run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Dotta 2026-05-06 06:05:58 -05:00 committed by GitHub
parent 50db8c01d2
commit 454edfe81e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
70 changed files with 21919 additions and 125 deletions

View file

@ -0,0 +1,3 @@
ALTER TABLE "issue_comments" ADD COLUMN "author_type" text;--> statement-breakpoint
ALTER TABLE "issue_comments" ADD COLUMN "presentation" jsonb;--> statement-breakpoint
ALTER TABLE "issue_comments" ADD COLUMN "metadata" jsonb;

File diff suppressed because it is too large Load diff

View file

@ -547,6 +547,13 @@
"when": 1777933347806,
"tag": "0077_unusual_karnak",
"breakpoints": true
},
{
"idx": 78,
"version": "7",
"when": 1778004024976,
"tag": "0078_white_darwin",
"breakpoints": true
}
]
}

View file

@ -1,4 +1,5 @@
import { pgTable, uuid, text, timestamp, index } from "drizzle-orm/pg-core";
import type { IssueCommentAuthorType, IssueCommentMetadata, IssueCommentPresentation } from "@paperclipai/shared";
import { pgTable, uuid, text, timestamp, index, jsonb } from "drizzle-orm/pg-core";
import { companies } from "./companies.js";
import { issues } from "./issues.js";
import { agents } from "./agents.js";
@ -12,8 +13,11 @@ export const issueComments = pgTable(
issueId: uuid("issue_id").notNull().references(() => issues.id),
authorAgentId: uuid("author_agent_id").references(() => agents.id),
authorUserId: text("author_user_id"),
authorType: text("author_type").$type<IssueCommentAuthorType>(),
createdByRunId: uuid("created_by_run_id").references(() => heartbeatRuns.id, { onDelete: "set null" }),
body: text("body").notNull(),
presentation: jsonb("presentation").$type<IssueCommentPresentation | null>(),
metadata: jsonb("metadata").$type<IssueCommentMetadata | null>(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
},

View file

@ -1260,9 +1260,12 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness {
id: randomUUID(),
companyId: parentIssue.companyId,
issueId,
authorType: options?.authorAgentId ? "agent" : "system",
authorAgentId: options?.authorAgentId ?? null,
authorUserId: null,
body,
presentation: null,
metadata: null,
createdAt: now,
updatedAt: now,
};

View file

@ -148,6 +148,25 @@ export const ISSUE_PRIORITIES = ["critical", "high", "medium", "low"] as const;
export type IssuePriority = (typeof ISSUE_PRIORITIES)[number];
export const MAX_ISSUE_REQUEST_DEPTH = 1024;
export const ISSUE_COMMENT_AUTHOR_TYPES = ["user", "agent", "system"] as const;
export type IssueCommentAuthorType = (typeof ISSUE_COMMENT_AUTHOR_TYPES)[number];
export const ISSUE_COMMENT_PRESENTATION_KINDS = ["message", "system_notice"] as const;
export type IssueCommentPresentationKind = (typeof ISSUE_COMMENT_PRESENTATION_KINDS)[number];
export const ISSUE_COMMENT_PRESENTATION_TONES = ["neutral", "info", "success", "warning", "danger"] as const;
export type IssueCommentPresentationTone = (typeof ISSUE_COMMENT_PRESENTATION_TONES)[number];
export const ISSUE_COMMENT_METADATA_ROW_TYPES = [
"text",
"code",
"key_value",
"issue_link",
"agent_link",
"run_link",
] as const;
export type IssueCommentMetadataRowType = (typeof ISSUE_COMMENT_METADATA_ROW_TYPES)[number];
export function clampIssueRequestDepth(value: number | null | undefined): number {
if (typeof value !== "number" || !Number.isFinite(value)) return 0;
return Math.min(MAX_ISSUE_REQUEST_DEPTH, Math.max(0, Math.floor(value)));

View file

@ -20,6 +20,10 @@ export {
INBOX_MINE_ISSUE_STATUS_FILTER,
ISSUE_PRIORITIES,
MAX_ISSUE_REQUEST_DEPTH,
ISSUE_COMMENT_AUTHOR_TYPES,
ISSUE_COMMENT_METADATA_ROW_TYPES,
ISSUE_COMMENT_PRESENTATION_KINDS,
ISSUE_COMMENT_PRESENTATION_TONES,
clampIssueRequestDepth,
ISSUE_THREAD_INTERACTION_KINDS,
ISSUE_THREAD_INTERACTION_STATUSES,
@ -130,6 +134,10 @@ export {
type AgentIconName,
type IssueStatus,
type IssuePriority,
type IssueCommentAuthorType,
type IssueCommentMetadataRowType,
type IssueCommentPresentationKind,
type IssueCommentPresentationTone,
type IssueThreadInteractionKind,
type IssueThreadInteractionStatus,
type IssueThreadInteractionContinuationPolicy,
@ -352,6 +360,8 @@ export type {
IssueBlockerAttentionState,
IssueProductivityReview,
IssueProductivityReviewTrigger,
SuccessfulRunHandoffState,
SuccessfulRunHandoffStateKind,
IssueReferenceSource,
IssueRelatedWorkItem,
IssueRelatedWorkSummary,
@ -366,6 +376,16 @@ export type {
IssueExecutionStagePrincipal,
IssueExecutionDecision,
IssueComment,
IssueCommentMetadata,
IssueCommentMetadataSection,
IssueCommentMetadataRow,
IssueCommentMetadataTextRow,
IssueCommentMetadataCodeRow,
IssueCommentMetadataKeyValueRow,
IssueCommentMetadataIssueLinkRow,
IssueCommentMetadataAgentLinkRow,
IssueCommentMetadataRunLinkRow,
IssueCommentPresentation,
IssueThreadInteractionActorFields,
SuggestedTaskDraft,
SuggestTasksPayload,
@ -475,6 +495,7 @@ export type {
CompanyPortabilityProjectWorkspaceManifestEntry,
CompanyPortabilityIssueRoutineTriggerManifestEntry,
CompanyPortabilityIssueRoutineManifestEntry,
CompanyPortabilityIssueCommentManifestEntry,
CompanyPortabilityIssueManifestEntry,
CompanyPortabilityManifest,
CompanyPortabilityExportResult,
@ -685,6 +706,11 @@ export {
issueReviewRequestSchema,
issueExecutionWorkspaceSettingsSchema,
checkoutIssueSchema,
issueCommentAuthorTypeSchema,
issueCommentPresentationSchema,
issueCommentMetadataRowSchema,
issueCommentMetadataSectionSchema,
issueCommentMetadataSchema,
addIssueCommentSchema,
issueThreadInteractionStatusSchema,
issueThreadInteractionKindSchema,

View file

@ -1,5 +1,7 @@
import type { AgentEnvConfig } from "./secrets.js";
import type { RoutineVariable } from "./routine.js";
import type { IssueCommentAuthorType } from "../constants.js";
import type { IssueCommentMetadata, IssueCommentPresentation } from "./issue.js";
export interface CompanyPortabilityInclude {
company: boolean;
@ -94,6 +96,16 @@ export interface CompanyPortabilityIssueRoutineManifestEntry {
triggers: CompanyPortabilityIssueRoutineTriggerManifestEntry[];
}
export interface CompanyPortabilityIssueCommentManifestEntry {
body: string;
authorType: IssueCommentAuthorType;
authorAgentSlug: string | null;
authorUserId: string | null;
presentation: IssueCommentPresentation | null;
metadata: IssueCommentMetadata | null;
createdAt: string | null;
}
export interface CompanyPortabilityIssueManifestEntry {
slug: string;
identifier: string | null;
@ -112,6 +124,7 @@ export interface CompanyPortabilityIssueManifestEntry {
billingCode: string | null;
executionWorkspaceSettings: Record<string, unknown> | null;
assigneeAdapterOverrides: Record<string, unknown> | null;
comments: CompanyPortabilityIssueCommentManifestEntry[];
metadata: Record<string, unknown> | null;
}

View file

@ -140,6 +140,8 @@ export type {
IssueBlockerAttentionState,
IssueProductivityReview,
IssueProductivityReviewTrigger,
SuccessfulRunHandoffState,
SuccessfulRunHandoffStateKind,
IssueReferenceSource,
IssueRelatedWorkItem,
IssueRelatedWorkSummary,
@ -155,6 +157,16 @@ export type {
IssueReviewRequest,
IssueExecutionDecision,
IssueComment,
IssueCommentMetadata,
IssueCommentMetadataSection,
IssueCommentMetadataRow,
IssueCommentMetadataTextRow,
IssueCommentMetadataCodeRow,
IssueCommentMetadataKeyValueRow,
IssueCommentMetadataIssueLinkRow,
IssueCommentMetadataAgentLinkRow,
IssueCommentMetadataRunLinkRow,
IssueCommentPresentation,
IssueThreadInteractionActorFields,
SuggestedTaskDraft,
SuggestTasksPayload,
@ -296,6 +308,7 @@ export type {
CompanyPortabilityProjectWorkspaceManifestEntry,
CompanyPortabilityIssueRoutineTriggerManifestEntry,
CompanyPortabilityIssueRoutineManifestEntry,
CompanyPortabilityIssueCommentManifestEntry,
CompanyPortabilityIssueManifestEntry,
CompanyPortabilityManifest,
CompanyPortabilityExportResult,

View file

@ -1,4 +1,8 @@
import type {
IssueCommentAuthorType,
IssueCommentMetadataRowType,
IssueCommentPresentationKind,
IssueCommentPresentationTone,
IssueExecutionMonitorClearReason,
IssueExecutionMonitorKind,
IssueExecutionMonitorRecoveryPolicy,
@ -162,6 +166,18 @@ export interface IssueProductivityReview {
updatedAt: Date;
}
export type SuccessfulRunHandoffStateKind = "required" | "resolved" | "escalated";
export interface SuccessfulRunHandoffState {
state: SuccessfulRunHandoffStateKind;
required: boolean;
sourceRunId: string | null;
correctiveRunId: string | null;
assigneeAgentId: string | null;
detectedProgressSummary: string | null;
createdAt: Date | string | null;
}
export interface IssueRelation {
id: string;
companyId: string;
@ -324,6 +340,7 @@ export interface Issue {
blocks?: IssueRelationIssueSummary[];
blockerAttention?: IssueBlockerAttention;
productivityReview?: IssueProductivityReview | null;
successfulRunHandoff?: SuccessfulRunHandoffState | null;
relatedWork?: IssueRelatedWorkSummary;
referencedIssueIdentifiers?: string[];
planDocument?: IssueDocument | null;
@ -346,14 +363,83 @@ export interface IssueComment {
id: string;
companyId: string;
issueId: string;
authorType: IssueCommentAuthorType;
authorAgentId: string | null;
authorUserId: string | null;
body: string;
presentation: IssueCommentPresentation | null;
metadata: IssueCommentMetadata | null;
followUpRequested?: boolean;
createdAt: Date;
updatedAt: Date;
}
interface IssueCommentMetadataRowBase {
type: IssueCommentMetadataRowType;
label?: string | null;
}
export interface IssueCommentMetadataTextRow extends IssueCommentMetadataRowBase {
type: "text";
text: string;
}
export interface IssueCommentMetadataCodeRow extends IssueCommentMetadataRowBase {
type: "code";
code: string;
language?: string | null;
}
export interface IssueCommentMetadataKeyValueRow extends IssueCommentMetadataRowBase {
type: "key_value";
label: string;
value: string;
}
export interface IssueCommentMetadataIssueLinkRow extends IssueCommentMetadataRowBase {
type: "issue_link";
issueId?: string | null;
identifier?: string | null;
title?: string | null;
}
export interface IssueCommentMetadataAgentLinkRow extends IssueCommentMetadataRowBase {
type: "agent_link";
agentId: string;
name?: string | null;
}
export interface IssueCommentMetadataRunLinkRow extends IssueCommentMetadataRowBase {
type: "run_link";
runId: string;
title?: string | null;
}
export type IssueCommentMetadataRow =
| IssueCommentMetadataTextRow
| IssueCommentMetadataCodeRow
| IssueCommentMetadataKeyValueRow
| IssueCommentMetadataIssueLinkRow
| IssueCommentMetadataAgentLinkRow
| IssueCommentMetadataRunLinkRow;
export interface IssueCommentMetadataSection {
title?: string | null;
rows: IssueCommentMetadataRow[];
}
export interface IssueCommentMetadata {
version: 1;
sections: IssueCommentMetadataSection[];
}
export interface IssueCommentPresentation {
kind: IssueCommentPresentationKind;
tone: IssueCommentPresentationTone;
title?: string | null;
detailsDefaultOpen: boolean;
}
export interface IssueThreadInteractionActorFields {
createdByAgentId?: string | null;
createdByUserId?: string | null;

View file

@ -1,5 +1,10 @@
import { z } from "zod";
import { MAX_COMPANY_ATTACHMENT_MAX_BYTES } from "../constants.js";
import {
issueCommentAuthorTypeSchema,
issueCommentMetadataSchema,
issueCommentPresentationSchema,
} from "./issue.js";
import { routineVariableSchema } from "./routine.js";
export const portabilityIncludeSchema = z
@ -131,6 +136,16 @@ export const portabilityIssueRoutineManifestEntrySchema = z.object({
triggers: z.array(portabilityIssueRoutineTriggerManifestEntrySchema).default([]),
});
export const portabilityIssueCommentManifestEntrySchema = z.object({
body: z.string().min(1),
authorType: issueCommentAuthorTypeSchema,
authorAgentSlug: z.string().min(1).nullable(),
authorUserId: z.string().nullable(),
presentation: issueCommentPresentationSchema.nullable(),
metadata: issueCommentMetadataSchema.nullable(),
createdAt: z.string().datetime().nullable(),
});
export const portabilityIssueManifestEntrySchema = z.object({
slug: z.string().min(1),
identifier: z.string().min(1).nullable(),
@ -149,6 +164,7 @@ export const portabilityIssueManifestEntrySchema = z.object({
billingCode: z.string().nullable(),
executionWorkspaceSettings: z.record(z.unknown()).nullable(),
assigneeAdapterOverrides: z.record(z.unknown()).nullable(),
comments: z.array(portabilityIssueCommentManifestEntrySchema).default([]),
metadata: z.record(z.unknown()).nullable(),
});

View file

@ -157,6 +157,11 @@ export {
issueReviewRequestSchema,
issueExecutionWorkspaceSettingsSchema,
checkoutIssueSchema,
issueCommentAuthorTypeSchema,
issueCommentPresentationSchema,
issueCommentMetadataRowSchema,
issueCommentMetadataSectionSchema,
issueCommentMetadataSchema,
addIssueCommentSchema,
issueThreadInteractionStatusSchema,
issueThreadInteractionKindSchema,

View file

@ -54,6 +54,46 @@ describe("issue validators", () => {
expect(parsed.body).toBe("Progress update\n\nNext action.");
});
it("accepts structured issue comment presentation and metadata", () => {
const parsed = addIssueCommentSchema.parse({
body: "Paperclip needs a disposition before this issue can continue.",
authorType: "system",
presentation: {
kind: "system_notice",
tone: "warning",
title: "Needs disposition",
},
metadata: {
version: 1,
sections: [
{
title: "Evidence",
rows: [
{ type: "key_value", label: "Cause", value: "successful_run_missing_state" },
{ type: "issue_link", label: "Source issue", identifier: "PAP-3440" },
{ type: "run_link", label: "Run", runId: "11111111-1111-4111-8111-111111111111" },
],
},
],
},
});
expect(parsed.presentation?.detailsDefaultOpen).toBe(false);
expect(parsed.metadata?.sections[0]?.rows).toHaveLength(3);
});
it("rejects arbitrary issue comment metadata", () => {
const parsed = addIssueCommentSchema.safeParse({
body: "Hidden details",
metadata: {
version: 1,
transcript: "raw log dump",
},
});
expect(parsed.success).toBe(false);
});
it("normalizes escaped line breaks in generated task drafts", () => {
const parsed = suggestedTaskDraftSchema.parse({
clientKey: "task-1",

View file

@ -8,6 +8,10 @@ import {
ISSUE_EXECUTION_POLICY_MODES,
ISSUE_EXECUTION_STAGE_TYPES,
ISSUE_EXECUTION_STATE_STATUSES,
ISSUE_COMMENT_AUTHOR_TYPES,
ISSUE_COMMENT_METADATA_ROW_TYPES,
ISSUE_COMMENT_PRESENTATION_KINDS,
ISSUE_COMMENT_PRESENTATION_TONES,
ISSUE_MONITOR_SCHEDULED_BY,
ISSUE_PRIORITIES,
clampIssueRequestDepth,
@ -233,8 +237,95 @@ export const checkoutIssueSchema = z.object({
export type CheckoutIssue = z.infer<typeof checkoutIssueSchema>;
const commentMetadataLabelSchema = z.string().trim().min(1).max(120);
const commentMetadataTextSchema = z.string().trim().min(1).max(2000);
export const issueCommentAuthorTypeSchema = z.enum(ISSUE_COMMENT_AUTHOR_TYPES);
export const issueCommentPresentationSchema = z.object({
kind: z.enum(ISSUE_COMMENT_PRESENTATION_KINDS).default("message"),
tone: z.enum(ISSUE_COMMENT_PRESENTATION_TONES).default("neutral"),
title: z.string().trim().min(1).max(160).nullable().optional(),
detailsDefaultOpen: z.boolean().optional().default(false),
}).strict();
export type IssueCommentPresentation = z.infer<typeof issueCommentPresentationSchema>;
const issueCommentMetadataBaseRowSchema = z.object({
type: z.enum(ISSUE_COMMENT_METADATA_ROW_TYPES),
label: commentMetadataLabelSchema.nullable().optional(),
});
const issueCommentMetadataTextRowSchema = issueCommentMetadataBaseRowSchema.extend({
type: z.literal("text"),
text: commentMetadataTextSchema,
}).strict();
const issueCommentMetadataCodeRowSchema = issueCommentMetadataBaseRowSchema.extend({
type: z.literal("code"),
code: z.string().min(1).max(4000),
language: z.string().trim().min(1).max(40).nullable().optional(),
}).strict();
const issueCommentMetadataKeyValueRowSchema = issueCommentMetadataBaseRowSchema.extend({
type: z.literal("key_value"),
label: commentMetadataLabelSchema,
value: commentMetadataTextSchema,
}).strict();
const issueCommentMetadataIssueLinkRowSchema = issueCommentMetadataBaseRowSchema.extend({
type: z.literal("issue_link"),
issueId: z.string().uuid().nullable().optional(),
identifier: z.string().trim().min(1).max(80).nullable().optional(),
title: z.string().trim().min(1).max(240).nullable().optional(),
}).strict();
const issueCommentMetadataAgentLinkRowSchema = issueCommentMetadataBaseRowSchema.extend({
type: z.literal("agent_link"),
agentId: z.string().uuid(),
name: z.string().trim().min(1).max(160).nullable().optional(),
}).strict();
const issueCommentMetadataRunLinkRowSchema = issueCommentMetadataBaseRowSchema.extend({
type: z.literal("run_link"),
runId: z.string().uuid(),
title: z.string().trim().min(1).max(160).nullable().optional(),
}).strict();
export const issueCommentMetadataRowSchema = z.discriminatedUnion("type", [
issueCommentMetadataTextRowSchema,
issueCommentMetadataCodeRowSchema,
issueCommentMetadataKeyValueRowSchema,
issueCommentMetadataIssueLinkRowSchema,
issueCommentMetadataAgentLinkRowSchema,
issueCommentMetadataRunLinkRowSchema,
]).superRefine((value, ctx) => {
if (value.type === "issue_link" && !value.issueId && !value.identifier) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Issue link rows require issueId or identifier",
path: ["issueId"],
});
}
});
export const issueCommentMetadataSectionSchema = z.object({
title: z.string().trim().min(1).max(160).nullable().optional(),
rows: z.array(issueCommentMetadataRowSchema).min(1).max(50),
}).strict();
export const issueCommentMetadataSchema = z.object({
version: z.literal(1),
sections: z.array(issueCommentMetadataSectionSchema).min(1).max(20),
}).strict();
export type IssueCommentMetadata = z.infer<typeof issueCommentMetadataSchema>;
export const addIssueCommentSchema = z.object({
body: multilineTextSchema.pipe(z.string().min(1)),
authorType: issueCommentAuthorTypeSchema.optional(),
presentation: issueCommentPresentationSchema.nullable().optional(),
metadata: issueCommentMetadataSchema.nullable().optional(),
reopen: z.boolean().optional(),
resume: z.boolean().optional(),
interrupt: z.boolean().optional(),