Files
PaperClipAI/server/src/services/run-liveness.ts
T
Dotta 1fca3a6d8c fix(github): silence anonymous sandbox launchers and auto-request GitHub connection on unconfigured git auth failures (#22954)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Sandboxed runs wrap `git` and `gh` with broker launchers so agents
do not inherit ambient host credentials, and task feeds use
`connection_intent` cards to let users connect services inline.
> - When a workspace has no GitHub connection configured, anonymous
sandbox launchers logged `Paperclip: GitHub capability_missing;
continuing without managed credentials.` on every `git` or `gh` call,
and failed local `gh --version`/`--help` commands.
> - In addition, when an agent tried to clone a private GitHub
repository, push to GitHub, or run `gh` without a GitHub connection
configured, the task feed did not prompt the user with a GitHub
connection card.
> - Both issues hurt first-run clarity: noisy `capability_missing`
warnings look like broken infrastructure, while unconfigured git auth
failures leave users without an inline path to connect GitHub.
> - This pull request marks intentional anonymous sandbox launchers
silent, treats local `gh` version/help commands as local, and
automatically attaches a `github` `connection_intent` card in the task
feed when a run hits an unambiguous unconfigured GitHub auth failure.
> - The benefit is clean anonymous git/gh execution and a one-click
inline GitHub setup card when a task needs private GitHub access.

## Linked Issues or Issue Description

**What happened?**
In sandboxes without a GitHub connection configured, running `git` (such
as `git --version` or public clones) logged `Paperclip: GitHub
capability_missing; continuing without managed credentials.` and `gh
--version` / `gh --help` attempted broker resolution. When an agent
tried an authenticated GitHub operation (such as cloning a private
repository, pushing, or running `gh`), the run failed or reported the
auth error without showing a GitHub connection card in the task feed.

**Expected behavior**
Anonymous unconfigured sandbox launchers should run public/local `git`
and local `gh` commands silently without emitting `capability_missing`
warnings, while keeping `capability_missing` diagnostics for genuinely
missing or failed-bridge broker configs. When an agent hits an
unconfigured GitHub authentication failure during a task run or
workspace clone, Paperclip should attach a `github` connection card in
the task feed and mark run liveness as blocked waiting for the user.

**Steps to reproduce**
1. Run an agent in a sandbox with no GitHub connection configured.
2. Execute `git --version`, `gh --version`, and `git clone
https://github.com/<org>/<private-repo>.git`.
3. Observe `Paperclip: GitHub capability_missing; continuing without
managed credentials.` on stdout/stderr and no GitHub connection card in
the task feed after the private clone fails.

**Paperclip version or commit**
`a0d5f275af` (`master`)

**Deployment mode**
Other (sandboxed Paperclip Runner and local server)

## What Changed

- Added explicit `anonymous` mode to GitHub broker launchers
(`packages/adapter-utils/src/github-launcher.ts`,
`packages/adapter-utils/src/execution-target.ts`,
`server/src/services/heartbeat-github-launchers.ts`) and supported
`"anonymous": true` in `broker.json` so intentionally unconfigured
sandboxes stay quiet while missing/broken broker bridges still emit
`capability_missing`.
- Treated local `gh` commands (`--version`, `--help`, `-h`, `version`,
`help`) as local in the `gh` launcher without contacting the credential
broker.
- Added `server/src/services/git-auth-connection-detection.ts` to detect
unambiguous `github.com` auth failures in failed command execution
events (`tool.execution.completed` and `item.completed`) and structured
workspace clone failures while ignoring `exitCode === 0`, assistant
prose, non-GitHub remotes, transient 5xx errors, and local non-auth git
errors.
- Added controller-only
`connectionIntentService(db).requestForRunGitHubAuthFailure(runId,
resultJsonOverride?)` in `server/src/services/connection-intents.ts`
(with `completed_git_auth` run-context mode) to create a `github`
`connection_intent` card in the task feed when GitHub is not already
configured/usable, skipping `host` auth mode, closed tasks, non-latest
runs, existing pending cards, and declined continuations.
- Wired `requestForRunGitHubAuthFailure` into
`classifyAndPersistRunLiveness`
(`server/src/services/heartbeat/run-lifecycle.ts`) and added
`githubConnectionRequested` support to `classifyRunLiveness`
(`server/src/services/run-liveness.ts`) to classify the run as `blocked`
(`Waiting for GitHub connection`).
- Added unit and embedded-Postgres integration tests in
`packages/adapter-utils/src/github-launcher.test.ts`,
`server/src/services/heartbeat-github-launchers.test.ts`, and
`server/src/__tests__/github-connection-auto-request.test.ts`.

## Verification

- `pnpm vitest run packages/adapter-utils/src/github-launcher.test.ts`
(41/41 passed)
- `pnpm vitest run
packages/adapter-utils/src/github-launcher-environment.test.ts
--testTimeout=15000` (40 passed, 1 skipped)
- `pnpm vitest run
server/src/services/heartbeat-github-launchers.test.ts
server/src/services/native-runtime/native-github-access.test.ts`
(passed)
- `pnpm vitest run
server/src/__tests__/github-connection-auto-request.test.ts
server/src/__tests__/connection-intents-service.test.ts
server/src/__tests__/ai-auth-failure.test.ts
server/src/services/heartbeat/run-comment-selection.test.ts` (86/86
passed)
- `pnpm vitest run server/src/__tests__/run-liveness.test.ts` (21/21
passed)
- `pnpm vitest run
server/src/__tests__/heartbeat-process-recovery.test.ts -t
"clone|connection|GitHub"` (6/6 passed)
- `pnpm --filter @paperclipai/adapter-utils typecheck && pnpm --filter
@paperclipai/server typecheck` (0 errors)

## Risks

- Low risk. No database migrations or UI schema changes are required;
the auto-created card reuses the existing `connection_intent`
interaction kind (`serviceSlug: "github"`).
- False-positive card creation is guarded by strict `github.com` host
matching, non-zero command exit requirements, `githubAuthenticationMode
!== "host"`, active-identity checks (`usableConnectionForAgent` and
`resolveManagedGitHubIdentitySelection`), idempotent pending-card
checks, and decline respect.

## Model Used

- Google Gemini (Antigravity agent) with tool use and local code/test
execution.

## Checklist

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

380 lines
16 KiB
TypeScript

import { isAiAuthenticationRepairable } from "./ai-auth-failure.js";
import type { HeartbeatRunStatus, IssueStatus, RunLivenessState } from "@paperclipai/shared";
export type RunLivenessActionability =
| "runnable"
| "manager_review"
| "blocked_external"
| "approval_required"
| "unknown";
export interface RunLivenessIssueInput {
status: IssueStatus | string;
title: string;
description: string | null;
workMode?: string | null;
}
export interface RunLivenessEvidenceInput {
issueCommentsCreated: number;
documentRevisionsCreated: number;
planDocumentRevisionsCreated: number;
workProductsCreated: number;
workspaceOperationsCreated: number;
activityEventsCreated: number;
toolOrActionEventsCreated: number;
latestEvidenceAt: Date | null;
}
export interface RunLivenessClassificationInput {
runStatus: HeartbeatRunStatus | string;
issue: RunLivenessIssueInput | null;
resultJson?: Record<string, unknown> | null;
issueCommentBodies?: string[] | null;
continuationSummaryBody?: string | null;
stdoutExcerpt?: string | null;
stderrExcerpt?: string | null;
error?: string | null;
errorCode?: string | null;
continuationAttempt?: number | null;
evidence?: Partial<RunLivenessEvidenceInput> | null;
/** Set by the controller only after creating a durable connection card. */
authenticationRepairRequested?: boolean;
/** Set by the controller only after auto-attaching a GitHub connection card. */
githubConnectionRequested?: boolean;
}
export interface RunLivenessClassification {
livenessState: RunLivenessState;
livenessReason: string;
continuationAttempt: number;
lastUsefulActionAt: Date | null;
nextAction: string | null;
actionability: RunLivenessActionability;
}
const DEFAULT_EVIDENCE: RunLivenessEvidenceInput = {
issueCommentsCreated: 0,
documentRevisionsCreated: 0,
planDocumentRevisionsCreated: 0,
workProductsCreated: 0,
workspaceOperationsCreated: 0,
activityEventsCreated: 0,
toolOrActionEventsCreated: 0,
latestEvidenceAt: null,
};
const PLANNING_ONLY_RE =
/\b(?:i(?:'ll| will| am going to|'m going to)|let me|i need to|next(?:,| i will| i'll)?|my next step is|the next step is)\s+(?:first\s+)?(?:inspect|check|review|look|investigate|analy[sz]e|open|read|start|begin|work on|implement|fix|test|update|create|add)\b/i;
const NEXT_STEPS_RE = /^\s*(?:next steps?|plan)\s*:/im;
const BLOCKER_RE =
/\b(?:blocked|can't proceed|cannot proceed|unable to proceed|waiting on|need(?:s|ed)? .{0,80}\b(?:approval|access|credential|credentials|secret|api key|token|input|clarification)|requires? .{0,80}\b(?:approval|access|credential|credentials|secret|api key|token|input|clarification))\b/i;
const NEGATED_BLOCKER_RE = /\b(?:not blocked|no blocker|no blockers|unblocked)\b/i;
const APPROVAL_REQUIRED_RE =
/\b(?:approval required|requires? .{0,80}\bapproval|need(?:s|ed)? .{0,80}\bapproval|waiting on .{0,80}\bapproval|pending approval|board approval|human approval|user approval|operator approval)\b/i;
const EXTERNAL_BLOCKER_RE =
/\b(?:can't proceed|cannot proceed|unable to proceed|waiting on|blocked by|blocked on|need(?:s|ed)?|requires?) .{0,120}\b(?:access|credential|credentials|secret|secrets|api key|token|password|login|account|permission|permissions|input|clarification)\b/i;
const MANAGER_REVIEW_RE =
/\b(?:manager review|human review|manual review|security review|escalate|production deploy|deploy(?:ing)? to production|deploy(?:ing)? to prod|prod deploy|production access|rotate .{0,40}\b(?:secret|key|token)|delete .{0,40}\bproduction|security-sensitive|credentialed operation|budget-sensitive|cost approval|spend approval)\b/i;
const RUNNABLE_RE =
/\b(?:(?:run|rerun|execute)\s+(?:pnpm|npm|yarn|bun|vitest|jest|pytest|cargo|go test|curl|tests?|typecheck|build|lint|package|verification)|(?:inspect|check|review|look|investigate|analy[sz]e|open|read|start|begin|continue|implement|fix|test|update|create|add|write|verify|validate|report)\b)/i;
const UNMANAGED_BACKGROUND_TASK_STOP_REASON = "unmanaged_background_task_stopped";
const UNMANAGED_BACKGROUND_TASK_LIVENESS_REASON = "unmanaged background task stopped; no durable live path";
function compactReason(reason: string) {
return reason.length <= 500 ? reason : `${reason.slice(0, 497)}...`;
}
function normalizeCount(value: unknown) {
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
}
function normalizeContinuationAttempt(value: unknown) {
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
}
function readText(value: unknown): string | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
function hasUnmanagedBackgroundTaskEvidence(resultJson: Record<string, unknown> | null | undefined) {
if (!resultJson) return false;
if (resultJson.stopReason === UNMANAGED_BACKGROUND_TASK_STOP_REASON) return true;
const evidence = resultJson.unmanagedBackgroundTask;
if (!evidence || typeof evidence !== "object" || Array.isArray(evidence)) return false;
const record = evidence as Record<string, unknown>;
return record.stopped === true &&
(record.stopReason === UNMANAGED_BACKGROUND_TASK_STOP_REASON ||
record.reason === UNMANAGED_BACKGROUND_TASK_LIVENESS_REASON);
}
function resultFinalText(resultJson: Record<string, unknown> | null | undefined) {
if (!resultJson) return "";
return [
readText(resultJson.nextAction),
readText(resultJson.summary),
readText(resultJson.result),
readText(resultJson.message),
readText(resultJson.error),
]
.filter((value): value is string => Boolean(value))
.join("\n");
}
function resultRawText(resultJson: Record<string, unknown> | null | undefined) {
if (!resultJson) return "";
return [
readText(resultJson.stdout),
readText(resultJson.stderr),
]
.filter((value): value is string => Boolean(value))
.join("\n");
}
function highSignalSources(input: RunLivenessClassificationInput) {
return [
...(input.issueCommentBodies ?? []).map(readText),
readText(resultFinalText(input.resultJson)),
readText(input.continuationSummaryBody),
].filter((value): value is string => Boolean(value));
}
function rawSources(input: RunLivenessClassificationInput) {
return [
readText(resultRawText(input.resultJson)),
readText(input.stdoutExcerpt),
readText(input.stderrExcerpt),
readText(input.error),
]
.filter((value): value is string => Boolean(value))
.map(stripNoisyTranscriptLines)
.filter((value) => value.length > 0);
}
function combinedOutput(input: RunLivenessClassificationInput) {
return [...highSignalSources(input), ...rawSources(input)].join("\n").trim();
}
function actionabilityText(input: RunLivenessClassificationInput) {
const highSignal = highSignalSources(input).join("\n").trim();
if (highSignal) return highSignal;
return rawSources(input).join("\n").trim();
}
export function hasUsefulOutput(input: RunLivenessClassificationInput) {
return combinedOutput(input).length > 0;
}
export function declaredBlocker(input: RunLivenessClassificationInput) {
if (input.issue?.status === "blocked") return true;
const actionability = classifyRunActionability(input);
return actionability === "blocked_external" || actionability === "approval_required";
}
export function looksLikePlanningOnly(input: RunLivenessClassificationInput) {
const text = actionabilityText(input);
if (!text) return false;
return PLANNING_ONLY_RE.test(text) || NEXT_STEPS_RE.test(text) || /^\s*next(?: steps?| action)?\s*:/im.test(text);
}
function normalizeEvidence(evidence: Partial<RunLivenessEvidenceInput> | null | undefined): RunLivenessEvidenceInput {
return {
issueCommentsCreated: normalizeCount(evidence?.issueCommentsCreated),
documentRevisionsCreated: normalizeCount(evidence?.documentRevisionsCreated),
planDocumentRevisionsCreated: normalizeCount(evidence?.planDocumentRevisionsCreated),
workProductsCreated: normalizeCount(evidence?.workProductsCreated),
workspaceOperationsCreated: normalizeCount(evidence?.workspaceOperationsCreated),
activityEventsCreated: normalizeCount(evidence?.activityEventsCreated),
toolOrActionEventsCreated: normalizeCount(evidence?.toolOrActionEventsCreated),
latestEvidenceAt: evidence?.latestEvidenceAt instanceof Date ? evidence.latestEvidenceAt : null,
};
}
export function hasConcreteActionEvidence(evidence: Partial<RunLivenessEvidenceInput> | null | undefined) {
const normalized = normalizeEvidence(evidence);
// Workspace creation is setup evidence, not task progress by itself. It can
// appear in reasons alongside durable activity, but it must not prevent a
// planning-only or empty run from receiving a bounded continuation.
return (
normalized.issueCommentsCreated +
normalized.documentRevisionsCreated +
normalized.workProductsCreated +
normalized.activityEventsCreated +
normalized.toolOrActionEventsCreated >
0
);
}
function evidenceReason(evidence: RunLivenessEvidenceInput) {
const parts: string[] = [];
if (evidence.issueCommentsCreated > 0) parts.push(`${evidence.issueCommentsCreated} issue comment(s)`);
if (evidence.documentRevisionsCreated > 0) parts.push(`${evidence.documentRevisionsCreated} document revision(s)`);
if (evidence.workProductsCreated > 0) parts.push(`${evidence.workProductsCreated} work product(s)`);
if (evidence.workspaceOperationsCreated > 0) parts.push(`${evidence.workspaceOperationsCreated} workspace operation(s)`);
if (evidence.activityEventsCreated > 0) parts.push(`${evidence.activityEventsCreated} activity event(s)`);
if (evidence.toolOrActionEventsCreated > 0) parts.push(`${evidence.toolOrActionEventsCreated} tool/action event(s)`);
return parts.join(", ");
}
function stripMarkdownListPrefix(line: string) {
return line.replace(/^\s*(?:[-*]|\d+\.)\s+/, "").trim();
}
function isNoisyTranscriptLine(line: string) {
const trimmed = line.trim();
if (!trimmed) return true;
return (
/^(?:command|status|exit_code|tool|tool_call|tool_result|stdout|stderr|event|payload|session|cwd|ref_id)\s*:/i.test(trimmed) ||
/^(?:\{|\[).{0,80}(?:tool|event|stdout|stderr|cmd|command|payload)/i.test(trimmed) ||
/^\$?\s*(?:rg|sed|cat|ls|git|pnpm|npm|yarn|curl|node|python)\b/i.test(trimmed)
);
}
function stripNoisyTranscriptLines(text: string) {
return text
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => !isNoisyTranscriptLine(line))
.join("\n")
.trim();
}
function nextNonNoiseLine(lines: string[], startIndex: number) {
for (let i = startIndex + 1; i < lines.length; i += 1) {
const line = stripMarkdownListPrefix(lines[i] ?? "");
if (!line || isNoisyTranscriptLine(line)) continue;
return line;
}
return null;
}
function extractNextActionFromText(text: string) {
const lines = text.split(/\r?\n/).map((entry) => entry.trim());
for (let i = 0; i < lines.length; i += 1) {
const rawLine = lines[i] ?? "";
if (!rawLine || isNoisyTranscriptLine(rawLine)) continue;
const line = stripMarkdownListPrefix(rawLine);
const labeled = line.match(/^next(?: steps?| action)?\s*:\s*(.*)$/i);
if (labeled) {
const sameLine = stripMarkdownListPrefix(labeled[1] ?? "");
return sameLine || nextNonNoiseLine(lines, i);
}
if (PLANNING_ONLY_RE.test(line)) return line;
}
return null;
}
function extractNextAction(input: RunLivenessClassificationInput) {
const structuredNextAction = readText(input.resultJson?.nextAction);
const candidates = [
...(input.issueCommentBodies ?? []),
structuredNextAction ? `Next action: ${structuredNextAction}` : null,
resultFinalText(input.resultJson),
input.continuationSummaryBody,
...rawSources(input),
].filter((value): value is string => Boolean(readText(value)));
for (const candidate of candidates) {
const line = extractNextActionFromText(candidate);
if (!line) continue;
return line.length <= 500 ? line : `${line.slice(0, 497)}...`;
}
return null;
}
export function classifyRunActionability(input: RunLivenessClassificationInput): RunLivenessActionability {
const text = actionabilityText(input);
if (!text) return "unknown";
if (NEGATED_BLOCKER_RE.test(text)) {
return RUNNABLE_RE.test(text) ? "runnable" : "unknown";
}
if (APPROVAL_REQUIRED_RE.test(text)) return "approval_required";
if (EXTERNAL_BLOCKER_RE.test(text) || BLOCKER_RE.test(text) && /\b(?:credential|secret|api key|token|access|input|clarification)\b/i.test(text)) {
return "blocked_external";
}
if (MANAGER_REVIEW_RE.test(text)) return "manager_review";
if (RUNNABLE_RE.test(text)) return "runnable";
return "unknown";
}
export function classifyRunLiveness(input: RunLivenessClassificationInput): RunLivenessClassification {
const evidence = normalizeEvidence(input.evidence);
const continuationAttempt = normalizeContinuationAttempt(input.continuationAttempt);
const actionability = classifyRunActionability(input);
const nextAction = extractNextAction(input);
const issueStatus = input.issue?.status ?? null;
const usefulOutput = hasUsefulOutput(input);
const concreteEvidence = hasConcreteActionEvidence(evidence);
// This is a diagnostic only. Requested deliverables (including plans) do not
// select a work mode; only the persisted field grants the planning exemption.
const planExempt = input.issue?.workMode === "planning" || evidence.planDocumentRevisionsCreated > 0;
const lastUsefulActionAt = concreteEvidence ? evidence.latestEvidenceAt : null;
const output = (state: RunLivenessState, reason: string, nextAction: string | null = null): RunLivenessClassification => ({
livenessState: state,
livenessReason: compactReason(reason),
continuationAttempt,
lastUsefulActionAt: state === "advanced" || state === "completed" || state === "blocked" ? lastUsefulActionAt : null,
nextAction,
actionability,
});
if (input.runStatus === "interrupted") {
return output("needs_followup", input.errorCode ? `Run interrupted (${input.errorCode})` : "Run interrupted");
}
if (input.runStatus === "failed" && input.authenticationRepairRequested && isAiAuthenticationRepairable(input)) {
return output("blocked", "Waiting for provider authentication repair", "Complete the connection request to continue this task");
}
if (input.runStatus === "failed" && input.githubConnectionRequested) {
return output("blocked", "Waiting for GitHub connection", "Complete the connection request to continue this task");
}
if (input.runStatus !== "succeeded") {
if (hasUnmanagedBackgroundTaskEvidence(input.resultJson)) {
return output("failed", UNMANAGED_BACKGROUND_TASK_LIVENESS_REASON);
}
return output("failed", input.errorCode ? `Run ended with ${input.runStatus} (${input.errorCode})` : `Run ended with ${input.runStatus}`);
}
if (issueStatus === "done" || issueStatus === "cancelled") {
return output("completed", `Issue is ${issueStatus}`);
}
if (input.githubConnectionRequested) {
return output("blocked", "Waiting for GitHub connection", "Complete the connection request to continue this task");
}
if (declaredBlocker(input)) {
return output("blocked", issueStatus === "blocked" ? "Issue status is blocked" : "Run output declared a concrete blocker", nextAction);
}
if (!usefulOutput && !concreteEvidence) {
return output("empty_response", "Run succeeded without useful output or concrete action evidence");
}
if (concreteEvidence) {
return output("advanced", `Run produced concrete action evidence: ${evidenceReason(evidence)}`);
}
if (planExempt && usefulOutput) {
return output("advanced", "Explicit planning mode or a saved plan revision is exempt from plan-only classification");
}
if (looksLikePlanningOnly(input) || nextAction) {
if (actionability === "runnable") {
return output("plan_only", "Run described runnable future work without concrete action evidence", nextAction);
}
return output("needs_followup", "Run described future work that is not safe to auto-continue", nextAction);
}
if (usefulOutput) {
return output("needs_followup", "Run produced useful output but no concrete action evidence", nextAction);
}
return output("empty_response", "Run succeeded without useful output");
}