Add pipeline workflow primitives and operator UI (#7903)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The pipeline subsystem models repeatable work as items moving
through stages, with agent automation, review gates, blockers, drift
notices, and linked work.
> - Operators need this to be usable as one coherent workflow surface,
not just as backend primitives or disconnected route experiments.
> - The branch now carries the pipeline data model, service/routes,
CLI/tutorial path, aggregation feeds, operator UI, stage automation
controls, liveness/retry handling, and follow-up polish that make the
primitive reviewable end to end.
> - This pull request is the single review target for that pipeline
workflow primitive stack.
> - The benefit is that reviewers can evaluate the full operator
experience and server contract together against `master`.

## Linked Issues or Issue Description

No public GitHub issue exists for this work. The underlying feature
request is described inline.

### Problem or motivation

Paperclip needs a first-class way to model multi-stage agent/company
workflows where upstream items can spawn downstream work, request
review, carry fields across pipelines, surface drift, retry automation,
and show operators where work is blocked or active. Without a unified
pipeline primitive, these workflows spread across ad hoc issues,
routines, and comments, making the state hard to inspect or operate.

### Proposed solution

Add the pipeline workflow primitive stack: database schema and
migrations, shared validators/types, server services and REST routes,
aggregation and liveness helpers, CLI/tutorial smoke support, and the
React operator UI for pipeline lists, boards, item detail,
review/learnings views, settings, stage automation, secrets, carry-over
fields, and retry/recovery flows.

### Alternatives considered

- Keep workflows as loosely linked issues and routines: rejected because
operators need a single board/detail/settings surface for repeated
workflow patterns.
- Ship backend primitives first and defer UI: rejected for this branch
because the operator experience is the main way to validate the
primitive.
- Add a narrower one-off content workflow: rejected because the same
primitives are useful across future company processes.

## What Changed

- Added and evolved pipeline schema, migrations, shared contracts,
server services, REST routes, route tests, and CLI/tutorial smoke
support.
- Added pipeline aggregation, health/liveness, drift acknowledgment,
blocker/carry-over, automation retry, stage automation environment, and
permission recovery behavior.
- Added the operator UI for pipeline index/board/item
detail/settings/review/learnings flows, including stage secrets,
automation controls, markdown/item descriptions, linked issue assets,
liveness banners, and source automation metadata.
- Refactored issue document frame rendering through the shared
`DocumentFrameHeader` component to keep document controls consistent
with the pipeline document surfaces.
- Kept this PR as the single base-branch review target for the current
pipeline branch.

## Verification

Current branch refresh:

- `pnpm vitest run server/src/__tests__/pipelines-service.test.ts` — 31
passed
- `pnpm vitest run server/src/__tests__/pipelines-routes.test.ts` — 19
passed
- `pnpm --filter ./server typecheck` — passed
- `pnpm --filter ./ui typecheck` — passed
- Verified Pipelines remains gated by `enablePipelines === true`:
sidebar item is hidden unless the flag is enabled, direct pipeline
routes redirect to `/dashboard` when disabled, and the Experimental
settings UI still has no Pipelines toggle.
- GitHub status checks on `df071c710646de625131064c3fb6588b5e97964a` —
all complete with no failing conclusions, including Actions, Socket,
Superagent/Security, and Greptile Review
- Greptile summary on `df071c710646de625131064c3fb6588b5e97964a` —
Confidence Score 5/5
- GitHub review-thread sweep — 0 unresolved Greptile threads

Previously recorded during branch development:

- Server pipeline service/route and aggregation tests
- Shared validator tests
- UI pipeline page/settings/item-detail/learnings/liveness tests
- Pipeline tutorial smoke path

## Risks

- High review surface: this is a large feature branch spanning database,
shared contracts, server behavior, CLI/docs, and UI.
- Migration ordering and schema compatibility need reviewer attention
because this branch has been kept current across multiple `master`
syncs.
- GitHub still reports merge state `BLOCKED` because the PR is awaiting
normal human review/branch-protection completion; all current status
checks are green.
- Branch-name checklist exception: this PR uses the pre-existing
requested branch name, which predates the current public-branch naming
rule. The PR title/body avoid internal issue references.

> 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 coding agent based on GPT-5, with repository tool use,
shell execution, git/GitHub CLI operations, and local verification
commands. Earlier commits in this branch were assisted by Paperclip
agents and other AI coding agents as recorded in commit authorship.

## 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)
- [ ] 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>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-06-26 12:02:44 -05:00
1 parent c79d347abe
commit 43b005b704
94 files changed
+51184 -251

No files matched your search

+6 -1
View File
@@ -331,7 +331,11 @@ export const ISSUE_TREE_HOLD_RELEASE_POLICY_STRATEGIES = ["manual", "after_activ
export type IssueTreeHoldReleasePolicyStrategy = (typeof ISSUE_TREE_HOLD_RELEASE_POLICY_STRATEGIES)[number];
export const ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY = "continuation-summary" as const;
export const SYSTEM_ISSUE_DOCUMENT_KEYS = [ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY] as const;
export const PIPELINE_CASE_BODY_DOCUMENT_KEY = "pipeline-case-body" as const;
export const SYSTEM_ISSUE_DOCUMENT_KEYS = [
ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY,
PIPELINE_CASE_BODY_DOCUMENT_KEY,
] as const;
export type SystemIssueDocumentKey = (typeof SYSTEM_ISSUE_DOCUMENT_KEYS)[number];
const SYSTEM_ISSUE_DOCUMENT_KEY_SET = new Set<string>(SYSTEM_ISSUE_DOCUMENT_KEYS);
@@ -786,6 +790,7 @@ export const PERMISSION_KEYS = [
"tasks:assign",
"tasks:assign_scope",
"tasks:manage_active_checkouts",
"pipelines:write",
"joins:approve",
] as const;
export type PermissionKey = (typeof PERMISSION_KEYS)[number];
+64
View File
@@ -14,6 +14,55 @@ export {
type AgentOrgChainInvalidReason,
type AgentWorkEligibility,
} from "./agent-eligibility.js";
export {
computePipelineHealth,
groupWarningsByStage,
isPipelineTerminalStageKind,
type PipelineHealthAgentRef,
type PipelineHealthFailedAutomationInput,
type PipelineHealthInput,
type PipelineHealthPipelineRef,
type PipelineHealthReport,
type PipelineHealthStageInput,
type PipelineHealthStageRef,
type PipelineHealthWarning,
type PipelineHealthWarningCode,
} from "./pipeline-health.js";
export {
caseTypeMatchesPipeline,
deriveCaseType,
type CaseTypePipelineRef,
} from "./pipeline-case-type.js";
export type {
PipelineAutomationRetryBlocker,
PipelineAutomationRetryCleanupOptions,
PipelineAutomationRetryEffectCounts,
PipelineAutomationRetryPlan,
PipelineAutomationRetryRequest,
PipelineAutomationRetryRoutineRef,
PipelineAutomationRetryScope,
PipelineAutomationRetryStageRef,
PipelineCaseAttachmentOutputItem,
PipelineCaseConversationSource,
PipelineCaseConversationSourceKind,
PipelineCaseConversationSourceLinkRole,
PipelineCaseConversationSourceReason,
PipelineCaseDocumentOutputItem,
PipelineCaseDocumentPayload,
PipelineCaseDocumentRevision,
PipelineCaseLiveness,
PipelineCaseLivenessState,
PipelineCaseOutputContextSummary,
PipelineCaseOutputContextSummaryItem,
PipelineCaseOutputItem,
PipelineCaseOutputItemBase,
PipelineCaseOutputKind,
PipelineCaseOutputSource,
PipelineCaseOutputSourceRole,
PipelineCaseOutputsResponse,
PipelineCaseWorkProductOutputItem,
PipelineStageAutomation,
} from "./types/pipeline.js";
export {
asBoolean,
asString,
@@ -86,6 +135,7 @@ export {
ISSUE_TREE_HOLD_RELEASE_POLICY_STRATEGIES,
ISSUE_TREE_HOLD_STATUSES,
ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY,
PIPELINE_CASE_BODY_DOCUMENT_KEY,
SYSTEM_ISSUE_DOCUMENT_KEYS,
isSystemIssueDocumentKey,
ISSUE_REFERENCE_SOURCE_KINDS,
@@ -1219,6 +1269,15 @@ export {
updateRoutineTriggerSchema,
routineVariableSchema,
runRoutineSchema,
pipelineAutomationRetryCleanupOptionsSchema,
pipelineAutomationRetryRequestSchema,
pipelineAutomationRetryScopeSchema,
pipelineStageAutomationSchema,
pipelineStageApproverSchema,
pipelineStageConfigSchema,
pipelineStageKindSchema,
pipelineStageOnEnterSchema,
pipelineStageVariableSchema,
rotateRoutineTriggerSecretSchema,
routineRevisionSnapshotRoutineV1Schema,
routineRevisionSnapshotTriggerV1Schema,
@@ -1411,22 +1470,27 @@ export {
ROUTINE_MENTION_SCHEME,
SKILL_MENTION_SCHEME,
USER_MENTION_SCHEME,
PIPELINE_MENTION_SCHEME,
buildAgentMentionHref,
buildPipelineMentionHref,
buildProjectMentionHref,
buildRoutineMentionHref,
buildSkillMentionHref,
buildUserMentionHref,
extractAgentMentionIds,
extractPipelineMentions,
extractProjectMentionIds,
extractRoutineMentionIds,
extractSkillMentionIds,
extractUserMentionIds,
parseAgentMentionHref,
parsePipelineMentionHref,
parseProjectMentionHref,
parseRoutineMentionHref,
parseSkillMentionHref,
parseUserMentionHref,
type ParsedAgentMention,
type ParsedPipelineMention,
type ParsedProjectMention,
type ParsedRoutineMention,
type ParsedSkillMention,
+34
View File
@@ -0,0 +1,34 @@
/**
* Derived `caseType`.
*
* A case's "type" is not a field anyone fills in — it is simply *which pipeline
* the case lives in* (one pipeline per kind of thing). We derive it from the
* pipeline so it can be used internally for display and ingest sanity-checks
* without any new user-facing field or lifecycle machinery.
*
* The pipeline key is a stable slug and is the canonical type identifier; we
* fall back to the pipeline id if a key is somehow absent.
*/
export interface CaseTypePipelineRef {
id: string;
key?: string | null;
}
export function deriveCaseType(pipeline: CaseTypePipelineRef): string {
const key = typeof pipeline.key === "string" ? pipeline.key.trim() : "";
return key || pipeline.id;
}
/**
* Ingest sanity-check: a case being ingested into a pipeline must match that
* pipeline's derived type. Returns true when the (optional) declared type is
* absent or already agrees with the pipeline — i.e. nothing to correct.
*/
export function caseTypeMatchesPipeline(
declaredCaseType: string | null | undefined,
pipeline: CaseTypePipelineRef,
): boolean {
if (declaredCaseType == null || declaredCaseType === "") return true;
return declaredCaseType === deriveCaseType(pipeline);
}
+366
View File
@@ -0,0 +1,366 @@
import { isAgentStatusInvokable } from "./agent-eligibility.js";
import { extractPipelineMentions } from "./project-mentions.js";
/**
* Setup-health warnings for pipelines.
*
* The goal is to warn — in plain, Zapier-level language with zero technical
* vocabulary — about any configuration that simply will not run, *before*
* someone discovers it mid-workflow. The copy here intentionally avoids words
* like "routine", "dispatch", or "JWT": a paused agent is "a paused teammate",
* a routine is "the instructions for this step", and so on.
*
* This module is a pure function so it can be unit-tested and shared between the
* server (which assembles the inputs from the database) and the UI.
*/
export type PipelineHealthWarningCode =
| "paused_agent"
| "stage_no_automation"
| "automation_no_instructions"
| "automation_no_agent"
| "automation_failed"
| "review_no_approver"
| "missing_pipeline_reference"
| "missing_stage_reference"
| "breakdown_target_missing"
| "breakdown_no_wait"
| "breakdown_target_not_entry_safe"
| "breakdown_field_mismatch"
| "unset_required_variable";
export interface PipelineHealthWarning {
/** Machine-readable reason; UI keys icons/grouping off this. */
code: PipelineHealthWarningCode;
/** The stage the warning is anchored to. */
stageId: string;
stageKey: string;
stageName: string;
/** Plain-language, prosumer-safe message ready to render as-is. */
message: string;
/** Optional UI route for the next useful place to inspect or fix the warning. */
href?: string;
hrefLabel?: string;
}
export interface PipelineHealthReport {
pipelineId: string;
warnings: PipelineHealthWarning[];
/** Convenience: true when there are no warnings at all. */
ok: boolean;
}
export interface PipelineHealthAgentRef {
id: string;
name?: string | null;
status: string;
}
export interface PipelineHealthStageRef {
key: string;
name: string;
kind?: string;
config?: Record<string, unknown> | null;
}
export interface PipelineHealthPipelineRef {
id: string;
name: string;
stages: PipelineHealthStageRef[];
}
export interface PipelineHealthStageInput {
id: string;
key: string;
name: string;
kind: string;
config: Record<string, unknown> | null | undefined;
/** Latest instructions body for the stage ("" when there are none). */
instructionsBody?: string | null;
}
export interface PipelineHealthFailedAutomationInput {
stageId: string;
stageKey: string;
stageName: string;
caseId: string;
caseTitle: string;
error?: string | null;
}
export interface PipelineHealthInput {
pipelineId: string;
stages: PipelineHealthStageInput[];
/** Every agent in the company, keyed by id, for invokability + name lookup. */
agentsById: Record<string, PipelineHealthAgentRef>;
/** Every pipeline in the company, keyed by id, for validating `/pipeline:` references. */
pipelinesById: Record<string, PipelineHealthPipelineRef>;
/** Failed stage automation still affecting live items in this pipeline. */
failedAutomations?: PipelineHealthFailedAutomationInput[];
}
type StageConfig = {
assigneeAgentId?: unknown;
automation?: unknown;
autoAdvanceOnChildrenTerminal?: unknown;
breakdown?: unknown;
onEnter?: unknown;
requireApproval?: unknown;
requireChildrenTerminal?: unknown;
approver?: { kind?: unknown; id?: unknown } | null;
variables?: unknown;
[key: string]: unknown;
};
export function isPipelineTerminalStageKind(kind: string | null | undefined): boolean {
return kind === "done" || kind === "cancelled";
}
function asConfig(config: PipelineHealthStageInput["config"]): StageConfig {
if (!config || typeof config !== "object" || Array.isArray(config)) return {};
return config as StageConfig;
}
function agentLabel(agent: PipelineHealthAgentRef | undefined): string {
const name = agent?.name?.trim();
return name && name.length > 0 ? name : "a teammate";
}
function hasOnEnterRoutineAutomation(config: StageConfig): boolean {
const onEnter = config.onEnter;
if (!onEnter || typeof onEnter !== "object" || Array.isArray(onEnter)) return false;
const record = onEnter as Record<string, unknown>;
return record.type === "run_routine" && typeof record.routineId === "string" && record.routineId.trim().length > 0;
}
function hasChildrenGateAutoAdvance(config: StageConfig): boolean {
const breakdown = readBreakdownConfig(config);
if (breakdown) return breakdown.waitForPieces && breakdown.whenFinishedMoveTo !== null;
return config.requireChildrenTerminal === true &&
typeof config.autoAdvanceOnChildrenTerminal === "string" &&
config.autoAdvanceOnChildrenTerminal.trim().length > 0;
}
/** True when a stage has saved automation that can move work forward. */
function hasRunnableStageAutomation(config: StageConfig): boolean {
return readBreakdownConfig(config) !== null || hasOnEnterRoutineAutomation(config) || hasChildrenGateAutoAdvance(config);
}
function automationAssigneeAgentId(config: StageConfig): string | null {
const automation = config.automation;
if (automation && typeof automation === "object" && !Array.isArray(automation)) {
const value = (automation as Record<string, unknown>).assigneeAgentId;
if (typeof value === "string" && value.trim()) return value.trim();
}
return typeof config.assigneeAgentId === "string" && config.assigneeAgentId.trim()
? config.assigneeAgentId.trim()
: null;
}
function readBreakdownConfig(config: StageConfig) {
const raw = config.breakdown;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
const record = raw as Record<string, unknown>;
const targetPipelineId = typeof record.targetPipelineId === "string" && record.targetPipelineId.trim()
? record.targetPipelineId.trim()
: null;
const targetStageKey = typeof record.targetStageKey === "string" && record.targetStageKey.trim()
? record.targetStageKey.trim()
: null;
const pieceNoun = typeof record.pieceNoun === "string" && record.pieceNoun.trim()
? record.pieceNoun.trim()
: "piece";
const inheritFields = Array.isArray(record.inheritFields)
? record.inheritFields.filter((field): field is string => typeof field === "string" && field.trim().length > 0).map((field) => field.trim())
: [];
const whenFinishedMoveTo = typeof record.whenFinishedMoveTo === "string" && record.whenFinishedMoveTo.trim()
? record.whenFinishedMoveTo.trim()
: typeof config.autoAdvanceOnChildrenTerminal === "string" && config.autoAdvanceOnChildrenTerminal.trim()
? config.autoAdvanceOnChildrenTerminal.trim()
: null;
return {
targetPipelineId,
targetStageKey,
pieceNoun,
inheritFields,
waitForPieces: record.waitForPieces === undefined ? config.requireChildrenTerminal === true : record.waitForPieces === true,
whenFinishedMoveTo,
};
}
export function computePipelineHealth(input: PipelineHealthInput): PipelineHealthReport {
const warnings: PipelineHealthWarning[] = [];
for (const stage of input.stages) {
const config = asConfig(stage.config);
const instructionsBody = (stage.instructionsBody ?? "").trim();
const anchor = { stageId: stage.id, stageKey: stage.key, stageName: stage.name };
const assigneeAgentId = automationAssigneeAgentId(config);
const hasStageAutomation = hasRunnableStageAutomation(config);
const isTerminalStage = isPipelineTerminalStageKind(stage.kind);
const breakdown = readBreakdownConfig(config);
// 1. A teammate is assigned to run this step, but they're paused / gone.
if (assigneeAgentId) {
const agent = input.agentsById[assigneeAgentId];
if (!agent) {
warnings.push({
...anchor,
code: "paused_agent",
message: `Assigned to a teammate who's no longer here. Pick someone else to run this step.`,
});
} else if (!isAgentStatusInvokable(agent.status)) {
warnings.push({
...anchor,
code: "paused_agent",
message: `${agentLabel(agent)} is paused, so this step won't run until they're back. Reassign it if you can't wait.`,
});
}
}
// 2. A teammate is assigned but there's nothing for them to do (no instructions).
if (assigneeAgentId && !instructionsBody) {
warnings.push({
...anchor,
code: "automation_no_instructions",
message: `Assigned to a teammate, but there are no instructions yet. Add instructions so this step doesn't stall.`,
});
}
// 3. Instructions exist, but no teammate is assigned to run them.
if (!assigneeAgentId && instructionsBody && !hasStageAutomation && stage.kind !== "review" && !isTerminalStage) {
warnings.push({
...anchor,
code: "automation_no_agent",
message: `This step has instructions, but no agent is assigned. Add an agent to run this step, or make it a review step if a person should decide.`,
});
}
// 4. Nothing runs here automatically. This is legal, but must be loud.
if (!assigneeAgentId && !instructionsBody && !hasStageAutomation && stage.kind !== "review" && !isTerminalStage) {
warnings.push({
...anchor,
code: "stage_no_automation",
message: `Nothing runs here automatically — items will sit until a person moves them. Add an agent to run this step, or make it a review step if a person should decide.`,
});
}
// 5. A review step with no one who can actually approve.
if (stage.kind === "review" || config.requireApproval === true) {
const approver = config.approver && typeof config.approver === "object" ? config.approver : null;
const kind = approver && typeof approver.kind === "string" ? approver.kind : "any_human";
const approverId =
approver && typeof approver.id === "string" && approver.id.trim() ? approver.id.trim() : null;
if (kind === "agent") {
const agent = approverId ? input.agentsById[approverId] : undefined;
if (!approverId || !agent) {
warnings.push({
...anchor,
code: "review_no_approver",
message: `No approver picked yet, so work will pile up here. Choose who approves.`,
});
} else if (!isAgentStatusInvokable(agent.status)) {
warnings.push({
...anchor,
code: "review_no_approver",
message: `${agentLabel(agent)} is the approver and they're paused, so nothing can be approved until they're back.`,
});
}
} else if (kind === "user" && !approverId) {
warnings.push({
...anchor,
code: "review_no_approver",
message: `No approver picked yet, so work will pile up here. Choose who approves.`,
});
}
}
// 6. First-class breakdown references. These replace prose scanning on
// breakdown stages because the target workflow is now config, not copy.
if (breakdown) {
const target = breakdown.targetPipelineId ? input.pipelinesById[breakdown.targetPipelineId] : undefined;
const targetStage = breakdown.targetStageKey
? target?.stages.find((s) => s.key === breakdown.targetStageKey)
: undefined;
if (!target || !targetStage) {
warnings.push({
...anchor,
code: "breakdown_target_missing",
message: `This step breaks work into another workflow, but that destination is missing. Pick where the pieces should go.`,
});
} else {
if (!breakdown.waitForPieces || !breakdown.whenFinishedMoveTo) {
warnings.push({
...anchor,
code: "breakdown_no_wait",
message: `This step creates ${breakdown.pieceNoun}s but does not wait for them before moving on. Turn on waiting if the next step depends on the pieces finishing.`,
});
}
const targetConfig = asConfig(targetStage.config);
const firstStage = target.stages[0];
if (
firstStage?.key !== targetStage.key ||
targetStage.kind === "review" ||
isPipelineTerminalStageKind(targetStage.kind) ||
targetConfig.disabled === true ||
targetConfig.requireApproval === true
) {
warnings.push({
...anchor,
code: "breakdown_target_not_entry_safe",
message: `New ${breakdown.pieceNoun}s start in a destination step that may not accept new work cleanly. Choose the entry step for that workflow.`,
});
}
}
} else if (instructionsBody) {
for (const mention of extractPipelineMentions(instructionsBody)) {
const target = input.pipelinesById[mention.pipelineId];
if (!target) {
warnings.push({
...anchor,
code: "missing_pipeline_reference",
message: `These instructions hand off to a workflow that's been deleted. Point them at one that exists.`,
});
continue;
}
if (mention.stageKey && !target.stages.some((s) => s.key === mention.stageKey)) {
warnings.push({
...anchor,
code: "missing_stage_reference",
message: `These instructions hand off to a step that no longer exists in "${target.name}". Point them at one that does.`,
});
}
}
}
// 7. Required stage variables are item inputs, not settings defaults.
// Missing per-item values are validated when work enters or runs through
// the pipeline; a blank default in settings is a normal configuration.
}
for (const failure of input.failedAutomations ?? []) {
warnings.push({
code: "automation_failed",
stageId: failure.stageId,
stageKey: failure.stageKey,
stageName: failure.stageName,
message: `Automation failed on "${failure.caseTitle}". Open the item to inspect the log and retry it.`,
href: `/pipelines/${input.pipelineId}/items/${failure.caseId}`,
hrefLabel: "Open item",
});
}
return { pipelineId: input.pipelineId, warnings, ok: warnings.length === 0 };
}
/** Group a flat warning list by stage id — handy for rendering per-stage badges. */
export function groupWarningsByStage(
warnings: PipelineHealthWarning[],
): Record<string, PipelineHealthWarning[]> {
const byStage: Record<string, PipelineHealthWarning[]> = {};
for (const warning of warnings) {
(byStage[warning.stageId] ??= []).push(warning);
}
return byStage;
}
+50
View File
@@ -3,6 +3,7 @@ export const AGENT_MENTION_SCHEME = "agent://";
export const USER_MENTION_SCHEME = "user://";
export const SKILL_MENTION_SCHEME = "skill://";
export const ROUTINE_MENTION_SCHEME = "routine://";
export const PIPELINE_MENTION_SCHEME = "pipeline://";
const HEX_COLOR_RE = /^[0-9a-f]{6}$/i;
const HEX_COLOR_SHORT_RE = /^[0-9a-f]{3}$/i;
@@ -13,6 +14,7 @@ const AGENT_MENTION_LINK_RE = /\[[^\]]*]\((agent:\/\/[^)\s]+)\)/gi;
const USER_MENTION_LINK_RE = /\[[^\]]*]\((user:\/\/[^)\s]+)\)/gi;
const SKILL_MENTION_LINK_RE = /\[[^\]]*]\((skill:\/\/[^)\s]+)\)/gi;
const ROUTINE_MENTION_LINK_RE = /\[[^\]]*]\((routine:\/\/[^)\s]+)\)/gi;
const PIPELINE_MENTION_LINK_RE = /\[[^\]]*]\((pipeline:\/\/[^)\s]+)\)/gi;
const AGENT_ICON_NAME_RE = /^[a-z0-9-]+$/i;
const SKILL_SLUG_RE = /^[a-z0-9][a-z0-9-]*$/i;
@@ -39,6 +41,11 @@ export interface ParsedRoutineMention {
routineId: string;
}
export interface ParsedPipelineMention {
pipelineId: string;
stageKey: string | null;
}
function normalizeHexColor(input: string | null | undefined): string | null {
if (!input) return null;
const trimmed = input.trim();
@@ -197,6 +204,32 @@ export function parseRoutineMentionHref(href: string): ParsedRoutineMention | nu
return { routineId };
}
export function buildPipelineMentionHref(pipelineId: string, stageKey?: string | null): string {
const trimmedPipelineId = pipelineId.trim();
const normalizedStageKey = stageKey?.trim();
if (!normalizedStageKey) return `${PIPELINE_MENTION_SCHEME}${trimmedPipelineId}`;
return `${PIPELINE_MENTION_SCHEME}${trimmedPipelineId}?stage=${encodeURIComponent(normalizedStageKey)}`;
}
export function parsePipelineMentionHref(href: string): ParsedPipelineMention | null {
if (!href.startsWith(PIPELINE_MENTION_SCHEME)) return null;
let url: URL;
try {
url = new URL(href);
} catch {
return null;
}
if (url.protocol !== "pipeline:") return null;
const pipelineId = `${url.hostname}${url.pathname}`.replace(/^\/+/, "").trim();
if (!pipelineId) return null;
const stageKey = url.searchParams.get("stage")?.trim() || null;
return { pipelineId, stageKey };
}
export function extractProjectMentionIds(markdown: string): string[] {
if (!markdown) return [];
const ids = new Set<string>();
@@ -257,6 +290,23 @@ export function extractRoutineMentionIds(markdown: string): string[] {
return [...ids];
}
export function extractPipelineMentions(markdown: string): ParsedPipelineMention[] {
if (!markdown) return [];
const seen = new Set<string>();
const mentions: ParsedPipelineMention[] = [];
const re = new RegExp(PIPELINE_MENTION_LINK_RE);
let match: RegExpExecArray | null;
while ((match = re.exec(markdown)) !== null) {
const parsed = parsePipelineMentionHref(match[1]);
if (!parsed) continue;
const key = `${parsed.pipelineId}:${parsed.stageKey ?? ""}`;
if (seen.has(key)) continue;
seen.add(key);
mentions.push(parsed);
}
return mentions;
}
function normalizeAgentIcon(input: string | null | undefined): string | null {
if (!input) return null;
const trimmed = input.trim().toLowerCase();
+1
View File
@@ -48,6 +48,7 @@ export interface InstanceExperimentalSettings {
enableEnvironments: boolean;
enableIsolatedWorkspaces: boolean;
enableStreamlinedLeftNavigation: boolean;
enablePipelines: boolean;
enableConferenceRoomChat: boolean;
enableTaskWatchdogs: boolean;
enableIssuePlanDecompositions: boolean;
+324
View File
@@ -0,0 +1,324 @@
import type { Issue } from "./issue.js";
import type { RoutineEnvConfig } from "./routine.js";
import type { ExecutionWorkspaceMode, IssueExecutionWorkspaceSettings } from "./workspace-runtime.js";
import type { SourceTrustMetadata } from "../trust-policy.js";
export type PipelineCaseConversationSourceReason =
| "producer_update"
| "producer_create"
| "automation_link"
| "conversation_link"
| "work_link";
export type PipelineCaseConversationSourceLinkRole = "automation" | "conversation" | "work";
export type PipelineCaseConversationSourceKind =
| "explicit_conversation"
| "own_producer"
| "inherited_parent_producer";
export interface PipelineCaseConversationSource {
issue: Issue;
kind: PipelineCaseConversationSourceKind;
isActive: boolean;
reason: PipelineCaseConversationSourceReason;
linkRole?: PipelineCaseConversationSourceLinkRole | null;
sourceRunId?: string | null;
}
export interface PipelineStageAutomation {
routineId: string;
assigneeAgentId: string | null;
instructionsBody: string;
projectId: string | null;
projectWorkspaceId: string | null;
executionWorkspaceId: string | null;
executionWorkspacePreference: ExecutionWorkspaceMode | null;
executionWorkspaceSettings: IssueExecutionWorkspaceSettings | null;
env: RoutineEnvConfig | null;
latestRoutineRevisionId: string | null;
latestRoutineRevisionNumber: number;
}
export type PipelineCaseLivenessState = "terminal" | "live" | "waiting" | "blocked" | "attention";
export interface PipelineCaseLiveness {
state: PipelineCaseLivenessState;
reason:
| "terminal"
| "lease_active"
| "linked_issue_active"
| "linked_issue_waiting"
| "linked_issue_blocked"
| "case_blocked"
| "automation_failed"
| "permission_preflight_failed"
| "breakdown_pending"
| "breakdown_incomplete"
| "children_waiting"
| "review_waiting"
| "no_action_path";
message: string;
issue?: {
id: string;
identifier: string | null;
title: string;
status: string;
} | null;
blocker?: {
caseId?: string | null;
issueId?: string | null;
title?: string | null;
status?: string | null;
terminalKind?: string | null;
} | null;
automation?: {
automationId?: string | null;
routineId?: string | null;
executionId?: string | null;
error?: string | null;
fingerprint?: string | null;
} | null;
breakdown?: {
expectedRequestKeys?: string[];
createdRequestKeys?: string[];
missingRequestKeys?: string[];
} | null;
}
export type PipelineAutomationRetryScope = "current_stage" | "previous_stage";
export interface PipelineAutomationRetryCleanupOptions {
retireDirectChildren: boolean;
retireDescendants: boolean;
cancelLinkedAutomationIssues: boolean;
}
export interface PipelineAutomationRetryStageRef {
id: string;
key: string;
name: string;
}
export interface PipelineAutomationRetryRoutineRef {
id: string;
title: string;
assigneeAgentId: string | null;
assigneeAgent: {
id: string;
name: string;
role: string;
title: string | null;
} | null;
}
export interface PipelineAutomationRetryEffectCounts {
directChildren: number;
descendants: number;
linkedAutomationIssues: number;
activeDescendants: number;
unresolvedBlockers: number;
}
export interface PipelineAutomationRetryBlocker {
kind:
| "automation_not_configured"
| "previous_stage_not_found"
| "target_stage_not_eligible"
| "target_case_terminal"
| "target_pipeline_archived"
| "active_descendants"
| "unresolved_blockers"
| "permission_preflight_failed";
message: string;
caseIds?: string[];
issueIds?: string[];
details?: Record<string, unknown>;
}
export interface PipelineAutomationRetryPlan {
caseId: string;
scope: PipelineAutomationRetryScope;
allowed: boolean;
caseVersion: number;
currentStage: PipelineAutomationRetryStageRef;
targetStage: PipelineAutomationRetryStageRef | null;
availableTargetStages: PipelineAutomationRetryStageRef[];
automationId: string | null;
routine: PipelineAutomationRetryRoutineRef | null;
previousAttemptId: string | null;
generation: number;
effectCounts: PipelineAutomationRetryEffectCounts;
defaultCleanup: PipelineAutomationRetryCleanupOptions;
blockers: PipelineAutomationRetryBlocker[];
}
export interface PipelineAutomationRetryRequest {
scope: PipelineAutomationRetryScope;
targetStageId?: string | null;
expectedVersion: number;
cleanup: PipelineAutomationRetryCleanupOptions;
}
export interface PipelineCaseDocumentPayload {
link: {
key: string;
documentId: string;
caseId: string;
[key: string]: unknown;
};
document: {
id: string;
title: string | null;
format: string;
latestBody: string;
latestRevisionId: string | null;
latestRevisionNumber: number;
[key: string]: unknown;
};
revision?: {
id: string;
body?: string | null;
title?: string | null;
revisionNumber?: number;
[key: string]: unknown;
} | null;
}
export interface PipelineCaseDocumentRevision {
id: string;
companyId: string;
documentId: string;
caseId: string;
key: string;
revisionNumber: number;
title: string | null;
format: string;
body: string;
changeSummary: string | null;
createdByAgentId: string | null;
createdByUserId: string | null;
createdAt: Date | string;
}
export type PipelineCaseOutputSourceRole = "origin" | "conversation" | "work" | "automation";
export type PipelineCaseOutputKind = "document" | "work_product" | "attachment";
export interface PipelineCaseOutputSource {
linkId: string;
role: PipelineCaseOutputSourceRole;
issueId: string;
issueIdentifier: string | null;
issueTitle: string;
issueStatus: string;
sourceTrust?: SourceTrustMetadata | null;
createdByRunId: string | null;
linkedAt: Date | string;
}
export interface PipelineCaseOutputItemBase {
id: string;
kind: PipelineCaseOutputKind;
title: string;
sourceIssueId: string;
sourceIssueIdentifier: string | null;
sourceIssuePath: string;
sourceIssueTitle: string;
sourceIssueStatus: string;
sourceRole: PipelineCaseOutputSourceRole;
sourceTrust?: SourceTrustMetadata | null;
sourceRunId: string | null;
sourceAgentId: string | null;
preview: string | null;
createdAt: Date | string;
updatedAt: Date | string;
}
export interface PipelineCaseDocumentOutputItem extends PipelineCaseOutputItemBase {
kind: "document";
documentId: string;
documentKey: string;
documentTitle: string | null;
format: string;
latestRevisionId: string | null;
latestRevisionNumber: number;
documentPath: string;
}
export interface PipelineCaseWorkProductOutputItem extends PipelineCaseOutputItemBase {
kind: "work_product";
workProductId: string;
type: string;
provider: string;
externalId: string | null;
url: string | null;
status: string;
reviewState: string;
isPrimary: boolean;
healthStatus: string;
summary: string | null;
metadata: Record<string, unknown> | null;
}
export interface PipelineCaseAttachmentOutputItem extends PipelineCaseOutputItemBase {
kind: "attachment";
attachmentId: string;
assetId: string;
filename: string | null;
contentType: string;
byteSize: number;
contentPath: string;
openPath: string;
downloadPath: string;
}
export type PipelineCaseOutputItem =
| PipelineCaseDocumentOutputItem
| PipelineCaseWorkProductOutputItem
| PipelineCaseAttachmentOutputItem;
export interface PipelineCaseOutputsResponse {
caseId: string;
pipelineId: string;
generatedAt: Date | string;
sources: PipelineCaseOutputSource[];
items: PipelineCaseOutputItem[];
counts: {
documents: number;
workProducts: number;
attachments: number;
bySourceRole: Partial<Record<PipelineCaseOutputSourceRole, number>>;
};
}
export interface PipelineCaseOutputContextSummaryItem {
id: string;
kind: PipelineCaseOutputKind;
title: string;
key: string | null;
revisionId: string | null;
revisionNumber: number | null;
sourceIssue: {
id: string;
identifier: string | null;
title: string;
status: string;
path: string;
role: PipelineCaseOutputSourceRole;
};
sourceRunId: string | null;
sourceAgentId: string | null;
sourceTrust?: SourceTrustMetadata | null;
excerpt: string | null;
excerptTruncated: boolean;
fetchHint: string;
}
export interface PipelineCaseOutputContextSummary {
generatedAt: Date | string;
itemCount: number;
totalItemCount: number;
omittedItemCount: number;
excerptMaxChars: number;
redactionNote: string;
items: PipelineCaseOutputContextSummaryItem[];
}
+13
View File
@@ -9,6 +9,7 @@ import type {
RoutineVariableType,
} from "../constants.js";
import type { EnvBinding } from "./secrets.js";
import type { ExecutionWorkspaceMode, IssueExecutionWorkspaceSettings } from "./workspace-runtime.js";
export interface RoutineDescriptionDocument {
id: string;
@@ -79,6 +80,8 @@ export interface Routine {
status: string;
concurrencyPolicy: string;
catchUpPolicy: string;
originKind?: string;
originId?: string | null;
variables: RoutineVariable[];
env?: RoutineEnvConfig | null;
latestRevisionId: string | null;
@@ -119,6 +122,8 @@ export interface RoutineRevisionSnapshotRoutineV1 {
status: RoutineStatus;
concurrencyPolicy: RoutineConcurrencyPolicy;
catchUpPolicy: RoutineCatchUpPolicy;
originKind?: string;
originId?: string | null;
variables: RoutineVariable[];
env: RoutineEnvConfig | null;
}
@@ -230,6 +235,14 @@ export interface RoutineExecutionIssueOrigin {
runId: string | null;
}
export interface RoutineRunWorkspaceContext {
projectId?: string | null;
projectWorkspaceId?: string | null;
executionWorkspaceId?: string | null;
executionWorkspacePreference?: ExecutionWorkspaceMode | null;
executionWorkspaceSettings?: IssueExecutionWorkspaceSettings | null;
}
export interface RoutineListItem extends Routine {
triggers: Pick<RoutineTrigger, "id" | "kind" | "label" | "enabled" | "cronExpression" | "timezone" | "nextRunAt" | "lastFiredAt" | "lastResult">[];
lastRun: RoutineRunSummary | null;
+21
View File
@@ -506,6 +506,27 @@ export {
type CreateAssetImageMetadata,
} from "./asset.js";
export {
pipelineAutomationRetryCleanupOptionsSchema,
pipelineAutomationRetryRequestSchema,
pipelineAutomationRetryScopeSchema,
pipelineStageAutomationSchema,
pipelineStageApproverSchema,
pipelineStageConfigSchema,
pipelineStageKindSchema,
pipelineStageOnEnterSchema,
pipelineStageVariableSchema,
type PipelineAutomationRetryCleanupOptions,
type PipelineAutomationRetryRequest,
type PipelineAutomationRetryScope,
type PipelineStageAutomationConfig,
type PipelineStageApprover,
type PipelineStageConfig,
type PipelineStageKind,
type PipelineStageOnEnter,
type PipelineStageVariable,
} from "./pipeline.js";
export {
createCompanyInviteSchema,
createOpenClawInvitePromptSchema,
@@ -42,6 +42,7 @@ export const instanceExperimentalSettingsSchema = z.object({
enableEnvironments: z.boolean().default(false),
enableIsolatedWorkspaces: z.boolean().default(false),
enableStreamlinedLeftNavigation: z.boolean().default(true),
enablePipelines: z.boolean().default(false),
enableConferenceRoomChat: z.boolean().default(false),
enableTaskWatchdogs: z.boolean().default(false),
enableIssuePlanDecompositions: z.boolean().default(false),
+159
View File
@@ -0,0 +1,159 @@
import { z } from "zod";
import {
ISSUE_EXECUTION_WORKSPACE_PREFERENCES,
issueExecutionWorkspaceSettingsSchema,
} from "./issue.js";
const routineVariableLikeNameSchema = z.string().trim().regex(/^[A-Za-z][A-Za-z0-9_]*$/);
export const pipelineStageKindSchema = z.enum(["working", "review", "done", "cancelled"]);
export const legacyPipelineStageKindSchema = z.enum(["open", "working", "review", "done", "cancelled"]);
export const pipelineStageApproverSchema = z.object({
kind: z.enum(["any_human", "user", "agent"]).optional().default("any_human"),
id: z.string().trim().min(1).max(200).optional(),
}).superRefine((value, ctx) => {
if (value.kind !== "any_human" && (typeof value.id !== "string" || value.id.length === 0)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["id"],
message: "Specific stage approvers require an id",
});
}
});
export const pipelineStageOnEnterSchema = z.object({
type: z.literal("run_routine"),
routineId: z.string().uuid(),
id: z.string().trim().min(1).max(200).optional(),
projectId: z.string().uuid().optional().nullable(),
projectWorkspaceId: z.string().uuid().optional().nullable(),
executionWorkspaceId: z.string().uuid().optional().nullable(),
executionWorkspacePreference: z.enum(ISSUE_EXECUTION_WORKSPACE_PREFERENCES).optional().nullable(),
executionWorkspaceSettings: issueExecutionWorkspaceSettingsSchema.optional().nullable(),
}).passthrough();
export const pipelineStageAutomationSchema = z.object({
routineId: z.string().uuid().optional().nullable(),
assigneeAgentId: z.string().uuid().optional().nullable(),
instructionsBody: z.string().optional().nullable(),
projectId: z.string().uuid().optional().nullable(),
projectWorkspaceId: z.string().uuid().optional().nullable(),
executionWorkspaceId: z.string().uuid().optional().nullable(),
executionWorkspacePreference: z.enum(ISSUE_EXECUTION_WORKSPACE_PREFERENCES).optional().nullable(),
executionWorkspaceSettings: issueExecutionWorkspaceSettingsSchema.optional().nullable(),
}).passthrough();
export const pipelineStageCarryOverPolicySchema = z.object({
version: z.literal(1).default(1),
mode: z.enum(["all_except", "only"]).default("all_except"),
includeFields: z.array(routineVariableLikeNameSchema).max(100).default([]),
excludeFields: z.array(routineVariableLikeNameSchema).max(100).default([]),
});
export const pipelineStageBreakdownSchema = z.object({
targetPipelineId: z.string().uuid(),
targetStageKey: z.string().trim().min(1).max(120),
pieceNoun: z.string().trim().min(1).max(80).default("piece"),
carryOverPolicy: pipelineStageCarryOverPolicySchema.optional(),
inheritFields: z.array(routineVariableLikeNameSchema).max(100).default([]),
advanceTo: z.string().trim().min(1).max(120).optional(),
waitForPieces: z.boolean().optional().default(false),
whenFinishedMoveTo: z.string().trim().min(1).max(120).optional(),
}).superRefine((value, ctx) => {
if (value.waitForPieces && !value.whenFinishedMoveTo) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["whenFinishedMoveTo"],
message: "Breakdown stages that wait for pieces need a destination stage",
});
}
});
export const pipelineStageVariableSchema = z.object({
key: routineVariableLikeNameSchema,
label: z.string().trim().max(120),
type: z.enum(["select", "text", "multiline"]).default("text"),
options: z.array(z.string().trim().min(1).max(120)).max(50).optional().default([]),
required: z.boolean().optional().default(false),
showInAddForm: z.boolean().optional().default(false),
}).superRefine((value, ctx) => {
if (value.type === "select" && value.options.length === 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["options"],
message: "Select variables require at least one option",
});
}
if (value.type !== "select" && value.options.length > 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["options"],
message: "Only select variables can define options",
});
}
});
export const pipelineStageConfigSchema = z.object({
variables: z.array(pipelineStageVariableSchema).default([]),
disabled: z.boolean().optional(),
disabledReason: z.string().trim().max(1_000).nullable().optional(),
requireApproval: z.boolean().optional(),
approver: pipelineStageApproverSchema.optional(),
/** Legacy input only; the server migrates it to requireApproval/approver. */
reviewerKind: z.enum(["human", "any"]).optional(),
whatHappensHere: z.string().trim().max(10_000).optional(),
onEnter: pipelineStageOnEnterSchema.optional(),
automation: pipelineStageAutomationSchema.optional(),
breakdown: pipelineStageBreakdownSchema.optional(),
approveToStageKey: z.string().trim().min(1).max(120).optional(),
rejectToStageKey: z.string().trim().min(1).max(120).optional(),
requestChangesToStageKey: z.string().trim().min(1).max(120).optional(),
requireRejectReason: z.boolean().optional(),
requireRequestChangesReason: z.boolean().optional(),
requireChildrenTerminal: z.boolean().optional(),
requireNoUnresolvedDrift: z.boolean().optional(),
}).passthrough().superRefine((value, ctx) => {
const keys = new Set<string>();
value.variables.forEach((variable, index) => {
if (keys.has(variable.key)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["variables", index, "key"],
message: "Pipeline stage variable keys must be unique",
});
}
keys.add(variable.key);
});
});
export const pipelineAutomationRetryScopeSchema = z.enum(["current_stage", "previous_stage"]);
export const pipelineAutomationRetryCleanupOptionsSchema = z.object({
retireDirectChildren: z.boolean().default(true),
retireDescendants: z.boolean().default(true),
cancelLinkedAutomationIssues: z.boolean().default(true),
});
export const pipelineAutomationRetryRequestSchema = z.object({
scope: pipelineAutomationRetryScopeSchema,
targetStageId: z.string().uuid().nullable().optional(),
expectedVersion: z.number().int().positive(),
cleanup: pipelineAutomationRetryCleanupOptionsSchema.default({
retireDirectChildren: true,
retireDescendants: true,
cancelLinkedAutomationIssues: true,
}),
});
export type PipelineStageKind = z.infer<typeof pipelineStageKindSchema>;
export type PipelineStageApprover = z.infer<typeof pipelineStageApproverSchema>;
export type PipelineStageOnEnter = z.infer<typeof pipelineStageOnEnterSchema>;
export type PipelineStageAutomationConfig = z.infer<typeof pipelineStageAutomationSchema>;
export type PipelineStageCarryOverPolicy = z.infer<typeof pipelineStageCarryOverPolicySchema>;
export type PipelineStageBreakdown = z.infer<typeof pipelineStageBreakdownSchema>;
export type PipelineStageVariable = z.infer<typeof pipelineStageVariableSchema>;
export type PipelineStageConfig = z.infer<typeof pipelineStageConfigSchema>;
export type PipelineAutomationRetryScope = z.infer<typeof pipelineAutomationRetryScopeSchema>;
export type PipelineAutomationRetryCleanupOptions = z.infer<typeof pipelineAutomationRetryCleanupOptionsSchema>;
export type PipelineAutomationRetryRequest = z.infer<typeof pipelineAutomationRetryRequestSchema>;
@@ -159,6 +159,7 @@ export const runRoutineSchema = z.object({
payload: z.record(z.string(), z.unknown()).optional().nullable(),
variables: z.record(z.string(), routineVariableValueSchema).optional().nullable(),
projectId: z.string().uuid().optional().nullable(),
projectWorkspaceId: z.string().uuid().optional().nullable(),
assigneeAgentId: z.string().uuid().optional().nullable(),
idempotencyKey: z.string().trim().max(255).optional().nullable(),
source: z.enum(["manual", "api"]).optional().default("manual"),