mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The low-trust review preset isolates untrusted agent runs and marks their raw outputs with `sourceTrust` quarantine metadata so higher-trust agents do not ingest raw output without promotion > - HTTP route writes tagged low-trust comments and documents with `sourceTrust`, but internal native completion replies, finalizer recoveries, continuation summary updates, and non-Muse native runner tool writes (`report_progress`, `write_document`) persisted `sourceTrust: null` > - Higher-trust non-Muse native runner reads (`list_documents`, `read_document`) also bypassed document quarantine redaction > - This pull request resolves `sourceTrust` centrally in `issueService.addComment` and `documentService.upsertIssueDocument` whenever an agent writes without an explicit `sourceTrust` value, removes the `museRuntime` gate on native runner `report_progress` and `write_document` writes, and redacts quarantined documents on higher-trust non-Muse native runner reads > - The benefit is that raw outputs from low-trust native runs retain quarantine metadata across all comment and document write paths and stay redacted from higher-trust agents until promoted ## Linked Issues or Issue Description **What happened?** When an agent running under the `low_trust_review` preset completed a native run or called native runner tools (`report_progress`, `write_document`), its comments and documents were saved with `sourceTrust: null`. Because `sourceTrust` was null, higher-trust agents could read the raw low-trust output directly through ordinary comment and document access without promotion. **Expected behavior** All agent-authored comments and documents produced under `low_trust_review`—including native run completion replies, recovered finalizer replies, continuation summary updates, and non-Muse native runner `report_progress` / `write_document` writes—must persist `sourceTrust` with `preset: "low_trust_review"` and `disposition: "quarantined"`, and higher-trust agents must receive the quarantined redaction placeholder instead of the raw body. **Steps to reproduce** 1. Configure an agent with `trustPreset: "low_trust_review"` and a valid `trustBoundary`. 2. Run a native task on that agent so it writes a completion reply, calls `report_progress` or `write_document`, or refreshes `continuation-summary`. 3. Read the resulting comment or document as a standard-trust agent via `get_task_history`, `list_documents`, `read_document`, or ordinary comment reads. 4. Before this fix, `sourceTrust` is `null` and the raw body is returned unredacted. **Paperclip version or commit** `master` (`ce204a223a`) ## What Changed - **`server/src/services/issues.ts`**: Updated `issueService.addComment` to select `projectId` and `executionPolicy` on the target issue and resolve `sourceTrust` via `resolveActorSourceTrustForIssue` whenever `actor.agentId` is set and `options?.sourceTrust === undefined`. This covers native run completion replies (`run-completion.ts`), recovered finalizer replies (`native-run-finalizer.ts`), status decision committer comments (`status-decision-committer.ts`), and internal agent comment writes. - **`server/src/services/documents.ts`**: Updated `documentService.upsertIssueDocument` to select `projectId` and `executionPolicy` on the target issue and resolve `sourceTrust` via `resolveActorSourceTrustForIssue` whenever `input.createdByAgentId` is set and `input.sourceTrust === undefined`. This covers continuation summary refreshes (`issue-continuation-summary.ts`), native plan writes (`native-session-executor.ts`), and internal agent document writes. - **`server/src/services/native-runtime/paperclip-runner-tool-authority.ts`**: Removed the `this.binding.museRuntime` guard on `resolveActorSourceTrustForIssue` in `report_progress` and `write_document` so all `paperclip_runner` runs tag writes consistently, and added higher-trust quarantine redaction (`redactQuarantinedBodyForHigherTrust`) for non-Muse `list_documents` and `read_document` reads. - **`server/src/__tests__/source-trust.test.ts`**: Added red-green regression tests covering `addComment` without explicit `sourceTrust`, `upsertIssueDocument` without explicit `sourceTrust`, and non-Muse `PaperclipRunnerToolAuthority` `report_progress` / `write_document` writes read by a higher-trust agent via `get_task_history`, `list_documents`, and `read_document`. ## Verification - Confirmed the new regression tests failed before the fix (`sourceTrust` received `null` on `addComment` and `upsertIssueDocument`). - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/source-trust.test.ts` — 10/10 passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/low-trust-red-team-routes.test.ts` — 14/14 passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/issue-continuation-summary.test.ts` — 8/8 passed. - `pnpm --filter @paperclipai/server typecheck` — passed with 0 errors. - `pnpm verify` exited 2 (broad CI coverage required); CI will run the full required check matrix on this PR. ## Risks - Low risk. Standard-trust agent writes continue to resolve to `sourceTrust: null` (unchanged behavior). - Callers that already pass an explicit `sourceTrust` value (such as promotion flows or HTTP routes) keep their explicit value without extra work. - Only newly inserted comments and agent-authored document upserts without an explicit `sourceTrust` perform the policy lookup inside the existing transaction. ## Model Used - Google Gemini (Antigravity agentic coding assistant) 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [ ] I will address all Greptile and reviewer comments before requesting merge
966 lines
39 KiB
TypeScript
966 lines
39 KiB
TypeScript
import { notifyStatusCardIssueChange } from "./status-card-notifications.js";
|
|
import { assertAgentInteraction } from "./agent-interaction-policy.js";
|
|
import { notifyIssueRecovery, notifyIssueGraphRecovery } from "./issue-recovery-notifications.js";
|
|
import { randomUUID } from "node:crypto";
|
|
import { and, asc, desc, eq, inArray, sql } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
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 {
|
|
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;
|
|
|
|
function normalizeDocumentKey(key: string) {
|
|
const normalized = key.trim().toLowerCase();
|
|
const parsed = issueDocumentKeySchema.safeParse(normalized);
|
|
if (!parsed.success) {
|
|
throw unprocessable("Invalid document key", parsed.error.issues);
|
|
}
|
|
return parsed.data;
|
|
}
|
|
|
|
function nextAvailableDocumentKey(sourceKey: string, existingKeys: string[]) {
|
|
const usedKeys = new Set(existingKeys);
|
|
for (let index = 2; index < 1000; index += 1) {
|
|
const suffix = `-${index}`;
|
|
const baseMaxLength = 64 - suffix.length;
|
|
const base = sourceKey.slice(0, baseMaxLength).replace(/[-_]+$/g, "") || "document";
|
|
const candidate = `${base}${suffix}`;
|
|
if (!usedKeys.has(candidate) && issueDocumentKeySchema.safeParse(candidate).success) {
|
|
return candidate;
|
|
}
|
|
}
|
|
throw conflict("Unable to choose a new document key for locked document", { key: sourceKey });
|
|
}
|
|
|
|
export function extractLegacyPlanBody(description: string | null | undefined) {
|
|
if (!description) return null;
|
|
const match = /<plan>\s*([\s\S]*?)\s*<\/plan>/i.exec(description);
|
|
if (!match) return null;
|
|
const body = match[1]?.trim();
|
|
return body ? body : null;
|
|
}
|
|
|
|
export function mapIssueDocumentRow(
|
|
row: {
|
|
id: string;
|
|
companyId: string;
|
|
issueId: string;
|
|
key: string;
|
|
title: string | null;
|
|
format: string;
|
|
latestBody: string;
|
|
latestRevisionId: string | null;
|
|
latestRevisionNumber: number;
|
|
createdByAgentId: string | null;
|
|
createdByUserId: string | null;
|
|
updatedByAgentId: string | null;
|
|
updatedByUserId: string | null;
|
|
lockedAt: Date | null;
|
|
lockedByAgentId: string | null;
|
|
lockedByUserId: string | null;
|
|
sourceTrust: typeof documents.$inferSelect.sourceTrust;
|
|
createdAt: Date;
|
|
updatedAt: Date;
|
|
},
|
|
includeBody: boolean,
|
|
) {
|
|
return {
|
|
id: row.id,
|
|
companyId: row.companyId,
|
|
issueId: row.issueId,
|
|
key: row.key,
|
|
title: row.title,
|
|
format: row.format,
|
|
...(includeBody ? { body: row.latestBody } : {}),
|
|
latestRevisionId: row.latestRevisionId ?? null,
|
|
latestRevisionNumber: row.latestRevisionNumber,
|
|
createdByAgentId: row.createdByAgentId,
|
|
createdByUserId: row.createdByUserId,
|
|
updatedByAgentId: row.updatedByAgentId,
|
|
updatedByUserId: row.updatedByUserId,
|
|
lockedAt: row.lockedAt,
|
|
lockedByAgentId: row.lockedByAgentId,
|
|
lockedByUserId: row.lockedByUserId,
|
|
sourceTrust: row.sourceTrust ?? null,
|
|
createdAt: row.createdAt,
|
|
updatedAt: row.updatedAt,
|
|
};
|
|
}
|
|
|
|
export const issueDocumentSelect = {
|
|
id: documents.id,
|
|
companyId: documents.companyId,
|
|
issueId: issueDocuments.issueId,
|
|
key: issueDocuments.key,
|
|
title: documents.title,
|
|
format: documents.format,
|
|
latestBody: documents.latestBody,
|
|
latestRevisionId: documents.latestRevisionId,
|
|
latestRevisionNumber: documents.latestRevisionNumber,
|
|
createdByAgentId: documents.createdByAgentId,
|
|
createdByUserId: documents.createdByUserId,
|
|
updatedByAgentId: documents.updatedByAgentId,
|
|
updatedByUserId: documents.updatedByUserId,
|
|
lockedAt: documents.lockedAt,
|
|
lockedByAgentId: documents.lockedByAgentId,
|
|
lockedByUserId: documents.lockedByUserId,
|
|
sourceTrust: documents.sourceTrust,
|
|
createdAt: documents.createdAt,
|
|
updatedAt: documents.updatedAt,
|
|
};
|
|
|
|
export function documentService(db: Db) {
|
|
const filterSystemDocuments = <T extends { key: string }>(rows: T[], includeSystem: boolean) =>
|
|
includeSystem ? rows : rows.filter((row) => !isSystemIssueDocumentKey(row.key));
|
|
|
|
return {
|
|
getIssueDocumentPayload: async (
|
|
issue: { id: string; description: string | null },
|
|
options: { includeSystem?: boolean } = {},
|
|
) => {
|
|
const [planDocument, documentSummaries] = await Promise.all([
|
|
db
|
|
.select(issueDocumentSelect)
|
|
.from(issueDocuments)
|
|
.innerJoin(documents, eq(issueDocuments.documentId, documents.id))
|
|
.where(and(eq(issueDocuments.issueId, issue.id), eq(issueDocuments.key, "plan")))
|
|
.then((rows) => rows[0] ?? null),
|
|
db
|
|
.select({ ...issueDocumentSelect, latestBody: sql<string>`''` })
|
|
.from(issueDocuments)
|
|
.innerJoin(documents, eq(issueDocuments.documentId, documents.id))
|
|
.where(eq(issueDocuments.issueId, issue.id))
|
|
.orderBy(asc(issueDocuments.key), desc(documents.updatedAt)),
|
|
]);
|
|
|
|
const legacyPlanBody = planDocument ? null : extractLegacyPlanBody(issue.description);
|
|
|
|
return {
|
|
planDocument: planDocument ? mapIssueDocumentRow(planDocument, true) : null,
|
|
documentSummaries: filterSystemDocuments(documentSummaries, options.includeSystem ?? false)
|
|
.map((row) => mapIssueDocumentRow(row, false)),
|
|
legacyPlanDocument: legacyPlanBody
|
|
? {
|
|
key: "plan" as const,
|
|
body: legacyPlanBody,
|
|
source: "issue_description" as const,
|
|
}
|
|
: null,
|
|
};
|
|
},
|
|
|
|
listIssueDocuments: async (issueId: string, options: { includeSystem?: boolean } = {}) => {
|
|
const rows = await db
|
|
.select(issueDocumentSelect)
|
|
.from(issueDocuments)
|
|
.innerJoin(documents, eq(issueDocuments.documentId, documents.id))
|
|
.where(eq(issueDocuments.issueId, issueId))
|
|
.orderBy(asc(issueDocuments.key), desc(documents.updatedAt));
|
|
return filterSystemDocuments(rows, options.includeSystem ?? false).map((row) => mapIssueDocumentRow(row, true));
|
|
},
|
|
|
|
getIssueDocumentByKey: async (issueId: string, rawKey: string) => {
|
|
const key = normalizeDocumentKey(rawKey);
|
|
const row = await db
|
|
.select(issueDocumentSelect)
|
|
.from(issueDocuments)
|
|
.innerJoin(documents, eq(issueDocuments.documentId, documents.id))
|
|
.where(and(eq(issueDocuments.issueId, issueId), eq(issueDocuments.key, key)))
|
|
.then((rows) => rows[0] ?? null);
|
|
return row ? mapIssueDocumentRow(row, true) : null;
|
|
},
|
|
|
|
/** Caller authorizes the task set first. One query reads only the requested key. */
|
|
getIssueDocumentsByKey: async (companyId: string, issueIds: string[], rawKey: string, includeBody = true) => {
|
|
const key = normalizeDocumentKey(rawKey);
|
|
if (issueIds.length > ISSUE_DOCUMENT_BATCH_MAX_IDS) throw unprocessable("Too many issue document IDs");
|
|
if (!issueIds.length) return [];
|
|
const join = and(eq(issueDocuments.documentId, documents.id), eq(documents.companyId, companyId));
|
|
const condition = and(eq(issueDocuments.companyId, companyId), inArray(issueDocuments.issueId, issueIds), eq(issueDocuments.key, key));
|
|
const read = async (connection: Db) => {
|
|
if (includeBody) {
|
|
// PostgreSQL counts encoded JSON one body at a time; no bodies cross
|
|
// into the app before the entire set fits. The same snapshot below
|
|
// prevents a concurrent edit from growing the admitted response.
|
|
const [size] = await connection.select({ bytes: sql<string>`coalesce(sum(octet_length(to_json(${documents.latestBody})::text)), 0)` })
|
|
.from(issueDocuments).innerJoin(documents, join).where(condition);
|
|
if (Number(size.bytes) > ISSUE_DOCUMENT_BATCH_MAX_BYTES) {
|
|
throw payloadTooLarge("Document batch exceeds 8 MiB; split issueIds into smaller requests or use includeBody=false", { maxResponseBytes: ISSUE_DOCUMENT_BATCH_MAX_BYTES });
|
|
}
|
|
}
|
|
const rows = await connection
|
|
.select({ ...issueDocumentSelect, latestBody: includeBody ? documents.latestBody : sql<string>`''` })
|
|
.from(issueDocuments).innerJoin(documents, join).where(condition);
|
|
return rows.map(row => mapIssueDocumentRow(row, includeBody));
|
|
};
|
|
return includeBody
|
|
? db.transaction(tx => read(tx as unknown as Db), { isolationLevel: "repeatable read", accessMode: "read only" })
|
|
: read(db);
|
|
},
|
|
|
|
/** Bounded receipt read: never load every historical body for one revision. */
|
|
getIssueDocumentRevision: async (issueId: string, rawKey: string, revisionId: string) => {
|
|
const key = normalizeDocumentKey(rawKey);
|
|
const [revision] = await db.select({
|
|
id: documentRevisions.id, companyId: documentRevisions.companyId,
|
|
documentId: documentRevisions.documentId, issueId: issueDocuments.issueId, key: issueDocuments.key,
|
|
revisionNumber: documentRevisions.revisionNumber, title: documentRevisions.title,
|
|
format: documentRevisions.format, body: documentRevisions.body, changeSummary: documentRevisions.changeSummary,
|
|
createdByAgentId: documentRevisions.createdByAgentId, createdByUserId: documentRevisions.createdByUserId,
|
|
createdByRunId: documentRevisions.createdByRunId, createdAt: documentRevisions.createdAt,
|
|
latestRevisionId: documents.latestRevisionId, latestRevisionNumber: documents.latestRevisionNumber,
|
|
}).from(issueDocuments)
|
|
.innerJoin(documents, eq(issueDocuments.documentId, documents.id))
|
|
.innerJoin(documentRevisions, and(eq(documentRevisions.documentId, documents.id), eq(documentRevisions.companyId, documents.companyId)))
|
|
.where(and(eq(issueDocuments.issueId, issueId), eq(issueDocuments.key, key), eq(documentRevisions.id, revisionId))).limit(1);
|
|
return revision ? { ...revision, isLatest: revision.latestRevisionId === revision.id } : null;
|
|
},
|
|
|
|
listIssueDocumentRevisions: async (issueId: string, rawKey: string, options: { limit?: number } = {}) => {
|
|
const key = normalizeDocumentKey(rawKey);
|
|
const query = db
|
|
.select({
|
|
id: documentRevisions.id,
|
|
companyId: documentRevisions.companyId,
|
|
documentId: documentRevisions.documentId,
|
|
issueId: issueDocuments.issueId,
|
|
key: issueDocuments.key,
|
|
revisionNumber: documentRevisions.revisionNumber,
|
|
title: documentRevisions.title,
|
|
format: documentRevisions.format,
|
|
body: documentRevisions.body,
|
|
changeSummary: documentRevisions.changeSummary,
|
|
createdByAgentId: documentRevisions.createdByAgentId,
|
|
createdByUserId: documentRevisions.createdByUserId,
|
|
createdByRunId: documentRevisions.createdByRunId,
|
|
createdAt: documentRevisions.createdAt,
|
|
})
|
|
.from(issueDocuments)
|
|
.innerJoin(documents, eq(issueDocuments.documentId, documents.id))
|
|
.innerJoin(documentRevisions, eq(documentRevisions.documentId, documents.id))
|
|
.where(and(eq(issueDocuments.issueId, issueId), eq(issueDocuments.key, key)))
|
|
.orderBy(desc(documentRevisions.revisionNumber));
|
|
// Newest first, so a limit keeps the most recent revisions.
|
|
return options.limit === undefined ? query : query.limit(options.limit);
|
|
},
|
|
|
|
upsertIssueDocument: async (input: {
|
|
issueId: string;
|
|
key: string;
|
|
title?: string | null;
|
|
format: string;
|
|
body: string;
|
|
changeSummary?: string | null;
|
|
baseRevisionId?: string | null;
|
|
createdByAgentId?: string | null;
|
|
createdByUserId?: string | null;
|
|
createdByRunId?: string | null;
|
|
sourceTrust?: typeof documents.$inferInsert.sourceTrust;
|
|
lockedDocumentStrategy?: "conflict" | "create_new_document";
|
|
}, options: { initialTaskCreation?: boolean } = {}) => {
|
|
const key = normalizeDocumentKey(input.key);
|
|
const issue = await db
|
|
.select({
|
|
id: issues.id,
|
|
companyId: issues.companyId,
|
|
projectId: issues.projectId,
|
|
executionPolicy: issues.executionPolicy,
|
|
createdByUserId: issues.createdByUserId,
|
|
responsibleUserId: issues.responsibleUserId,
|
|
})
|
|
.from(issues)
|
|
.where(eq(issues.id, input.issueId))
|
|
.then((rows) => rows[0] ?? null);
|
|
if (!issue) throw notFound("Issue not found");
|
|
|
|
const maxAttempts = input.lockedDocumentStrategy === "create_new_document" ? 3 : 1;
|
|
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
|
try {
|
|
return await db.transaction(async (tx) => {
|
|
await notifyStatusCardIssueChange(tx, issue.companyId);
|
|
const now = new Date();
|
|
const existing = await tx
|
|
.select({
|
|
id: documents.id,
|
|
companyId: documents.companyId,
|
|
issueId: issueDocuments.issueId,
|
|
key: issueDocuments.key,
|
|
title: documents.title,
|
|
format: documents.format,
|
|
latestBody: documents.latestBody,
|
|
latestRevisionId: documents.latestRevisionId,
|
|
latestRevisionNumber: documents.latestRevisionNumber,
|
|
createdByAgentId: documents.createdByAgentId,
|
|
createdByUserId: documents.createdByUserId,
|
|
updatedByAgentId: documents.updatedByAgentId,
|
|
updatedByUserId: documents.updatedByUserId,
|
|
lockedAt: documents.lockedAt,
|
|
lockedByAgentId: documents.lockedByAgentId,
|
|
lockedByUserId: documents.lockedByUserId,
|
|
sourceTrust: documents.sourceTrust,
|
|
createdAt: documents.createdAt,
|
|
updatedAt: documents.updatedAt,
|
|
})
|
|
.from(issueDocuments)
|
|
.innerJoin(documents, eq(issueDocuments.documentId, documents.id))
|
|
.where(and(eq(issueDocuments.issueId, issue.id), eq(issueDocuments.key, key)))
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
await assertAgentInteraction(tx, {
|
|
companyId: issue.companyId, actorAgentId: input.createdByAgentId,
|
|
operation: options.initialTaskCreation && !existing ? "mention" : "edit", issueId: issue.id,
|
|
texts: [
|
|
...(!existing || input.body !== existing.latestBody ? [input.body] : []),
|
|
...(input.title !== undefined && input.title !== existing?.title ? [input.title ?? ""] : []),
|
|
input.changeSummary ?? "",
|
|
], lock: true,
|
|
});
|
|
|
|
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) {
|
|
if (input.lockedDocumentStrategy === "create_new_document") {
|
|
const issueDocumentKeys = await tx
|
|
.select({ key: issueDocuments.key })
|
|
.from(issueDocuments)
|
|
.where(eq(issueDocuments.issueId, issue.id));
|
|
const fallbackKey = nextAvailableDocumentKey(key, issueDocumentKeys.map((row) => row.key));
|
|
|
|
await notifyIssueGraphRecovery(tx, { companyId: issue.companyId, issueId: issue.id });
|
|
const [document] = await tx
|
|
.insert(documents)
|
|
.values({
|
|
companyId: issue.companyId,
|
|
title: input.title ?? null,
|
|
format: input.format,
|
|
latestBody: input.body,
|
|
latestRevisionId: null,
|
|
latestRevisionNumber: 1,
|
|
createdByAgentId: input.createdByAgentId ?? null,
|
|
createdByUserId: input.createdByUserId ?? null,
|
|
updatedByAgentId: input.createdByAgentId ?? null,
|
|
updatedByUserId: input.createdByUserId ?? null,
|
|
lockedAt: null,
|
|
lockedByAgentId: null,
|
|
lockedByUserId: null,
|
|
sourceTrust: resolvedSourceTrust ?? null,
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
})
|
|
.returning();
|
|
|
|
const [revision] = await tx
|
|
.insert(documentRevisions)
|
|
.values({
|
|
companyId: issue.companyId,
|
|
documentId: document.id,
|
|
revisionNumber: 1,
|
|
title: input.title ?? null,
|
|
format: input.format,
|
|
body: input.body,
|
|
changeSummary: input.changeSummary ?? null,
|
|
createdByAgentId: input.createdByAgentId ?? null,
|
|
createdByUserId: input.createdByUserId ?? null,
|
|
createdByRunId,
|
|
createdAt: now,
|
|
})
|
|
.returning();
|
|
|
|
await tx
|
|
.update(documents)
|
|
.set({ latestRevisionId: revision.id })
|
|
.where(eq(documents.id, document.id));
|
|
|
|
await tx.insert(issueDocuments).values({
|
|
companyId: issue.companyId,
|
|
issueId: issue.id,
|
|
documentId: document.id,
|
|
key: fallbackKey,
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
});
|
|
|
|
return {
|
|
created: true as const,
|
|
redirectedFromLockedDocument: {
|
|
id: existing.id,
|
|
key: existing.key,
|
|
},
|
|
document: {
|
|
id: document.id,
|
|
companyId: issue.companyId,
|
|
issueId: issue.id,
|
|
key: fallbackKey,
|
|
title: document.title,
|
|
format: document.format,
|
|
body: document.latestBody,
|
|
latestRevisionId: revision.id,
|
|
latestRevisionNumber: 1,
|
|
createdByAgentId: document.createdByAgentId,
|
|
createdByUserId: document.createdByUserId,
|
|
updatedByAgentId: document.updatedByAgentId,
|
|
updatedByUserId: document.updatedByUserId,
|
|
lockedAt: null,
|
|
lockedByAgentId: null,
|
|
lockedByUserId: null,
|
|
sourceTrust: document.sourceTrust ?? null,
|
|
createdAt: document.createdAt,
|
|
updatedAt: document.updatedAt,
|
|
},
|
|
};
|
|
}
|
|
|
|
throw conflict("Document is locked", {
|
|
key: existing.key,
|
|
documentId: existing.id,
|
|
lockedAt: existing.lockedAt,
|
|
});
|
|
}
|
|
|
|
if (!input.baseRevisionId) {
|
|
throw conflict("Document update requires baseRevisionId. GET the current document, read its body and latestRevisionId, then set baseRevisionId to that latestRevisionId when updating.", {
|
|
currentRevisionId: existing.latestRevisionId,
|
|
});
|
|
}
|
|
if (input.baseRevisionId !== existing.latestRevisionId) {
|
|
throw conflict("Document was updated by someone else", {
|
|
currentRevisionId: existing.latestRevisionId,
|
|
});
|
|
}
|
|
|
|
await notifyIssueGraphRecovery(tx, { companyId: issue.companyId, issueId: issue.id });
|
|
const nextRevisionNumber = existing.latestRevisionNumber + 1;
|
|
const [revision] = await tx
|
|
.insert(documentRevisions)
|
|
.values({
|
|
companyId: issue.companyId,
|
|
documentId: existing.id,
|
|
revisionNumber: nextRevisionNumber,
|
|
title: input.title ?? null,
|
|
format: input.format,
|
|
body: input.body,
|
|
changeSummary: input.changeSummary ?? null,
|
|
createdByAgentId: input.createdByAgentId ?? null,
|
|
createdByUserId: input.createdByUserId ?? null,
|
|
createdByRunId,
|
|
createdAt: now,
|
|
})
|
|
.returning();
|
|
|
|
await tx
|
|
.update(documents)
|
|
.set({
|
|
title: input.title ?? null,
|
|
format: input.format,
|
|
latestBody: input.body,
|
|
latestRevisionId: revision.id,
|
|
latestRevisionNumber: nextRevisionNumber,
|
|
updatedByAgentId: input.createdByAgentId ?? null,
|
|
updatedByUserId: input.createdByUserId ?? null,
|
|
sourceTrust: resolvedSourceTrust ?? null,
|
|
updatedAt: now,
|
|
})
|
|
.where(eq(documents.id, existing.id));
|
|
|
|
await tx
|
|
.update(issueDocuments)
|
|
.set({ updatedAt: now })
|
|
.where(eq(issueDocuments.documentId, existing.id));
|
|
|
|
const { latestBody: _previousBody, ...existingMetadata } = existing;
|
|
return {
|
|
created: false as const,
|
|
document: {
|
|
...existingMetadata,
|
|
title: input.title ?? null,
|
|
format: input.format,
|
|
body: input.body,
|
|
latestRevisionId: revision.id,
|
|
latestRevisionNumber: nextRevisionNumber,
|
|
updatedByAgentId: input.createdByAgentId ?? null,
|
|
updatedByUserId: input.createdByUserId ?? null,
|
|
lockedAt: existing.lockedAt,
|
|
lockedByAgentId: existing.lockedByAgentId,
|
|
lockedByUserId: existing.lockedByUserId,
|
|
sourceTrust: resolvedSourceTrust ?? null,
|
|
updatedAt: now,
|
|
},
|
|
};
|
|
}
|
|
|
|
if (input.baseRevisionId) {
|
|
throw conflict("Document does not exist yet", { key });
|
|
}
|
|
|
|
await notifyIssueGraphRecovery(tx, { companyId: issue.companyId, issueId: issue.id });
|
|
const [document] = await tx
|
|
.insert(documents)
|
|
.values({
|
|
companyId: issue.companyId,
|
|
title: input.title ?? null,
|
|
format: input.format,
|
|
latestBody: input.body,
|
|
latestRevisionId: null,
|
|
latestRevisionNumber: 1,
|
|
createdByAgentId: input.createdByAgentId ?? null,
|
|
createdByUserId: input.createdByUserId ?? null,
|
|
updatedByAgentId: input.createdByAgentId ?? null,
|
|
updatedByUserId: input.createdByUserId ?? null,
|
|
lockedAt: null,
|
|
lockedByAgentId: null,
|
|
lockedByUserId: null,
|
|
sourceTrust: resolvedSourceTrust ?? null,
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
})
|
|
.returning();
|
|
|
|
const [revision] = await tx
|
|
.insert(documentRevisions)
|
|
.values({
|
|
companyId: issue.companyId,
|
|
documentId: document.id,
|
|
revisionNumber: 1,
|
|
title: input.title ?? null,
|
|
format: input.format,
|
|
body: input.body,
|
|
changeSummary: input.changeSummary ?? null,
|
|
createdByAgentId: input.createdByAgentId ?? null,
|
|
createdByUserId: input.createdByUserId ?? null,
|
|
createdByRunId,
|
|
createdAt: now,
|
|
})
|
|
.returning();
|
|
|
|
await tx
|
|
.update(documents)
|
|
.set({ latestRevisionId: revision.id })
|
|
.where(eq(documents.id, document.id));
|
|
|
|
await tx.insert(issueDocuments).values({
|
|
companyId: issue.companyId,
|
|
issueId: issue.id,
|
|
documentId: document.id,
|
|
key,
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
});
|
|
if (key === "plan") {
|
|
emitPlanCreatedAfterCommit({
|
|
companyId: issue.companyId,
|
|
createdByAgentId: input.createdByAgentId,
|
|
createdByUserId: input.createdByUserId,
|
|
atTaskCreation: options.initialTaskCreation === true,
|
|
task: issue,
|
|
});
|
|
}
|
|
|
|
return {
|
|
created: true as const,
|
|
document: {
|
|
id: document.id,
|
|
companyId: issue.companyId,
|
|
issueId: issue.id,
|
|
key,
|
|
title: document.title,
|
|
format: document.format,
|
|
body: document.latestBody,
|
|
latestRevisionId: revision.id,
|
|
latestRevisionNumber: 1,
|
|
createdByAgentId: document.createdByAgentId,
|
|
createdByUserId: document.createdByUserId,
|
|
updatedByAgentId: document.updatedByAgentId,
|
|
updatedByUserId: document.updatedByUserId,
|
|
lockedAt: document.lockedAt,
|
|
lockedByAgentId: document.lockedByAgentId,
|
|
lockedByUserId: document.lockedByUserId,
|
|
sourceTrust: document.sourceTrust ?? null,
|
|
createdAt: document.createdAt,
|
|
updatedAt: document.updatedAt,
|
|
},
|
|
};
|
|
});
|
|
} catch (error) {
|
|
if (isUniqueViolation(error, "issue_documents_company_issue_key_uq")) {
|
|
if (input.lockedDocumentStrategy === "create_new_document" && attempt < maxAttempts - 1) {
|
|
continue;
|
|
}
|
|
throw conflict("Document key already exists on this issue", { key });
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
throw conflict("Unable to choose a new document key for locked document", { key });
|
|
},
|
|
|
|
/**
|
|
* Batched issue-document insert for company import.
|
|
*
|
|
* Every imported document is a fresh create (the issue is brand new), so we
|
|
* skip {@link upsertIssueDocument}'s per-row existence/lock/base-revision
|
|
* dance and the follow-up latest-revision update: ids are pre-generated so
|
|
* `latest_revision_id` can be written inline. Documents, their initial
|
|
* revisions, and the issue links are each inserted in chunked statements.
|
|
*/
|
|
createIssueDocumentsForImport: async (rows: ImportIssueDocumentRow[]): Promise<void> => {
|
|
if (rows.length === 0) return;
|
|
const now = new Date();
|
|
const documentRows: Array<Record<string, unknown>> = [];
|
|
const revisionRows: Array<Record<string, unknown>> = [];
|
|
const linkRows: Array<Record<string, unknown>> = [];
|
|
for (const row of rows) {
|
|
const key = normalizeDocumentKey(row.key);
|
|
const documentId = randomUUID();
|
|
const revisionId = randomUUID();
|
|
documentRows.push({
|
|
id: documentId,
|
|
companyId: row.companyId,
|
|
title: row.title ?? null,
|
|
format: row.format,
|
|
latestBody: row.body,
|
|
latestRevisionId: revisionId,
|
|
latestRevisionNumber: 1,
|
|
createdByAgentId: row.createdByAgentId ?? null,
|
|
createdByUserId: row.createdByUserId ?? null,
|
|
updatedByAgentId: row.createdByAgentId ?? null,
|
|
updatedByUserId: row.createdByUserId ?? null,
|
|
lockedAt: null,
|
|
lockedByAgentId: null,
|
|
lockedByUserId: null,
|
|
sourceTrust: row.sourceTrust ?? null,
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
});
|
|
revisionRows.push({
|
|
id: revisionId,
|
|
companyId: row.companyId,
|
|
documentId,
|
|
revisionNumber: 1,
|
|
title: row.title ?? null,
|
|
format: row.format,
|
|
body: row.body,
|
|
changeSummary: null,
|
|
createdByAgentId: row.createdByAgentId ?? null,
|
|
createdByUserId: row.createdByUserId ?? null,
|
|
createdByRunId: row.createdByRunId ?? null,
|
|
createdAt: now,
|
|
});
|
|
linkRows.push({
|
|
companyId: row.companyId,
|
|
issueId: row.issueId,
|
|
documentId,
|
|
key,
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
});
|
|
}
|
|
await db.transaction(async (tx) => {
|
|
for (const companyId of new Set(rows.map(row => row.companyId))) {
|
|
await notifyStatusCardIssueChange(tx, companyId);
|
|
await notifyIssueRecovery(tx, { companyId });
|
|
}
|
|
await insertRowsInChunks(tx, documents, documentRows);
|
|
await insertRowsInChunks(tx, documentRevisions, revisionRows);
|
|
await insertRowsInChunks(tx, issueDocuments, linkRows);
|
|
});
|
|
},
|
|
|
|
restoreIssueDocumentRevision: async (input: {
|
|
issueId: string;
|
|
key: string;
|
|
revisionId: string;
|
|
createdByAgentId?: string | null;
|
|
createdByUserId?: string | null;
|
|
createdByRunId?: string | null;
|
|
}) => {
|
|
const key = normalizeDocumentKey(input.key);
|
|
return db.transaction(async (tx) => {
|
|
const [existing, issue] = await Promise.all([
|
|
tx
|
|
.select(issueDocumentSelect)
|
|
.from(issueDocuments)
|
|
.innerJoin(documents, eq(issueDocuments.documentId, documents.id))
|
|
.where(and(eq(issueDocuments.issueId, input.issueId), eq(issueDocuments.key, key)))
|
|
.then((rows) => rows[0] ?? null),
|
|
tx
|
|
.select({
|
|
id: issues.id,
|
|
companyId: issues.companyId,
|
|
projectId: issues.projectId,
|
|
executionPolicy: issues.executionPolicy,
|
|
})
|
|
.from(issues)
|
|
.where(eq(issues.id, input.issueId))
|
|
.then((rows) => rows[0] ?? null),
|
|
]);
|
|
|
|
if (!existing || !issue) throw notFound("Document not found");
|
|
if (existing.lockedAt) {
|
|
throw conflict("Document is locked", {
|
|
key: existing.key,
|
|
documentId: existing.id,
|
|
lockedAt: existing.lockedAt,
|
|
});
|
|
}
|
|
|
|
const revision = await tx
|
|
.select({
|
|
id: documentRevisions.id,
|
|
companyId: documentRevisions.companyId,
|
|
documentId: documentRevisions.documentId,
|
|
revisionNumber: documentRevisions.revisionNumber,
|
|
title: documentRevisions.title,
|
|
format: documentRevisions.format,
|
|
body: documentRevisions.body,
|
|
createdByAgentId: documentRevisions.createdByAgentId,
|
|
createdByRunId: documentRevisions.createdByRunId,
|
|
})
|
|
.from(documentRevisions)
|
|
.where(and(eq(documentRevisions.id, input.revisionId), eq(documentRevisions.documentId, existing.id)))
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
if (!revision) throw notFound("Document revision not found");
|
|
await assertAgentInteraction(tx, {
|
|
companyId: existing.companyId, actorAgentId: input.createdByAgentId,
|
|
operation: "edit", issueId: input.issueId, texts: [revision.body, revision.title ?? ""], lock: true,
|
|
});
|
|
if (existing.latestRevisionId === revision.id) {
|
|
throw conflict("Selected revision is already the latest revision", {
|
|
currentRevisionId: existing.latestRevisionId,
|
|
});
|
|
}
|
|
|
|
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();
|
|
const nextRevisionNumber = existing.latestRevisionNumber + 1;
|
|
const [restoredRevision] = await tx
|
|
.insert(documentRevisions)
|
|
.values({
|
|
companyId: existing.companyId,
|
|
documentId: existing.id,
|
|
revisionNumber: nextRevisionNumber,
|
|
title: revision.title ?? null,
|
|
format: revision.format,
|
|
body: revision.body,
|
|
changeSummary: `Restored from revision ${revision.revisionNumber}`,
|
|
createdByAgentId: restoreTrust.revisionCreatedByAgentId,
|
|
createdByUserId: restoreTrust.revisionCreatedByUserId,
|
|
createdByRunId: restoreTrust.revisionCreatedByRunId,
|
|
createdAt: now,
|
|
})
|
|
.returning();
|
|
|
|
await notifyStatusCardIssueChange(tx, existing.companyId);
|
|
await tx
|
|
.update(documents)
|
|
.set({
|
|
title: revision.title ?? null,
|
|
format: revision.format,
|
|
latestBody: revision.body,
|
|
latestRevisionId: restoredRevision.id,
|
|
latestRevisionNumber: nextRevisionNumber,
|
|
updatedByAgentId: input.createdByAgentId ?? null,
|
|
updatedByUserId: input.createdByUserId ?? null,
|
|
sourceTrust: restoreTrust.sourceTrust,
|
|
updatedAt: now,
|
|
})
|
|
.where(eq(documents.id, existing.id));
|
|
|
|
await tx
|
|
.update(issueDocuments)
|
|
.set({ updatedAt: now })
|
|
.where(eq(issueDocuments.documentId, existing.id));
|
|
|
|
const { latestBody: _previousBody, ...existingMetadata } = existing;
|
|
return {
|
|
restoredFromRevisionId: revision.id,
|
|
restoredFromRevisionNumber: revision.revisionNumber,
|
|
document: {
|
|
...existingMetadata,
|
|
title: revision.title ?? null,
|
|
format: revision.format,
|
|
body: revision.body,
|
|
latestRevisionId: restoredRevision.id,
|
|
latestRevisionNumber: nextRevisionNumber,
|
|
updatedByAgentId: input.createdByAgentId ?? null,
|
|
updatedByUserId: input.createdByUserId ?? null,
|
|
sourceTrust: restoreTrust.sourceTrust,
|
|
updatedAt: now,
|
|
},
|
|
};
|
|
});
|
|
},
|
|
|
|
lockIssueDocument: async (input: {
|
|
issueId: string;
|
|
key: string;
|
|
lockedByAgentId?: string | null;
|
|
lockedByUserId?: string | null;
|
|
}) => {
|
|
const key = normalizeDocumentKey(input.key);
|
|
return db.transaction(async (tx) => {
|
|
const existing = await tx
|
|
.select(issueDocumentSelect)
|
|
.from(issueDocuments)
|
|
.innerJoin(documents, eq(issueDocuments.documentId, documents.id))
|
|
.where(and(eq(issueDocuments.issueId, input.issueId), eq(issueDocuments.key, key)))
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
if (!existing) throw notFound("Document not found");
|
|
await assertAgentInteraction(tx, {
|
|
companyId: existing.companyId, actorAgentId: input.lockedByAgentId,
|
|
operation: "edit", issueId: input.issueId, lock: true,
|
|
});
|
|
if (existing.lockedAt) {
|
|
return {
|
|
changed: false as const,
|
|
document: mapIssueDocumentRow(existing, true),
|
|
};
|
|
}
|
|
|
|
await notifyIssueGraphRecovery(tx, { companyId: existing.companyId, issueId: existing.issueId });
|
|
const now = new Date();
|
|
await tx
|
|
.update(documents)
|
|
.set({
|
|
lockedAt: now,
|
|
lockedByAgentId: input.lockedByAgentId ?? null,
|
|
lockedByUserId: input.lockedByUserId ?? null,
|
|
updatedAt: now,
|
|
})
|
|
.where(eq(documents.id, existing.id));
|
|
|
|
await tx
|
|
.update(issueDocuments)
|
|
.set({ updatedAt: now })
|
|
.where(eq(issueDocuments.documentId, existing.id));
|
|
|
|
return {
|
|
changed: true as const,
|
|
document: {
|
|
...mapIssueDocumentRow(existing, true),
|
|
lockedAt: now,
|
|
lockedByAgentId: input.lockedByAgentId ?? null,
|
|
lockedByUserId: input.lockedByUserId ?? null,
|
|
updatedAt: now,
|
|
},
|
|
};
|
|
});
|
|
},
|
|
|
|
unlockIssueDocument: async (issueId: string, rawKey: string, actorAgentId?: string | null) => {
|
|
const key = normalizeDocumentKey(rawKey);
|
|
return db.transaction(async (tx) => {
|
|
const existing = await tx
|
|
.select(issueDocumentSelect)
|
|
.from(issueDocuments)
|
|
.innerJoin(documents, eq(issueDocuments.documentId, documents.id))
|
|
.where(and(eq(issueDocuments.issueId, issueId), eq(issueDocuments.key, key)))
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
if (!existing) throw notFound("Document not found");
|
|
await assertAgentInteraction(tx, {
|
|
companyId: existing.companyId, actorAgentId, operation: "edit", issueId, lock: true,
|
|
});
|
|
if (!existing.lockedAt) {
|
|
return {
|
|
changed: false as const,
|
|
document: mapIssueDocumentRow(existing, true),
|
|
};
|
|
}
|
|
|
|
await notifyIssueGraphRecovery(tx, { companyId: existing.companyId, issueId: existing.issueId });
|
|
const now = new Date();
|
|
await tx
|
|
.update(documents)
|
|
.set({
|
|
lockedAt: null,
|
|
lockedByAgentId: null,
|
|
lockedByUserId: null,
|
|
updatedAt: now,
|
|
})
|
|
.where(eq(documents.id, existing.id));
|
|
|
|
await tx
|
|
.update(issueDocuments)
|
|
.set({ updatedAt: now })
|
|
.where(eq(issueDocuments.documentId, existing.id));
|
|
|
|
return {
|
|
changed: true as const,
|
|
document: {
|
|
...mapIssueDocumentRow(existing, true),
|
|
lockedAt: null,
|
|
lockedByAgentId: null,
|
|
lockedByUserId: null,
|
|
updatedAt: now,
|
|
},
|
|
};
|
|
});
|
|
},
|
|
|
|
deleteIssueDocument: async (issueId: string, rawKey: string, actorAgentId?: string | null) => {
|
|
const key = normalizeDocumentKey(rawKey);
|
|
return db.transaction(async (tx) => {
|
|
const existing = await tx
|
|
.select(issueDocumentSelect)
|
|
.from(issueDocuments)
|
|
.innerJoin(documents, eq(issueDocuments.documentId, documents.id))
|
|
.where(and(eq(issueDocuments.issueId, issueId), eq(issueDocuments.key, key)))
|
|
.then((rows) => rows[0] ?? null);
|
|
|
|
if (!existing) return null;
|
|
await assertAgentInteraction(tx, {
|
|
companyId: existing.companyId, actorAgentId, operation: "edit", issueId, lock: true,
|
|
});
|
|
if (existing.lockedAt) {
|
|
throw conflict("Document is locked", {
|
|
key: existing.key,
|
|
documentId: existing.id,
|
|
lockedAt: existing.lockedAt,
|
|
});
|
|
}
|
|
|
|
await notifyIssueGraphRecovery(tx, { companyId: existing.companyId, issueId: existing.issueId });
|
|
await tx.delete(issueDocuments).where(eq(issueDocuments.documentId, existing.id));
|
|
await notifyStatusCardIssueChange(tx, existing.companyId);
|
|
await tx.delete(documents).where(eq(documents.id, existing.id));
|
|
|
|
return {
|
|
...existing,
|
|
body: existing.latestBody,
|
|
latestRevisionId: existing.latestRevisionId ?? null,
|
|
};
|
|
});
|
|
},
|
|
};
|
|
}
|