mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 18:35:33 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Native task completion independently verifies that declared PR deliverables are merged. > - Runs can already use an authorized managed GitHub connection to merge private PRs. > - Completion used the background credential resolver, which cannot select that run's managed identity. > - This pull request reuses operation-time identity and grant checks for completion verification. > - Agents can finish delivered work while unavailable grants and unverified merges remain blocked. ## Linked Issues or Issue Description Related: #22244 introduced the native PR merge gate. No duplicate fix was found in the open PR search. The roadmap's personal GitHub identity capability already covers the intended identity model. **What happened?** A native agent with a managed GitHub connection merges a private PR, then completion rejects it as not verified merged. The independent server-side check only tries legacy company token names or an instance token; it does not use the agent run's managed connection. **Expected behavior** Verify the merge with the run's current accepted GitHub identity, retaining current grant, membership, trust and company boundaries. GitHub must confirm the merge regardless of saved work-product metadata. **Steps to reproduce** 1. Configure a managed GitHub identity with access to a private repository and no legacy company GitHub token. 2. Use a native task run to merge and register a PR deliverable. 3. Finish the task. Before this change, the merge verifier cannot authenticate with the managed identity and rejects completion. ## What Changed - Bind completion credential lookup to the persisted company, native task and run. - Add a server-side completion credential path that shares managed grant, membership and trust checks with command credentials. Both active and succeeded runs capture identity under the existing task/run locks and reconcile pending steering acknowledgements before credential lookup. The command credential API still requires a running run. - Resolve credentials once for all PRs in a verification attempt; do no credential work for tasks without PR deliverables. - Preserve legacy fallback only for runs without a managed identity, and preserve the public-only restriction on server-environment credentials. - Add 23 PostgreSQL-backed authorization regression cases and document completion's identity behavior. ## Verification - Local checks cover revision `da2a3608b0375ead646bbbad35af853191488f07`. [Greptile review](https://github.com/paperclipai/paperclip/pull/22357#issuecomment-7023243798) is 5/5 on that revision with both prior threads resolved. [Required CI](https://github.com/paperclipai/paperclip/actions/runs/44625662403) passed on attempt 2 for the same revision, including typecheck, build, canary, server/runner suites and all eight e2e shards. - Red/green: the private-PR and identity-selection cases failed before the initial fix. Review exposed a succeeded-run reassessment failure and then an unsettled-steering gap in that path; each has a regression that failed on the reviewed commit and passes after its correction. Unresolved steering performs no token lookup, and durable acknowledgement selects the new person. The full worker test completes the task after automatic-review withdrawal while command credentials remain unavailable to the finished run. - `pnpm exec vitest run server/src/services/native-runtime/native-pull-request-completion.test.ts server/src/services/native-runtime/native-completion-feedback.test.ts server/src/__tests__/github-operation-credentials.test.ts server/src/__tests__/native-status-reassessment-work.test.ts server/src/__tests__/run-identity.test.ts server/src/__tests__/run-identity-projections.test.ts` — 222 tests pass across six files, on macOS arm64 with Node 25.6.1 and embedded PostgreSQL. - `pnpm --filter @paperclipai/server typecheck` — passes. - `pnpm verify --explain` — exits 2 because the subsystem documentation selects broad CI coverage. Required CI supplies the broader test/build coverage; this exit is not a full-suite pass. - The credential selection, steering, grant and company checks use real PostgreSQL state. Only the secret vault and GitHub HTTP transport are mocked; test requests never reach GitHub. - `git diff --check` and the staged secret/PII scan pass. No runtime artifacts are committed. - Earlier CI revision `4e42f64`: the [Build job](https://github.com/paperclipai/paperclip/actions/runs/44624163145/job/135914203042) ended after the runner received a shutdown signal and the workflow was cancelled. Its log does not show a compiler error before interruption; this interrupted attempt is not build verification. The current revision subsequently passed its own CI build on attempt 2. - Current revision canary: the [Canary Dry Run job](https://github.com/paperclipai/paperclip/actions/runs/44625662403/job/135919504493) was interrupted by runner shutdown before completion. The repository runner-loss classifier returns `lost: true` for its actual annotation and log. A targeted retry was refused while the workflow remained active. The same revision subsequently passed Canary Dry Run and the full workflow on attempt 2; the earlier interrupted attempt remains recorded here separately. - Live acceptance remains pending deployment; the change has not been deployed. ## Risks Completion now reads managed credentials through a server-side path shared with the existing authorization checks. Successful finished runs can be reassessed without granting them command execution credentials. Denied or unavailable identities must remain blocked without falling through to a different identity; regression tests cover revocation and company/task isolation. Credential lookup is shared within one bounded PR verification attempt, not cached across attempts. The existing HTTP deadline and merge proof requirements remain in place. No migrations or API contract changes. ## Model Used OpenAI Codex, `gpt-6.1-sol`, xhigh reasoning, with repository inspection, code editing and test execution. Context-window size is not exposed by the harness. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
781 lines
33 KiB
TypeScript
781 lines
33 KiB
TypeScript
import { readTaskRetryIntent, readTaskRetryBoardMessageOrigin } from "./task-retry.js";
|
|
import { and, asc, desc, eq, getTableColumns, inArray, sql } from "drizzle-orm";
|
|
import {
|
|
agentWakeupRequests,
|
|
heartbeatRuns,
|
|
heartbeatRunEvents,
|
|
issueComments,
|
|
issueThreadInteractions,
|
|
issues,
|
|
runIdentityContexts,
|
|
type Db,
|
|
} from "@paperclipai/db";
|
|
import { conflict, forbidden } from "../errors.js";
|
|
import { notifyChatRunMilestones } from "./chat-run-milestone-notifications.js";
|
|
import { boundRunIssueId, boundRunIssueIdSql, runTaskContextColumn } from "./run-task-binding.js";
|
|
import { isUuidLike } from "@paperclipai/shared";
|
|
import { queuedCommentIdsFromRunContext, queuedCommentIdsFromWakePayload } from "./issue-queued-comment-queue.js";
|
|
import { queuedInteractionId } from "./queued-interaction-response.js";
|
|
|
|
/** Resolve an explicit click from persisted receipts, never caller context or message authors. */
|
|
export async function explicitOperatorRunIdentity(
|
|
executor: Pick<Db, "select">,
|
|
run: Pick<typeof heartbeatRuns.$inferSelect, "id" | "companyId" | "agentId" | "contextSnapshot" | "wakeupRequestId">,
|
|
) {
|
|
const [request] = run.wakeupRequestId ? await executor.select().from(agentWakeupRequests).where(and(
|
|
eq(agentWakeupRequests.id, run.wakeupRequestId), eq(agentWakeupRequests.companyId, run.companyId),
|
|
eq(agentWakeupRequests.agentId, run.agentId), eq(agentWakeupRequests.runId, run.id),
|
|
)) : [];
|
|
if (request?.payload?.manualUserWake === true) {
|
|
if (request.requestedByActorType !== "user" || !request.requestedByActorId) {
|
|
throw forbidden("Manual wake requires an authenticated user");
|
|
}
|
|
return { actorId: request.requestedByActorId, cause: "manual_user_wake" };
|
|
}
|
|
const prefix = "queued-comment-interrupt:";
|
|
if (!request?.idempotencyKey?.startsWith(prefix)) return null;
|
|
const queueId = request.idempotencyKey.slice(prefix.length);
|
|
// The key only locates a candidate. The consumed queue, actor, run, company,
|
|
// agent, task, and delivered messages must all independently agree.
|
|
if (!isUuidLike(queueId)) {
|
|
throw forbidden("Queued-message interrupt authority is unavailable");
|
|
}
|
|
const [receipt] = await executor.select().from(agentWakeupRequests).where(and(
|
|
eq(agentWakeupRequests.id, queueId), eq(agentWakeupRequests.companyId, run.companyId),
|
|
eq(agentWakeupRequests.agentId, run.agentId), eq(agentWakeupRequests.runId, run.id),
|
|
eq(agentWakeupRequests.status, "coalesced"),
|
|
));
|
|
const marker = receipt?.payload?.queuedCommentInterrupt;
|
|
const actorId = marker && typeof marker === "object" && "actorId" in marker ? marker.actorId : null;
|
|
if (typeof actorId !== "string" || !actorId || !receipt ||
|
|
receipt.payload?.issueId !== run.contextSnapshot?.issueId ||
|
|
request.requestedByActorType !== "user" || request.requestedByActorId !== actorId) {
|
|
throw forbidden("Queued-message interrupt authority is unavailable");
|
|
}
|
|
const ids = queuedCommentIdsFromWakePayload(receipt.payload);
|
|
if (!ids.length) {
|
|
const interactionId = queuedInteractionId(receipt.payload);
|
|
const [interaction] = interactionId && run.contextSnapshot?.interactionId === interactionId
|
|
? await executor.select({ resolvedByUserId: issueThreadInteractions.resolvedByUserId })
|
|
.from(issueThreadInteractions).where(and(
|
|
eq(issueThreadInteractions.id, interactionId), eq(issueThreadInteractions.companyId, run.companyId),
|
|
eq(issueThreadInteractions.issueId, String(run.contextSnapshot.issueId)),
|
|
eq(issueThreadInteractions.status, String(receipt.payload?.interactionStatus)),
|
|
))
|
|
: [];
|
|
if (!interaction || interaction.resolvedByUserId !== actorId) {
|
|
throw forbidden("Queued-message interrupt authority is unavailable");
|
|
}
|
|
return { actorId, cause: "queued_comment_interrupt" };
|
|
}
|
|
const deliveredIds = queuedCommentIdsFromRunContext(run.contextSnapshot);
|
|
if (!ids.every(id => deliveredIds.includes(id))) {
|
|
throw forbidden("Queued-message interrupt authority is unavailable");
|
|
}
|
|
return { actorId, cause: "queued_comment_interrupt" };
|
|
}
|
|
|
|
export type RunIdentityContext = typeof runIdentityContexts.$inferSelect;
|
|
|
|
/** Only the recipient's completed connection action authorizes a handoff. */
|
|
function acceptedConnectionRecipient(interaction: Pick<typeof issueThreadInteractions.$inferSelect,
|
|
"kind" | "status" | "resolvedByAgentId" | "resolvedByUserId" | "addresseeUserId" | "result"
|
|
> | undefined): string | null {
|
|
return interaction?.kind === "connection_intent"
|
|
&& interaction.status === "accepted"
|
|
&& !interaction.resolvedByAgentId
|
|
&& interaction.resolvedByUserId === interaction.addresseeUserId
|
|
&& interaction.result?.outcome === "connected"
|
|
&& "connectionId" in interaction.result
|
|
&& typeof interaction.result.connectionId === "string"
|
|
? interaction.addresseeUserId : null;
|
|
}
|
|
|
|
function assertRunTaskIdentity(run: {
|
|
nativeIssueId?: string | null;
|
|
issueId?: string | null;
|
|
contextSnapshot?: Record<string, unknown> | null;
|
|
} | undefined) {
|
|
const issueId = run?.nativeIssueId ?? run?.issueId ?? run?.contextSnapshot?.issueId ?? run?.contextSnapshot?.taskId;
|
|
const legacyIssueId = run?.contextSnapshot?.issueId ?? run?.contextSnapshot?.taskId;
|
|
if ([issueId, legacyIssueId].some(id => id !== undefined && id !== null &&
|
|
(typeof id !== "string" || !isUuidLike(id)))) {
|
|
throw forbidden("Run task identity is invalid");
|
|
}
|
|
return issueId;
|
|
}
|
|
type Executor = Pick<Db, "select" | "insert" | "update">;
|
|
|
|
/**
|
|
* Lock the task before the run, matching task mutation ordering. Identity
|
|
* operations do not change parent keys: NO KEY UPDATE still serializes writers
|
|
* and steering, while allowing audit inserts to check their foreign keys.
|
|
* FOR UPDATE can deadlock with an append that holds KEY SHARE on the run and
|
|
* then checks the task while identity capture holds the task and waits on the run.
|
|
*/
|
|
async function lockIdentityTask(
|
|
executor: Pick<Db, "select">,
|
|
companyId: string,
|
|
runId: string,
|
|
) {
|
|
const [run] = await executor
|
|
.select({
|
|
contextSnapshot: runTaskContextColumn,
|
|
nativeIssueId: heartbeatRuns.nativeIssueId,
|
|
issueId: heartbeatRuns.issueId,
|
|
})
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId)),
|
|
);
|
|
const issueId = assertRunTaskIdentity(run);
|
|
if (typeof issueId === "string")
|
|
await executor
|
|
.select({ id: issues.id })
|
|
.from(issues)
|
|
.where(and(eq(issues.id, issueId), eq(issues.companyId, companyId)))
|
|
.for("no key update");
|
|
}
|
|
|
|
async function append(
|
|
executor: Executor,
|
|
input: {
|
|
companyId: string;
|
|
runId: string;
|
|
responsibleUserId: string | null;
|
|
messageId?: string | null;
|
|
parentContextId?: string | null;
|
|
cause: string;
|
|
correlationId: string;
|
|
status?: "accepted" | "pending";
|
|
},
|
|
) {
|
|
const [existing] = await executor
|
|
.select()
|
|
.from(runIdentityContexts)
|
|
.where(
|
|
and(
|
|
eq(runIdentityContexts.runId, input.runId),
|
|
eq(runIdentityContexts.correlationId, input.correlationId),
|
|
),
|
|
);
|
|
if (existing) return existing;
|
|
const [last] = await executor
|
|
.select()
|
|
.from(runIdentityContexts)
|
|
.where(eq(runIdentityContexts.runId, input.runId))
|
|
.orderBy(desc(runIdentityContexts.revision))
|
|
.limit(1);
|
|
const [created] = await executor
|
|
.insert(runIdentityContexts)
|
|
.values({
|
|
...input,
|
|
revision: (last?.revision ?? 0) + 1,
|
|
acceptedAt: input.status === "pending" ? null : new Date(),
|
|
})
|
|
.returning();
|
|
if (!created) throw new Error("Failed to persist run identity");
|
|
if (created.status === "accepted") await activate(executor, created);
|
|
return created;
|
|
}
|
|
|
|
async function activate(executor: Executor, context: RunIdentityContext) {
|
|
const [binding] = await executor.select({ issueId: boundRunIssueIdSql() })
|
|
.from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.id, context.runId), eq(heartbeatRuns.companyId, context.companyId),
|
|
));
|
|
if (binding?.issueId) {
|
|
await notifyChatRunMilestones(executor, { companyId: context.companyId, issueId: binding.issueId });
|
|
}
|
|
const [run] = await executor
|
|
.update(heartbeatRuns)
|
|
.set({
|
|
responsibleUserId: context.responsibleUserId,
|
|
activeIdentityContextId: context.id,
|
|
updatedAt: new Date(),
|
|
})
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.id, context.runId),
|
|
eq(heartbeatRuns.companyId, context.companyId),
|
|
),
|
|
)
|
|
.returning({
|
|
nativeIssueId: heartbeatRuns.nativeIssueId,
|
|
issueId: heartbeatRuns.issueId,
|
|
contextSnapshot: runTaskContextColumn,
|
|
});
|
|
const issueId = run ? boundRunIssueId(run) : null;
|
|
if (typeof issueId === "string")
|
|
await executor
|
|
.update(issues)
|
|
.set({ continuationIdentityContextId: context.id })
|
|
.where(
|
|
and(eq(issues.id, issueId), eq(issues.companyId, context.companyId)),
|
|
);
|
|
}
|
|
|
|
/** Called only for newly dispatched runs. Historical rows are never backfilled. */
|
|
export async function initializeRunIdentity(
|
|
db: Db,
|
|
input: {
|
|
companyId: string;
|
|
runId: string;
|
|
responsibleUserId: string | null;
|
|
messageIds?: string[];
|
|
issueId?: string | null;
|
|
interactionId?: string | null;
|
|
parentRunId?: string | null;
|
|
parentContextId?: string | null;
|
|
cause: string;
|
|
},
|
|
) {
|
|
return db.transaction(async (tx) => {
|
|
await lockIdentityTask(tx, input.companyId, input.runId);
|
|
const [run] = await tx
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.id, input.runId),
|
|
eq(heartbeatRuns.companyId, input.companyId),
|
|
),
|
|
)
|
|
.for("no key update");
|
|
if (!run) throw forbidden("Run identity does not belong to this company");
|
|
if (run.activeIdentityContextId) {
|
|
const [current] = await tx
|
|
.select()
|
|
.from(runIdentityContexts)
|
|
.where(eq(runIdentityContexts.id, run.activeIdentityContextId));
|
|
return current!;
|
|
}
|
|
const operatorIdentity = await explicitOperatorRunIdentity(tx, run);
|
|
let retryOrigin: string | null = null;
|
|
const retryId = run.contextSnapshot?.taskRetryRequestId;
|
|
if (typeof retryId === "string") {
|
|
const [receipt] = await tx.select().from(agentWakeupRequests).where(and(
|
|
eq(agentWakeupRequests.id, retryId), eq(agentWakeupRequests.companyId, input.companyId),
|
|
eq(agentWakeupRequests.agentId, run.agentId)));
|
|
const retry = readTaskRetryIntent(receipt?.payload);
|
|
if (run.contextSnapshot?.boardMessageRetry === true || retry?.boardMessageOrigin) {
|
|
if (!retry?.boardMessageOrigin) throw forbidden("This saved message can no longer be retried safely. Send a new message on the task to continue from saved work.");
|
|
const [dispatch] = run.wakeupRequestId ? await tx.select().from(agentWakeupRequests).where(and(
|
|
eq(agentWakeupRequests.id, run.wakeupRequestId), eq(agentWakeupRequests.companyId, input.companyId),
|
|
eq(agentWakeupRequests.agentId, run.agentId), eq(agentWakeupRequests.runId, run.id),
|
|
eq(agentWakeupRequests.status, "claimed"), eq(agentWakeupRequests.reason, "task_retry"),
|
|
eq(agentWakeupRequests.idempotencyKey, `task-retry-dispatch:${receipt!.id}`),
|
|
eq(agentWakeupRequests.requestedByActorType, "user"), eq(agentWakeupRequests.requestedByActorId, retry.actorId))) : [];
|
|
const [task] = input.issueId ? await tx.select({ id: issues.id }).from(issues).where(and(
|
|
eq(issues.id, input.issueId), eq(issues.companyId, input.companyId), eq(issues.assigneeAgentId, run.agentId),
|
|
eq(issues.executionRunId, run.id))) : [];
|
|
const origin = input.issueId && run.status === "running" && task && dispatch &&
|
|
[run.issueId, run.nativeIssueId, run.contextSnapshot?.issueId, run.contextSnapshot?.taskId]
|
|
.every(id => id === null || id === undefined || id === input.issueId) && receipt!.runId === run.id && receipt!.status === "coalesced" &&
|
|
receipt!.reason === "task_retry" && receipt!.requestedByActorType === "user" &&
|
|
run.contextSnapshot?.previousRunId === retry.sourceRunId && retry.generationId === receipt!.id && !retry.chatActionId && !retry.canonicalIntentId &&
|
|
receipt!.payload?.issueId === input.issueId && retry.actorId === receipt!.requestedByActorId &&
|
|
await readTaskRetryBoardMessageOrigin(tx as unknown as Db, { companyId: input.companyId, issueId: input.issueId,
|
|
agentId: run.agentId, sourceRunId: retry.sourceRunId, actorId: retry.actorId });
|
|
if (!origin || origin.commentId !== retry.boardMessageOrigin.commentId ||
|
|
origin.identityContextId !== retry.boardMessageOrigin.identityContextId) {
|
|
throw forbidden("This saved message can no longer be retried safely. Send a new message on the task to continue from saved work.");
|
|
}
|
|
retryOrigin = origin.identityContextId;
|
|
}
|
|
}
|
|
const snapshotRetryRunId = run.contextSnapshot?.retryOfRunId;
|
|
const retryRunId = run.retryOfRunId ?? (
|
|
typeof snapshotRetryRunId === "string" ? snapshotRetryRunId.trim() || null : null
|
|
);
|
|
const isRetry = retryRunId !== null || retryOrigin !== null;
|
|
const parentRunId = retryRunId ?? input.parentRunId;
|
|
const [parent] = parentRunId
|
|
? await tx
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.id, parentRunId),
|
|
eq(heartbeatRuns.companyId, input.companyId),
|
|
),
|
|
)
|
|
: [];
|
|
const [interaction] =
|
|
input.interactionId && input.issueId
|
|
? await tx
|
|
.select()
|
|
.from(issueThreadInteractions)
|
|
.where(
|
|
and(
|
|
eq(issueThreadInteractions.id, input.interactionId),
|
|
eq(issueThreadInteractions.companyId, input.companyId),
|
|
eq(issueThreadInteractions.issueId, input.issueId),
|
|
),
|
|
)
|
|
: [];
|
|
const retryContextId = retryOrigin ?? (isRetry ? parent?.activeIdentityContextId : null);
|
|
// A preparation failure can precede identity initialization. An ordinary
|
|
// retry retains its stored person when available, or the caller's existing
|
|
// responsible-user resolution. It never replays a connection handoff.
|
|
const uninitializedRetryUserId = isRetry && !retryContextId
|
|
? parent?.responsibleUserId : null;
|
|
if (!operatorIdentity && isRetry && !retryContextId && interaction?.kind === "connection_intent")
|
|
throw forbidden("Originating execution identity is unavailable");
|
|
// An ordinary approval keeps its saved origin when preparation failed
|
|
// before the previous run accepted an identity. A stored retry context
|
|
// still wins after initialization or later accepted steering.
|
|
const parentId = operatorIdentity ? null : (
|
|
retryContextId ?? interaction?.sourceIdentityContextId
|
|
?? (isRetry ? null : input.parentContextId ?? parent?.activeIdentityContextId)
|
|
);
|
|
const [origin] = parentId
|
|
? await tx
|
|
.select()
|
|
.from(runIdentityContexts)
|
|
.where(
|
|
and(
|
|
eq(runIdentityContexts.id, parentId),
|
|
eq(runIdentityContexts.companyId, input.companyId),
|
|
eq(runIdentityContexts.status, "accepted"),
|
|
),
|
|
)
|
|
: [];
|
|
if (parentId && !origin)
|
|
throw forbidden("Originating execution identity is unavailable");
|
|
const connectionRecipient = acceptedConnectionRecipient(interaction);
|
|
const identity = operatorIdentity
|
|
? { responsibleUserId: operatorIdentity.actorId, cause: operatorIdentity.cause }
|
|
: !isRetry && connectionRecipient && origin?.responsibleUserId !== connectionRecipient
|
|
? { responsibleUserId: connectionRecipient, cause: "connection_handoff" }
|
|
: {
|
|
responsibleUserId: origin ? origin.responsibleUserId : uninitializedRetryUserId ?? input.responsibleUserId,
|
|
cause: origin?.cause === "company_default" ? "company_default" : input.cause,
|
|
};
|
|
let current = await append(tx, {
|
|
companyId: input.companyId,
|
|
runId: input.runId,
|
|
...identity,
|
|
parentContextId: origin?.id ?? null,
|
|
correlationId: "dispatch",
|
|
});
|
|
const ids = [...new Set(input.messageIds ?? [])];
|
|
const comments =
|
|
ids.length && input.issueId
|
|
? await tx
|
|
.select()
|
|
.from(issueComments)
|
|
.where(
|
|
and(
|
|
eq(issueComments.companyId, input.companyId),
|
|
eq(issueComments.issueId, input.issueId),
|
|
inArray(issueComments.id, ids),
|
|
),
|
|
)
|
|
: [];
|
|
for (const id of ids) {
|
|
const comment = comments.find((c) => c.id === id);
|
|
if (!comment?.authorUserId) continue;
|
|
current = await append(tx, {
|
|
companyId: input.companyId,
|
|
runId: input.runId,
|
|
responsibleUserId: operatorIdentity?.actorId ?? comment.authorUserId,
|
|
messageId: id,
|
|
parentContextId: current.id,
|
|
cause: operatorIdentity?.cause ?? "instruction",
|
|
correlationId: `message:${id}`,
|
|
});
|
|
}
|
|
return current;
|
|
});
|
|
}
|
|
|
|
/** Caller holds the task and run row locks, in that order. Reserve before delivery so acquisitions cannot guess. */
|
|
export async function prepareSteeredIdentity(
|
|
executor: Executor,
|
|
input: {
|
|
companyId: string;
|
|
runId: string;
|
|
messageId: string;
|
|
issueId: string;
|
|
source?: "comment" | "interaction";
|
|
},
|
|
) {
|
|
const [run] = await executor
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.id, input.runId),
|
|
eq(heartbeatRuns.companyId, input.companyId),
|
|
),
|
|
);
|
|
const [comment] = input.source === "interaction" ? [] : await executor
|
|
.select()
|
|
.from(issueComments)
|
|
.where(
|
|
and(
|
|
eq(issueComments.id, input.messageId),
|
|
eq(issueComments.companyId, input.companyId),
|
|
eq(issueComments.issueId, input.issueId),
|
|
),
|
|
);
|
|
const [interaction] = input.source === "interaction" ? await executor.select().from(issueThreadInteractions).where(and(
|
|
eq(issueThreadInteractions.id, input.messageId),
|
|
eq(issueThreadInteractions.companyId, input.companyId),
|
|
eq(issueThreadInteractions.issueId, input.issueId),
|
|
inArray(issueThreadInteractions.status, ["accepted", "answered", "rejected"]),
|
|
)) : [];
|
|
const responsibleUserId = interaction?.resolvedByUserId ?? comment?.authorUserId;
|
|
if (!run || !responsibleUserId)
|
|
throw forbidden("Steering requires an authenticated message author");
|
|
if (
|
|
run.status !== "running" ||
|
|
boundRunIssueId(run) !== input.issueId
|
|
) {
|
|
throw conflict("Steering targets a different or inactive execution");
|
|
}
|
|
return append(executor, {
|
|
companyId: input.companyId,
|
|
runId: input.runId,
|
|
responsibleUserId,
|
|
messageId: input.messageId,
|
|
parentContextId: run.activeIdentityContextId,
|
|
cause: "steering",
|
|
correlationId: `${input.source === "interaction" ? "interaction" : "message"}:${input.messageId}`,
|
|
status: "pending",
|
|
});
|
|
}
|
|
|
|
export async function reserveSteeredIdentity(
|
|
db: Db,
|
|
input: Parameters<typeof prepareSteeredIdentity>[1],
|
|
) {
|
|
return db.transaction(async (tx) => {
|
|
await lockIdentityTask(tx, input.companyId, input.runId);
|
|
const [run] = await tx
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.id, input.runId),
|
|
eq(heartbeatRuns.companyId, input.companyId),
|
|
),
|
|
)
|
|
.for("no key update");
|
|
// Processes started before the broker rollout keep their original environment.
|
|
if (!run?.activeIdentityContextId) return null;
|
|
const [pending] = await tx
|
|
.select()
|
|
.from(runIdentityContexts)
|
|
.where(
|
|
and(
|
|
eq(runIdentityContexts.runId, run.id),
|
|
eq(runIdentityContexts.status, "pending"),
|
|
),
|
|
)
|
|
.limit(1);
|
|
if (pending && pending.messageId !== input.messageId) {
|
|
if (await storedSteeringAcknowledgement(tx, pending))
|
|
await acceptSteeredIdentity(tx, pending);
|
|
else
|
|
throw conflict(
|
|
"A prior steering acknowledgement must be reconciled first",
|
|
);
|
|
}
|
|
const [existing] = await tx
|
|
.select()
|
|
.from(runIdentityContexts)
|
|
.where(
|
|
and(
|
|
eq(runIdentityContexts.runId, run.id),
|
|
eq(runIdentityContexts.messageId, input.messageId),
|
|
eq(runIdentityContexts.status, "accepted"),
|
|
),
|
|
);
|
|
if (existing) return existing;
|
|
const context = await prepareSteeredIdentity(tx, input);
|
|
if (context.status === "rejected") {
|
|
await tx
|
|
.update(runIdentityContexts)
|
|
.set({ status: "pending" })
|
|
.where(eq(runIdentityContexts.id, context.id));
|
|
return { ...context, status: "pending" };
|
|
}
|
|
return context;
|
|
});
|
|
}
|
|
|
|
export async function rejectSteeredIdentity(
|
|
db: Db,
|
|
context: RunIdentityContext,
|
|
) {
|
|
await db
|
|
.update(runIdentityContexts)
|
|
.set({ status: "rejected" })
|
|
.where(
|
|
and(
|
|
eq(runIdentityContexts.id, context.id),
|
|
eq(runIdentityContexts.status, "pending"),
|
|
),
|
|
);
|
|
}
|
|
|
|
/** Accept within the caller's task/run transaction; standalone recovery uses reconcileSteeredIdentity. */
|
|
export async function acceptSteeredIdentity(
|
|
executor: Executor,
|
|
context: RunIdentityContext,
|
|
) {
|
|
// A replay must not reactivate a historical identity after later instructions.
|
|
const [accepted] = await executor
|
|
.update(runIdentityContexts)
|
|
.set({ status: "accepted", acceptedAt: new Date() })
|
|
.where(
|
|
and(
|
|
eq(runIdentityContexts.id, context.id),
|
|
eq(runIdentityContexts.status, "pending"),
|
|
),
|
|
)
|
|
.returning();
|
|
if (accepted) await activate(executor, accepted);
|
|
}
|
|
|
|
const runIdentityFields = {
|
|
id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId,
|
|
status: heartbeatRuns.status, responsibleUserId: heartbeatRuns.responsibleUserId,
|
|
activeIdentityContextId: heartbeatRuns.activeIdentityContextId,
|
|
};
|
|
|
|
export const runIdentityTaskFields = {
|
|
...runIdentityFields, nativeIssueId: heartbeatRuns.nativeIssueId, issueId: heartbeatRuns.issueId,
|
|
wakeupRequestId: heartbeatRuns.wakeupRequestId,
|
|
contextSnapshot: sql<Record<string, unknown> | null>`case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object'
|
|
then jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId',
|
|
'taskId', ${heartbeatRuns.contextSnapshot}->'taskId',
|
|
'conversationSessionGeneration', ${heartbeatRuns.contextSnapshot}->'conversationSessionGeneration',
|
|
'paperclipSkillTest', ${heartbeatRuns.contextSnapshot}->'paperclipSkillTest') else null end`,
|
|
};
|
|
|
|
export const runIdentityBrokerFields = {
|
|
...runIdentityFields, invocationSource: heartbeatRuns.invocationSource,
|
|
contextSnapshot: sql<Record<string, unknown> | null>`case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object'
|
|
then jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId',
|
|
'projectId', ${heartbeatRuns.contextSnapshot}->'projectId', 'routineId', ${heartbeatRuns.contextSnapshot}->'routineId',
|
|
'responsibleUserId', ${heartbeatRuns.contextSnapshot}->'responsibleUserId',
|
|
'responsible_user_id', ${heartbeatRuns.contextSnapshot}->'responsible_user_id',
|
|
'paperclipIssue', case when jsonb_typeof(${heartbeatRuns.contextSnapshot}->'paperclipIssue') = 'object'
|
|
then jsonb_build_object('id', ${heartbeatRuns.contextSnapshot}->'paperclipIssue'->'id',
|
|
'projectId', ${heartbeatRuns.contextSnapshot}->'paperclipIssue'->'projectId',
|
|
'responsibleUserId', ${heartbeatRuns.contextSnapshot}->'paperclipIssue'->'responsibleUserId',
|
|
'responsible_user_id', ${heartbeatRuns.contextSnapshot}->'paperclipIssue'->'responsible_user_id') else null end)
|
|
else null end`,
|
|
};
|
|
|
|
const runIdentityProjectFields = {
|
|
...runIdentityTaskFields, runtimeMode: heartbeatRuns.runtimeMode,
|
|
runnerProfileJson: sql<Record<string, unknown> | null>`case when jsonb_typeof(${heartbeatRuns.runnerProfileJson}) = 'object'
|
|
then case when ${heartbeatRuns.runnerProfileJson} ? 'nativeExecutionInput'
|
|
then jsonb_build_object('nativeExecutionInput', ${heartbeatRuns.runnerProfileJson}->'nativeExecutionInput')
|
|
else '{}'::jsonb end else null end`,
|
|
};
|
|
|
|
type FullIdentityRun = typeof heartbeatRuns.$inferSelect;
|
|
type IdentityRun = Pick<FullIdentityRun, keyof typeof runIdentityFields>;
|
|
type TaskIdentityRun = Pick<FullIdentityRun, keyof typeof runIdentityTaskFields>;
|
|
type BrokerIdentityRun = Pick<FullIdentityRun, keyof typeof runIdentityBrokerFields>;
|
|
type ProjectIdentityRun = Pick<FullIdentityRun, keyof typeof runIdentityProjectFields>;
|
|
export type RunIdentityReadScope = "github_credentials" | "request_authentication" | "identity" | "task_authorization" | "token_broker" | "project_execution";
|
|
export type RunIdentityCapture<Scope extends RunIdentityReadScope | undefined = undefined> = {
|
|
run: Scope extends "identity" ? IdentityRun : Scope extends "task_authorization" ? TaskIdentityRun :
|
|
Scope extends "token_broker" ? BrokerIdentityRun : Scope extends "project_execution" ? ProjectIdentityRun : FullIdentityRun;
|
|
context: RunIdentityContext | null;
|
|
};
|
|
|
|
export async function captureRunIdentity<Scope extends RunIdentityReadScope | undefined = undefined>(
|
|
db: Db,
|
|
input: { companyId: string; runId: string; agentId: string },
|
|
options?: { readScope: Scope },
|
|
): Promise<RunIdentityCapture<Scope>> {
|
|
return captureRunIdentityForPurpose(db, input, options);
|
|
}
|
|
|
|
export async function captureRunCompletionIdentity(
|
|
db: Db,
|
|
input: { companyId: string; runId: string; agentId: string; issueId: string },
|
|
): Promise<RunIdentityCapture<"github_credentials">> {
|
|
return captureRunIdentityForPurpose(db, input, { readScope: "github_credentials" }, input.issueId);
|
|
}
|
|
|
|
async function captureRunIdentityForPurpose<Scope extends RunIdentityReadScope | undefined = undefined>(
|
|
db: Db,
|
|
input: { companyId: string; runId: string; agentId: string },
|
|
options?: { readScope: Scope },
|
|
completionIssueId?: string,
|
|
): Promise<RunIdentityCapture<Scope>> {
|
|
// Lock acquisition serializes with steering delivery and its durable acknowledgement.
|
|
return db.transaction(async (tx) => {
|
|
await lockIdentityTask(tx, input.companyId, input.runId);
|
|
const [run] = await tx
|
|
.select(options?.readScope === "identity" ? runIdentityFields :
|
|
options?.readScope === "task_authorization" ? runIdentityTaskFields :
|
|
options?.readScope === "token_broker" ? runIdentityBrokerFields :
|
|
options?.readScope === "project_execution" ? runIdentityProjectFields :
|
|
options?.readScope === "github_credentials" || options?.readScope === "request_authentication" ? {
|
|
...getTableColumns(heartbeatRuns),
|
|
contextSnapshot: sql<Record<string, unknown> | null>`case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object'
|
|
then jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId',
|
|
'taskId', ${heartbeatRuns.contextSnapshot}->'taskId', 'projectId', ${heartbeatRuns.contextSnapshot}->'projectId',
|
|
'executionPolicy', ${heartbeatRuns.contextSnapshot}->'executionPolicy') else null end`,
|
|
runnerProfileJson: sql<Record<string, unknown> | null>`null`,
|
|
resultJson: sql<Record<string, unknown> | null>`null`,
|
|
stdoutExcerpt: sql<string | null>`null`, stderrExcerpt: sql<string | null>`null`,
|
|
} : getTableColumns(heartbeatRuns))
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.id, input.runId),
|
|
eq(heartbeatRuns.companyId, input.companyId),
|
|
eq(heartbeatRuns.agentId, input.agentId),
|
|
completionIssueId !== undefined ? eq(heartbeatRuns.nativeIssueId, completionIssueId) : undefined,
|
|
),
|
|
)
|
|
.for("no key update");
|
|
if (!run || (run.status !== "running" && !(completionIssueId !== undefined && run.status === "succeeded")))
|
|
throw forbidden(
|
|
"Credential acquisition requires this agent's active run",
|
|
);
|
|
const [pending] = await tx
|
|
.select()
|
|
.from(runIdentityContexts)
|
|
.where(
|
|
and(
|
|
eq(runIdentityContexts.runId, run.id),
|
|
eq(runIdentityContexts.status, "pending"),
|
|
),
|
|
)
|
|
.limit(1);
|
|
if (pending) {
|
|
const acknowledgement = await storedSteeringAcknowledgement(tx, pending);
|
|
if (!acknowledgement)
|
|
throw conflict(
|
|
"Message acceptance is being reconciled; retry credential acquisition",
|
|
);
|
|
await acceptSteeredIdentity(tx, pending);
|
|
run.activeIdentityContextId = pending.id;
|
|
run.responsibleUserId = pending.responsibleUserId;
|
|
}
|
|
const [context] = run.activeIdentityContextId
|
|
? await tx
|
|
.select()
|
|
.from(runIdentityContexts)
|
|
.where(
|
|
and(
|
|
eq(runIdentityContexts.id, run.activeIdentityContextId),
|
|
eq(runIdentityContexts.runId, run.id),
|
|
),
|
|
)
|
|
: [];
|
|
return { run, context: context ?? null } as RunIdentityCapture<Scope>;
|
|
});
|
|
}
|
|
|
|
export const requestRunIdentityFields = {
|
|
nativeIssueId: heartbeatRuns.nativeIssueId,
|
|
issueId: heartbeatRuns.issueId,
|
|
taskContext: runTaskContextColumn,
|
|
pendingIdentityContext: sql<boolean>`exists (select 1 from run_identity_contexts pending_context
|
|
where pending_context.run_id = "heartbeat_runs"."id" and pending_context.status = 'pending')`,
|
|
identityContext: sql<{ id: string; responsibleUserId: string | null } | null>`(select
|
|
jsonb_build_object('id', active_context.id, 'responsibleUserId', active_context.responsible_user_id)
|
|
from run_identity_contexts active_context
|
|
where active_context.id = "heartbeat_runs"."active_identity_context_id"
|
|
and active_context.run_id = "heartbeat_runs"."id")`,
|
|
};
|
|
|
|
type RequestRunIdentityRow = Pick<FullIdentityRun, "status" | "activeIdentityContextId" | "responsibleUserId"> & {
|
|
nativeIssueId?: string | null;
|
|
issueId?: string | null;
|
|
taskContext?: Record<string, unknown> | null;
|
|
pendingIdentityContext?: boolean | null;
|
|
identityContext?: { id: string; responsibleUserId: string | null } | null;
|
|
};
|
|
|
|
export async function resolveRequestRunIdentity(
|
|
db: Db,
|
|
input: { companyId: string; runId: string; agentId: string },
|
|
run: RequestRunIdentityRow,
|
|
): Promise<{ activeIdentityContextId: string | null; responsibleUserId: string | null }> {
|
|
if (!run.activeIdentityContextId || run.status !== "running") {
|
|
return { activeIdentityContextId: run.activeIdentityContextId, responsibleUserId: run.responsibleUserId };
|
|
}
|
|
if (run.pendingIdentityContext) {
|
|
const captured = await captureRunIdentity(db, input, { readScope: "request_authentication" });
|
|
return { activeIdentityContextId: captured.context?.id ?? null, responsibleUserId: captured.context?.responsibleUserId ?? null };
|
|
}
|
|
assertRunTaskIdentity({ nativeIssueId: run.nativeIssueId, issueId: run.issueId, contextSnapshot: run.taskContext });
|
|
return { activeIdentityContextId: run.identityContext?.id ?? null, responsibleUserId: run.identityContext?.responsibleUserId ?? null };
|
|
}
|
|
|
|
export async function listRunIdentityContexts(
|
|
db: Db,
|
|
companyId: string,
|
|
runId: string,
|
|
) {
|
|
return db
|
|
.select()
|
|
.from(runIdentityContexts)
|
|
.where(
|
|
and(
|
|
eq(runIdentityContexts.companyId, companyId),
|
|
eq(runIdentityContexts.runId, runId),
|
|
),
|
|
)
|
|
.orderBy(asc(runIdentityContexts.revision));
|
|
}
|
|
|
|
/** Late native acknowledgements settle reservations even when the HTTP caller timed out. */
|
|
export async function reconcileSteeredIdentity(
|
|
db: Db,
|
|
context: RunIdentityContext,
|
|
) {
|
|
await db.transaction(async (tx) => {
|
|
await lockIdentityTask(tx, context.companyId, context.runId);
|
|
const [run] = await tx
|
|
.select()
|
|
.from(heartbeatRuns)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRuns.id, context.runId),
|
|
eq(heartbeatRuns.companyId, context.companyId),
|
|
),
|
|
)
|
|
.for("no key update");
|
|
if (!run) return;
|
|
await acceptSteeredIdentity(tx, context);
|
|
});
|
|
}
|
|
|
|
/** Only events validated and persisted by the native control-plane transport count. */
|
|
export async function storedSteeringAcknowledgement(
|
|
executor: Pick<Db, "select">,
|
|
context: Pick<RunIdentityContext, "companyId" | "runId" | "messageId">,
|
|
) {
|
|
if (!context.messageId) return null;
|
|
const [receipt] = await executor
|
|
.select({ payload: heartbeatRunEvents.payload })
|
|
.from(heartbeatRunEvents)
|
|
.where(
|
|
and(
|
|
eq(heartbeatRunEvents.companyId, context.companyId),
|
|
eq(heartbeatRunEvents.runId, context.runId),
|
|
eq(heartbeatRunEvents.eventType, "item.completed"),
|
|
sql`${heartbeatRunEvents.sourceEventId} is not null`,
|
|
sql`${heartbeatRunEvents.payload}->'prpEvent'->'payload'->>'kind' = 'steering_acknowledgement'`,
|
|
sql`${heartbeatRunEvents.payload}->'prpEvent'->>'itemId' like ${`%:steer:${context.messageId}`}`,
|
|
),
|
|
)
|
|
.limit(1);
|
|
const event = receipt?.payload?.prpEvent as { turnId?: string } | undefined;
|
|
return typeof event?.turnId === "string" ? { turnId: event.turnId } : null;
|
|
}
|