mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 04:29:01 +01:00
refactor(trust): extract document source-trust resolution helpers
Extract resolveDocumentCreatedByRunId, resolveDocumentWriteSourceTrust, and resolveDocumentRestoreSourceTrust into server/src/services/document-source-trust.ts so server/src/services/documents.ts stays under 1,000 lines.
This commit is contained in:
1 parent
09de82f54d
commit
9431ad2830
2 files changed
+164
-104
No files matched your search
@@ -0,0 +1,136 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { documents, heartbeatRuns } from "@paperclipai/db";
|
||||
import { isUuidLike } from "@paperclipai/shared";
|
||||
import { HttpError } from "../errors.js";
|
||||
import {
|
||||
buildLowTrustSourceTrust,
|
||||
resolveActorSourceTrustForIssue,
|
||||
type SourceTrustIssueContext,
|
||||
} from "./source-trust.js";
|
||||
|
||||
type DocumentSourceTrust = typeof documents.$inferInsert.sourceTrust;
|
||||
|
||||
export async function resolveDocumentCreatedByRunId(
|
||||
dbOrTx: Pick<Db, "select">,
|
||||
companyId: string,
|
||||
runId: string | null | undefined,
|
||||
): Promise<string | null> {
|
||||
const normalized = typeof runId === "string" ? runId.trim() : "";
|
||||
if (!normalized || !isUuidLike(normalized)) return null;
|
||||
const existing = await dbOrTx
|
||||
.select({ id: heartbeatRuns.id })
|
||||
.from(heartbeatRuns)
|
||||
.where(and(eq(heartbeatRuns.id, normalized), eq(heartbeatRuns.companyId, companyId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
return existing?.id ?? null;
|
||||
}
|
||||
|
||||
export async function resolveDocumentWriteSourceTrust(input: {
|
||||
db: Db;
|
||||
issue: SourceTrustIssueContext;
|
||||
createdByAgentId?: string | null;
|
||||
createdByRunId?: string | null;
|
||||
explicitSourceTrust?: DocumentSourceTrust;
|
||||
}): Promise<{ createdByRunId: string | null; sourceTrust: DocumentSourceTrust }> {
|
||||
const createdByRunId = await resolveDocumentCreatedByRunId(
|
||||
input.db,
|
||||
input.issue.companyId,
|
||||
input.createdByRunId,
|
||||
);
|
||||
if (input.explicitSourceTrust !== undefined) {
|
||||
return { createdByRunId, sourceTrust: input.explicitSourceTrust };
|
||||
}
|
||||
if (!input.createdByAgentId) {
|
||||
return { createdByRunId, sourceTrust: null };
|
||||
}
|
||||
const sourceTrust = await resolveActorSourceTrustForIssue({
|
||||
db: input.db,
|
||||
issue: input.issue,
|
||||
actor: {
|
||||
actorType: "agent",
|
||||
actorId: input.createdByAgentId,
|
||||
agentId: input.createdByAgentId,
|
||||
runId: createdByRunId,
|
||||
},
|
||||
});
|
||||
return { createdByRunId, sourceTrust };
|
||||
}
|
||||
|
||||
export async function resolveDocumentRestoreSourceTrust(input: {
|
||||
db: Db;
|
||||
issue: SourceTrustIssueContext;
|
||||
restoringAgentId?: string | null;
|
||||
restoringUserId?: string | null;
|
||||
restoringRunId?: string | null;
|
||||
originalRevisionAgentId?: string | null;
|
||||
originalRevisionRunId?: string | null;
|
||||
}): Promise<{
|
||||
sourceTrust: DocumentSourceTrust;
|
||||
revisionCreatedByAgentId: string | null;
|
||||
revisionCreatedByUserId: string | null;
|
||||
revisionCreatedByRunId: string | null;
|
||||
}> {
|
||||
const createdByRunId = await resolveDocumentCreatedByRunId(
|
||||
input.db,
|
||||
input.issue.companyId,
|
||||
input.restoringRunId,
|
||||
);
|
||||
const actorSourceTrust = input.restoringAgentId
|
||||
? await resolveActorSourceTrustForIssue({
|
||||
db: input.db,
|
||||
issue: input.issue,
|
||||
actor: {
|
||||
actorType: "agent",
|
||||
actorId: input.restoringAgentId,
|
||||
agentId: input.restoringAgentId,
|
||||
runId: createdByRunId,
|
||||
},
|
||||
})
|
||||
: null;
|
||||
|
||||
const normalizedOriginalRunId = input.originalRevisionAgentId
|
||||
? await resolveDocumentCreatedByRunId(input.db, input.issue.companyId, input.originalRevisionRunId)
|
||||
: null;
|
||||
let restoredRevisionSourceTrust: DocumentSourceTrust = null;
|
||||
if (!actorSourceTrust && input.originalRevisionAgentId) {
|
||||
try {
|
||||
restoredRevisionSourceTrust = await resolveActorSourceTrustForIssue({
|
||||
db: input.db,
|
||||
issue: input.issue,
|
||||
actor: {
|
||||
actorType: "agent",
|
||||
actorId: input.originalRevisionAgentId,
|
||||
agentId: input.originalRevisionAgentId,
|
||||
runId: input.originalRevisionRunId ?? null,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
// If the original revision author's policy changed and now conflicts (403),
|
||||
// do not block the restore — fail closed by treating the restored content as quarantined.
|
||||
if (error instanceof HttpError && error.status === 403) {
|
||||
restoredRevisionSourceTrust = buildLowTrustSourceTrust({
|
||||
issueId: input.issue.id,
|
||||
runId: normalizedOriginalRunId,
|
||||
agentId: input.originalRevisionAgentId,
|
||||
});
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const preserveQuarantinedProvenance = Boolean(!actorSourceTrust && restoredRevisionSourceTrust);
|
||||
return {
|
||||
sourceTrust: actorSourceTrust ?? restoredRevisionSourceTrust ?? null,
|
||||
revisionCreatedByAgentId: preserveQuarantinedProvenance
|
||||
? (input.originalRevisionAgentId ?? null)
|
||||
: (input.restoringAgentId ?? null),
|
||||
revisionCreatedByUserId: preserveQuarantinedProvenance
|
||||
? null
|
||||
: (input.restoringUserId ?? null),
|
||||
revisionCreatedByRunId: preserveQuarantinedProvenance
|
||||
? normalizedOriginalRunId
|
||||
: createdByRunId,
|
||||
};
|
||||
}
|
||||
@@ -4,33 +4,21 @@ import { notifyIssueRecovery, notifyIssueGraphRecovery } from "./issue-recovery-
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, asc, desc, eq, inArray, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { documentRevisions, documents, heartbeatRuns, issueDocuments, issues } from "@paperclipai/db";
|
||||
import { ISSUE_DOCUMENT_BATCH_MAX_IDS, isSystemIssueDocumentKey, isUuidLike, issueDocumentKeySchema } from "@paperclipai/shared";
|
||||
import { HttpError, conflict, notFound, payloadTooLarge, unprocessable } from "../errors.js";
|
||||
import { documentRevisions, documents, issueDocuments, issues } from "@paperclipai/db";
|
||||
import { ISSUE_DOCUMENT_BATCH_MAX_IDS, isSystemIssueDocumentKey, issueDocumentKeySchema } from "@paperclipai/shared";
|
||||
import { conflict, notFound, payloadTooLarge, unprocessable } from "../errors.js";
|
||||
import { isUniqueViolation } from "../db-errors.js";
|
||||
import { insertRowsInChunks } from "./batch-insert.js";
|
||||
import type { ImportIssueDocumentRow } from "./import-write-types.js";
|
||||
import { emitPlanCreatedAfterCommit } from "./product-telemetry.js";
|
||||
import { buildLowTrustSourceTrust, resolveActorSourceTrustForIssue } from "./source-trust.js";
|
||||
import {
|
||||
resolveDocumentRestoreSourceTrust,
|
||||
resolveDocumentWriteSourceTrust,
|
||||
} from "./document-source-trust.js";
|
||||
|
||||
// Stay below download_artifact's 10 MiB limit, including JSON escaping and metadata.
|
||||
export const ISSUE_DOCUMENT_BATCH_MAX_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
async function resolveDocumentCreatedByRunId(
|
||||
dbOrTx: Pick<Db, "select">,
|
||||
companyId: string,
|
||||
runId: string | null | undefined,
|
||||
): Promise<string | null> {
|
||||
const normalized = typeof runId === "string" ? runId.trim() : "";
|
||||
if (!normalized || !isUuidLike(normalized)) return null;
|
||||
const existing = await dbOrTx
|
||||
.select({ id: heartbeatRuns.id })
|
||||
.from(heartbeatRuns)
|
||||
.where(and(eq(heartbeatRuns.id, normalized), eq(heartbeatRuns.companyId, companyId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
return existing?.id ?? null;
|
||||
}
|
||||
|
||||
function normalizeDocumentKey(key: string) {
|
||||
const normalized = key.trim().toLowerCase();
|
||||
const parsed = issueDocumentKeySchema.safeParse(normalized);
|
||||
@@ -338,31 +326,13 @@ export function documentService(db: Db) {
|
||||
], lock: true,
|
||||
});
|
||||
|
||||
const createdByRunId = await resolveDocumentCreatedByRunId(
|
||||
tx,
|
||||
issue.companyId,
|
||||
input.createdByRunId,
|
||||
);
|
||||
const resolvedSourceTrust =
|
||||
input.sourceTrust !== undefined
|
||||
? input.sourceTrust
|
||||
: input.createdByAgentId
|
||||
? await resolveActorSourceTrustForIssue({
|
||||
db: tx as unknown as Db,
|
||||
issue: {
|
||||
id: issue.id,
|
||||
companyId: issue.companyId,
|
||||
projectId: issue.projectId,
|
||||
executionPolicy: issue.executionPolicy,
|
||||
},
|
||||
actor: {
|
||||
actorType: "agent",
|
||||
actorId: input.createdByAgentId,
|
||||
agentId: input.createdByAgentId,
|
||||
runId: createdByRunId,
|
||||
},
|
||||
})
|
||||
: null;
|
||||
const { createdByRunId, sourceTrust: resolvedSourceTrust } = await resolveDocumentWriteSourceTrust({
|
||||
db: tx as unknown as Db,
|
||||
issue,
|
||||
createdByAgentId: input.createdByAgentId,
|
||||
createdByRunId: input.createdByRunId,
|
||||
explicitSourceTrust: input.sourceTrust,
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
if (existing.lockedAt) {
|
||||
@@ -778,55 +748,15 @@ export function documentService(db: Db) {
|
||||
});
|
||||
}
|
||||
|
||||
const createdByRunId = await resolveDocumentCreatedByRunId(
|
||||
tx,
|
||||
existing.companyId,
|
||||
input.createdByRunId,
|
||||
);
|
||||
const actorSourceTrust = input.createdByAgentId
|
||||
? await resolveActorSourceTrustForIssue({
|
||||
db: tx as unknown as Db,
|
||||
issue,
|
||||
actor: {
|
||||
actorType: "agent",
|
||||
actorId: input.createdByAgentId,
|
||||
agentId: input.createdByAgentId,
|
||||
runId: createdByRunId,
|
||||
},
|
||||
})
|
||||
: null;
|
||||
const originalRevisionRunId = revision.createdByAgentId
|
||||
? await resolveDocumentCreatedByRunId(tx, existing.companyId, revision.createdByRunId)
|
||||
: null;
|
||||
let restoredRevisionSourceTrust: typeof documents.$inferInsert.sourceTrust = null;
|
||||
if (!actorSourceTrust && revision.createdByAgentId) {
|
||||
try {
|
||||
restoredRevisionSourceTrust = await resolveActorSourceTrustForIssue({
|
||||
db: tx as unknown as Db,
|
||||
issue,
|
||||
actor: {
|
||||
actorType: "agent",
|
||||
actorId: revision.createdByAgentId,
|
||||
agentId: revision.createdByAgentId,
|
||||
runId: revision.createdByRunId ?? null,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
// If the original revision author's policy changed and now conflicts (403),
|
||||
// do not block the restore — fail closed by treating the restored content as quarantined.
|
||||
if (error instanceof HttpError && error.status === 403) {
|
||||
restoredRevisionSourceTrust = buildLowTrustSourceTrust({
|
||||
issueId: issue.id,
|
||||
runId: originalRevisionRunId,
|
||||
agentId: revision.createdByAgentId,
|
||||
});
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
const resolvedSourceTrust = actorSourceTrust ?? restoredRevisionSourceTrust ?? null;
|
||||
const preserveQuarantinedRevisionProvenance = Boolean(!actorSourceTrust && restoredRevisionSourceTrust);
|
||||
const restoreTrust = await resolveDocumentRestoreSourceTrust({
|
||||
db: tx as unknown as Db,
|
||||
issue,
|
||||
restoringAgentId: input.createdByAgentId,
|
||||
restoringUserId: input.createdByUserId,
|
||||
restoringRunId: input.createdByRunId,
|
||||
originalRevisionAgentId: revision.createdByAgentId,
|
||||
originalRevisionRunId: revision.createdByRunId,
|
||||
});
|
||||
|
||||
await notifyIssueGraphRecovery(tx, { companyId: existing.companyId, issueId: existing.issueId });
|
||||
const now = new Date();
|
||||
@@ -841,15 +771,9 @@ export function documentService(db: Db) {
|
||||
format: revision.format,
|
||||
body: revision.body,
|
||||
changeSummary: `Restored from revision ${revision.revisionNumber}`,
|
||||
createdByAgentId: preserveQuarantinedRevisionProvenance
|
||||
? revision.createdByAgentId
|
||||
: (input.createdByAgentId ?? null),
|
||||
createdByUserId: preserveQuarantinedRevisionProvenance
|
||||
? null
|
||||
: (input.createdByUserId ?? null),
|
||||
createdByRunId: preserveQuarantinedRevisionProvenance
|
||||
? originalRevisionRunId
|
||||
: createdByRunId,
|
||||
createdByAgentId: restoreTrust.revisionCreatedByAgentId,
|
||||
createdByUserId: restoreTrust.revisionCreatedByUserId,
|
||||
createdByRunId: restoreTrust.revisionCreatedByRunId,
|
||||
createdAt: now,
|
||||
})
|
||||
.returning();
|
||||
@@ -865,7 +789,7 @@ export function documentService(db: Db) {
|
||||
latestRevisionNumber: nextRevisionNumber,
|
||||
updatedByAgentId: input.createdByAgentId ?? null,
|
||||
updatedByUserId: input.createdByUserId ?? null,
|
||||
sourceTrust: resolvedSourceTrust,
|
||||
sourceTrust: restoreTrust.sourceTrust,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(eq(documents.id, existing.id));
|
||||
@@ -888,7 +812,7 @@ export function documentService(db: Db) {
|
||||
latestRevisionNumber: nextRevisionNumber,
|
||||
updatedByAgentId: input.createdByAgentId ?? null,
|
||||
updatedByUserId: input.createdByUserId ?? null,
|
||||
sourceTrust: resolvedSourceTrust,
|
||||
sourceTrust: restoreTrust.sourceTrust,
|
||||
updatedAt: now,
|
||||
},
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user