mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
Merge master and renumber GitHub App setup migration
This commit is contained in:
commit
cf48352c85
79 files changed
+5008
-227
No files matched your search
@@ -285,6 +285,34 @@ describe("claude remote execution", () => {
|
||||
expect(call?.[2]).not.toContain("--resume");
|
||||
});
|
||||
|
||||
it("explains a remote-to-local session reset even when the cwd matches", async () => {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-claude-local-reset-"));
|
||||
cleanupDirs.push(rootDir);
|
||||
vi.stubEnv("PAPERCLIP_HOME", rootDir);
|
||||
const onLog = vi.fn(async () => {});
|
||||
|
||||
await execute({
|
||||
runId: "run-local-reset",
|
||||
agent: { id: "agent-1", companyId: "company-1", name: "Claude Coder", adapterType: "claude_local", adapterConfig: {} },
|
||||
runtime: {
|
||||
sessionId: "12345678-1234-4abc-9def-123456789012",
|
||||
sessionParams: {
|
||||
cwd: rootDir,
|
||||
remoteExecution: { transport: "ssh", host: "remote.test", port: 22, username: "fixture", remoteCwd: rootDir },
|
||||
},
|
||||
sessionDisplayId: null,
|
||||
taskKey: null,
|
||||
},
|
||||
config: { engine: "cli", command: "claude", cwd: rootDir, paperclipRuntimeSkills: [] },
|
||||
context: {},
|
||||
onLog,
|
||||
});
|
||||
|
||||
expect(runChildProcess.mock.calls[0]?.[2]).not.toContain("--resume");
|
||||
expect(onLog).toHaveBeenCalledWith("stdout", expect.stringContaining("does not match the current execution target"));
|
||||
expect(onLog).not.toHaveBeenCalledWith("stdout", expect.stringContaining("was saved for cwd"));
|
||||
});
|
||||
|
||||
it("resumes saved Claude sessions for remote SSH execution when the remote identity matches", async () => {
|
||||
const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-claude-remote-resume-match-"));
|
||||
cleanupDirs.push(rootDir);
|
||||
|
||||
@@ -499,19 +499,21 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
||||
const billingType = resolveClaudeBillingType(effectiveEnv);
|
||||
const claudeSkillEntries = await readPaperclipRuntimeSkillEntries(config, __moduleDir);
|
||||
const desiredSkillNames = new Set(resolveClaudeDesiredSkillNames(config, claudeSkillEntries));
|
||||
// When instructionsFilePath is configured, build a stable content-addressed
|
||||
// file that includes both the file content and the path directive, so we only
|
||||
// need --append-system-prompt-file (Claude CLI forbids using both flags together).
|
||||
// Keep per-run working-copy paths out of the content-addressed system prompt.
|
||||
// Resumed sessions retain that prompt, so refresh the location on every turn.
|
||||
let combinedInstructionsContents: string | null = null;
|
||||
let instructionsPathDirective = "";
|
||||
if (instructionsFilePath) {
|
||||
try {
|
||||
const instructionsContent = await fs.readFile(instructionsFilePath, "utf-8");
|
||||
const pathDirective =
|
||||
`\nThe above agent instructions were loaded from ${instructionsFilePath}. ` +
|
||||
instructionsPathDirective =
|
||||
`Agent instructions for this run were loaded from ${instructionsFilePath}. ` +
|
||||
`Resolve any relative file references from ${instructionsFileDir}. ` +
|
||||
`This base directory is authoritative for sibling instruction files such as ` +
|
||||
`./HEARTBEAT.md, ./SOUL.md, and ./TOOLS.md; do not resolve those from the parent agent directory.`;
|
||||
combinedInstructionsContents = instructionsContent + pathDirective;
|
||||
`./HEARTBEAT.md, ./SOUL.md, and ./TOOLS.md; do not resolve those from the parent agent directory. ` +
|
||||
`This location replaces any instruction file location from earlier turns.`;
|
||||
combinedInstructionsContents = instructionsContent +
|
||||
"\nUse the agent instruction file location supplied in the current run prompt to resolve relative file references.";
|
||||
} catch (err) {
|
||||
const reason = err instanceof Error ? err.message : String(err);
|
||||
await onLog(
|
||||
@@ -778,18 +780,20 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
||||
? runtimeMcpServers.length === 0
|
||||
: runtimeMcpServerIdentity === runtimeMcpIdentity;
|
||||
const isValidUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(runtimeSessionId);
|
||||
const hasMatchingSessionCwd = claudeSessionCwdMatchesExecutionTarget({
|
||||
runtimeSessionCwd,
|
||||
effectiveExecutionCwd,
|
||||
executionTargetIsRemote,
|
||||
});
|
||||
const hasMatchingExecutionTarget = adapterExecutionTargetSessionMatches(runtimeRemoteExecution, runtimeExecutionTarget);
|
||||
const canResumeSession =
|
||||
runtimeSessionId.length > 0 &&
|
||||
isValidUuid &&
|
||||
hasMatchingPromptBundle &&
|
||||
// Each CLI invocation loads --mcp-config, including --resume invocations.
|
||||
// Refreshing tools does not invalidate the saved conversation.
|
||||
claudeSessionCwdMatchesExecutionTarget({
|
||||
runtimeSessionCwd,
|
||||
effectiveExecutionCwd,
|
||||
executionTargetIsRemote,
|
||||
}) &&
|
||||
adapterExecutionTargetSessionMatches(runtimeRemoteExecution, runtimeExecutionTarget);
|
||||
hasMatchingSessionCwd &&
|
||||
hasMatchingExecutionTarget;
|
||||
const sessionId = canResumeSession ? runtimeSessionId : null;
|
||||
if (runtimeSessionId && !isValidUuid) {
|
||||
await onLog(
|
||||
@@ -798,26 +802,20 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
||||
);
|
||||
}
|
||||
if (
|
||||
executionTargetIsRemote &&
|
||||
runtimeSessionId &&
|
||||
isValidUuid &&
|
||||
!canResumeSession
|
||||
!hasMatchingExecutionTarget
|
||||
) {
|
||||
await onLog(
|
||||
"stdout",
|
||||
`[paperclip] Claude session "${runtimeSessionId}" does not match the current remote execution identity and will not be resumed in "${effectiveExecutionCwd}". Starting a fresh remote session.\n`,
|
||||
`[paperclip] Claude session "${runtimeSessionId}" does not match the current execution target and will not be resumed in "${effectiveExecutionCwd}". Starting a fresh session.\n`,
|
||||
);
|
||||
} else if (
|
||||
runtimeSessionId &&
|
||||
isValidUuid &&
|
||||
runtimeSessionCwd.length > 0 &&
|
||||
path.resolve(runtimeSessionCwd) !== path.resolve(effectiveExecutionCwd)
|
||||
!hasMatchingSessionCwd
|
||||
) {
|
||||
await onLog(
|
||||
"stdout",
|
||||
`[paperclip] Claude session "${runtimeSessionId}" does not match the current remote execution identity and will not be resumed in "${effectiveExecutionCwd}". Starting a fresh remote session.\n`,
|
||||
);
|
||||
} else if (runtimeSessionId && isValidUuid && !canResumeSession) {
|
||||
await onLog(
|
||||
"stdout",
|
||||
`[paperclip] Claude session "${runtimeSessionId}" was saved for cwd "${runtimeSessionCwd}" and will not be resumed in "${effectiveExecutionCwd}".\n`,
|
||||
@@ -916,6 +914,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
||||
: renderTemplate(promptTemplate, templateData);
|
||||
const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();
|
||||
const prompt = joinPromptSections([
|
||||
instructionsPathDirective,
|
||||
renderedBootstrapPrompt,
|
||||
selectInitialCommunicationGuidance(context, { resumedSession: Boolean(resumeSessionId) }),
|
||||
wakePrompt,
|
||||
@@ -944,7 +943,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
|
||||
}
|
||||
if (attemptInstructionsFilePath && !resumeSessionId) {
|
||||
commandNotes.push(
|
||||
`Injected agent instructions via --append-system-prompt-file ${instructionsFilePath} (with path directive appended)`,
|
||||
`Injected agent instructions via --append-system-prompt-file ${instructionsFilePath} (with current file location in the run prompt)`,
|
||||
);
|
||||
}
|
||||
if (runtimeMcpServers.length > 0) {
|
||||
|
||||
+72
-47
@@ -1,6 +1,5 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { drizzle as drizzlePg } from "drizzle-orm/postgres-js";
|
||||
import { migrate as migratePg } from "drizzle-orm/postgres-js/migrator";
|
||||
import { readFile, readdir } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import postgres from "postgres";
|
||||
@@ -463,6 +462,14 @@ async function recordMigrationHistoryEntry(
|
||||
);
|
||||
}
|
||||
|
||||
// These idempotent privacy migrations commit keyset batches inside their DO
|
||||
// blocks. Execute each statement at top level so DDL locks and completed batches
|
||||
// are released before the next batch. History is recorded only after completion.
|
||||
const MIGRATIONS_WITH_BATCH_COMMITS = new Set([
|
||||
"0313_private_task_access.sql",
|
||||
"0314_private_task_draft_assets.sql",
|
||||
]);
|
||||
|
||||
async function applyPendingMigrationsManually(
|
||||
url: string,
|
||||
pendingMigrations: string[],
|
||||
@@ -475,40 +482,75 @@ async function applyPendingMigrationsManually(
|
||||
journalEntries.map((entry) => [entry.fileName, normalizeFolderMillis(entry.folderMillis)]),
|
||||
);
|
||||
|
||||
const sql = createUtilitySql(url);
|
||||
const pool = createUtilitySql(url);
|
||||
try {
|
||||
const { migrationTableSchema, columnNames } = await ensureMigrationJournalTable(sql);
|
||||
const qualifiedTable = `${quoteIdentifier(migrationTableSchema)}.${quoteIdentifier(DRIZZLE_MIGRATIONS_TABLE)}`;
|
||||
const sql = await pool.reserve();
|
||||
try {
|
||||
// A session lock survives each batch COMMIT. Reserve the connection so
|
||||
// pool rotation cannot release it while another migrator is waiting.
|
||||
await sql`SELECT pg_advisory_lock(hashtextextended('paperclip:migrations', 0))`;
|
||||
const { migrationTableSchema, columnNames } = await ensureMigrationJournalTable(sql);
|
||||
const qualifiedTable = `${quoteIdentifier(migrationTableSchema)}.${quoteIdentifier(DRIZZLE_MIGRATIONS_TABLE)}`;
|
||||
|
||||
for (const migrationFile of orderedPendingMigrations) {
|
||||
const migrationContent = await readMigrationFileContent(migrationFile);
|
||||
const hash = createHash("sha256").update(migrationContent).digest("hex");
|
||||
const existingEntry = await migrationHistoryEntryExists(
|
||||
sql,
|
||||
qualifiedTable,
|
||||
columnNames,
|
||||
migrationFile,
|
||||
hash,
|
||||
);
|
||||
if (existingEntry) continue;
|
||||
|
||||
await runInTransaction(sql, async () => {
|
||||
for (const statement of splitMigrationStatements(migrationContent)) {
|
||||
await sql.unsafe(statement);
|
||||
}
|
||||
|
||||
await recordMigrationHistoryEntry(
|
||||
for (const migrationFile of orderedPendingMigrations) {
|
||||
const migrationContent = await readMigrationFileContent(migrationFile);
|
||||
const hash = createHash("sha256").update(migrationContent).digest("hex");
|
||||
const existingEntry = await migrationHistoryEntryExists(
|
||||
sql,
|
||||
qualifiedTable,
|
||||
columnNames,
|
||||
migrationFile,
|
||||
hash,
|
||||
folderMillisByFileName.get(migrationFile) ?? Date.now(),
|
||||
);
|
||||
});
|
||||
if (existingEntry) continue;
|
||||
|
||||
const applyMigration = async () => {
|
||||
for (const statement of splitMigrationStatements(migrationContent)) {
|
||||
if (MIGRATIONS_WITH_BATCH_COMMITS.has(migrationFile)) {
|
||||
// A cancelled concurrent build leaves an invalid index. IF NOT
|
||||
// EXISTS alone would skip it on retry and journal an incomplete index.
|
||||
const index = statement.replace(/^\s*--.*$/gm, "").trim()
|
||||
.match(/^CREATE (?:UNIQUE )?INDEX CONCURRENTLY IF NOT EXISTS "([A-Za-z_][A-Za-z0-9_]*)"/i);
|
||||
if (index) {
|
||||
const invalid = await sql<{ invalid: boolean }[]>`
|
||||
SELECT NOT i.indisvalid AS invalid FROM pg_index i
|
||||
JOIN pg_class c ON c.oid = i.indexrelid
|
||||
JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||
WHERE n.nspname = 'public' AND c.relname = ${index[1]}`;
|
||||
if (invalid[0]?.invalid) {
|
||||
await sql.unsafe(`DROP INDEX CONCURRENTLY ${quoteIdentifier("public")}.${quoteIdentifier(index[1])}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
await sql.unsafe(statement);
|
||||
}
|
||||
|
||||
await recordMigrationHistoryEntry(
|
||||
sql,
|
||||
qualifiedTable,
|
||||
columnNames,
|
||||
migrationFile,
|
||||
hash,
|
||||
folderMillisByFileName.get(migrationFile) ?? Date.now(),
|
||||
);
|
||||
};
|
||||
if (MIGRATIONS_WITH_BATCH_COMMITS.has(migrationFile)) {
|
||||
await applyMigration();
|
||||
} else {
|
||||
await runInTransaction(sql, applyMigration);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
await sql`SELECT pg_advisory_unlock(hashtextextended('paperclip:migrations', 0))`;
|
||||
} catch {
|
||||
// Preserve the migration error if the session died; PostgreSQL releases
|
||||
// its lock on disconnect, and pool.end() closes any remaining connection.
|
||||
}
|
||||
sql.release();
|
||||
}
|
||||
} finally {
|
||||
await sql.end();
|
||||
await pool.end();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1033,26 +1075,10 @@ export async function applyPendingMigrations(url: string): Promise<void> {
|
||||
if (initialState.status === "upToDate") return;
|
||||
|
||||
if (initialState.reason === "no-migration-journal-empty-db") {
|
||||
const sql = createUtilitySql(url);
|
||||
try {
|
||||
const db = drizzlePg(sql);
|
||||
await migratePg(db, { migrationsFolder: MIGRATIONS_FOLDER });
|
||||
} finally {
|
||||
await sql.end();
|
||||
}
|
||||
|
||||
let bootstrappedState = await inspectMigrations(url);
|
||||
if (bootstrappedState.status === "upToDate") return;
|
||||
if (bootstrappedState.reason === "pending-migrations") {
|
||||
const repair = await reconcilePendingMigrationHistory(url);
|
||||
if (repair.repairedMigrations.length > 0) {
|
||||
bootstrappedState = await inspectMigrations(url);
|
||||
}
|
||||
if (bootstrappedState.status === "needsMigrations" && bootstrappedState.reason === "pending-migrations") {
|
||||
await applyPendingMigrationsManually(url, bootstrappedState.pendingMigrations);
|
||||
bootstrappedState = await inspectMigrations(url);
|
||||
}
|
||||
}
|
||||
// Use the same per-file executor for bootstrap and upgrades: Drizzle wraps
|
||||
// the whole journal in one transaction and cannot run committing backfills.
|
||||
await applyPendingMigrationsManually(url, initialState.pendingMigrations);
|
||||
const bootstrappedState = await inspectMigrations(url);
|
||||
if (bootstrappedState.status === "upToDate") return;
|
||||
throw new Error(
|
||||
`Failed to bootstrap migrations: ${bootstrappedState.pendingMigrations.join(", ")}`,
|
||||
@@ -1116,8 +1142,7 @@ export async function migratePostgresIfEmpty(url: string): Promise<MigrationBoot
|
||||
return { migrated: false, reason: "not-empty-no-migration-journal", tableCount };
|
||||
}
|
||||
|
||||
const db = drizzlePg(sql);
|
||||
await migratePg(db, { migrationsFolder: MIGRATIONS_FOLDER });
|
||||
await applyPendingMigrationsManually(url, await listMigrationFiles());
|
||||
|
||||
return { migrated: true, reason: "migrated-empty-db", tableCount: 0 };
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import postgres from "postgres";
|
||||
import { applyPendingMigrations } from "./client.js";
|
||||
import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "./test-embedded-postgres.js";
|
||||
|
||||
const MIGRATION_FILE = "0313_private_task_access.sql";
|
||||
const cleanups: Array<() => Promise<void>> = [];
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
if (!embeddedPostgresSupport.supported) console.warn(`Private-task migration checks unavailable: ${embeddedPostgresSupport.reason}`);
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
|
||||
async function migrationHash() {
|
||||
const content = await fs.promises.readFile(new URL(`./migrations/${MIGRATION_FILE}`, import.meta.url), "utf8");
|
||||
return createHash("sha256").update(content).digest("hex");
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
while (cleanups.length > 0) await cleanups.pop()?.();
|
||||
});
|
||||
|
||||
describeEmbeddedPostgres("heartbeat run issue privacy migration", () => {
|
||||
it("backfills every valid context issue binding and preserves maintenance runs", async () => {
|
||||
const database = await startEmbeddedPostgresTestDatabase("paperclip-run-issue-privacy-");
|
||||
cleanups.push(database.cleanup);
|
||||
const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} });
|
||||
cleanups.push(async () => sql.end());
|
||||
|
||||
await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${await migrationHash()}`;
|
||||
|
||||
await sql`DROP TRIGGER IF EXISTS heartbeat_runs_set_scope_kind ON heartbeat_runs`;
|
||||
const companyId = randomUUID();
|
||||
const agentId = randomUUID();
|
||||
const firstIssueId = randomUUID();
|
||||
const secondIssueId = randomUUID();
|
||||
const firstRunId = randomUUID();
|
||||
const secondRunId = randomUUID();
|
||||
const maintenanceRunId = randomUUID();
|
||||
|
||||
await sql`
|
||||
INSERT INTO "companies" ("id", "name", "issue_prefix")
|
||||
VALUES (${companyId}, 'Run Privacy', 'RPR')
|
||||
`;
|
||||
await sql`
|
||||
INSERT INTO "agents" ("id", "company_id", "name", "role", "adapter_type", "adapter_config")
|
||||
VALUES (${agentId}, ${companyId}, 'Runner', 'engineer', 'process', '{}'::jsonb)
|
||||
`;
|
||||
await sql`
|
||||
INSERT INTO "issues" ("id", "company_id", "title", "identifier")
|
||||
VALUES
|
||||
(${firstIssueId}, ${companyId}, 'First private task', 'RPR-1'),
|
||||
(${secondIssueId}, ${companyId}, 'Second private task', 'RPR-2')
|
||||
`;
|
||||
await sql`
|
||||
INSERT INTO "heartbeat_runs" (
|
||||
"id", "company_id", "agent_id", "status", "issue_id", "context_snapshot"
|
||||
)
|
||||
VALUES
|
||||
(${firstRunId}, ${companyId}, ${agentId}, 'succeeded', NULL, ${sql.json({ issueId: firstIssueId })}),
|
||||
(${secondRunId}, ${companyId}, ${agentId}, 'failed', NULL, ${sql.json({ taskId: secondIssueId })}),
|
||||
(${maintenanceRunId}, ${companyId}, ${agentId}, 'succeeded', NULL, ${sql.json({ wakeReason: "heartbeat_timer" })})
|
||||
`;
|
||||
|
||||
const legacyProjectId = randomUUID();
|
||||
await sql`INSERT INTO projects (id, company_id, name, visibility) VALUES (${legacyProjectId}, ${companyId}, 'Legacy private project', 'private')`;
|
||||
await sql`INSERT INTO activity_log (company_id, actor_type, actor_id, action, entity_type, entity_id)
|
||||
VALUES (${companyId}, 'user', 'original-owner', 'project.created', 'project', ${legacyProjectId})`;
|
||||
await sql`INSERT INTO project_access_members (company_id, project_id, subject_type, subject_id)
|
||||
VALUES (${companyId}, ${legacyProjectId}, 'user', 'ordinary-reader')`;
|
||||
|
||||
const agentProjectId = randomUUID(), runProjectId = randomUUID(), preferredProjectId = randomUUID();
|
||||
await sql`UPDATE heartbeat_runs SET responsible_user_id = 'run-owner' WHERE id = ${secondRunId}`;
|
||||
await sql`INSERT INTO projects (id, company_id, name, visibility) VALUES
|
||||
(${agentProjectId}, ${companyId}, 'Agent API project', 'private'),
|
||||
(${runProjectId}, ${companyId}, 'Run-backed project', 'private'),
|
||||
(${preferredProjectId}, ${companyId}, 'Recorded owner project', 'private')`;
|
||||
await sql`INSERT INTO activity_log (company_id, actor_type, actor_id, responsible_user_id, run_id, action, entity_type, entity_id) VALUES
|
||||
(${companyId}, 'agent', ${agentId}, 'activity-owner', NULL, 'project.created', 'project', ${agentProjectId}),
|
||||
(${companyId}, 'agent', ${agentId}, NULL, ${secondRunId}, 'project.created', 'project', ${runProjectId}),
|
||||
(${companyId}, 'agent', ${agentId}, 'activity-owner', ${secondRunId}, 'project.created', 'project', ${preferredProjectId})`;
|
||||
|
||||
await applyPendingMigrations(database.connectionString);
|
||||
for (const [projectId, owner] of [[agentProjectId, 'activity-owner'], [runProjectId, 'run-owner'], [preferredProjectId, 'activity-owner']]) {
|
||||
expect(await sql`SELECT privacy_owner_user_id FROM projects WHERE id = ${projectId}`).toEqual([{ privacy_owner_user_id: owner }]);
|
||||
expect(await sql`SELECT subject_id FROM project_access_members WHERE project_id = ${projectId}`).toEqual([{ subject_id: owner }]);
|
||||
}
|
||||
const [legacyProject] = await sql`SELECT privacy_owner_user_id FROM projects WHERE id = ${legacyProjectId}`;
|
||||
expect(legacyProject.privacy_owner_user_id).toBe('original-owner');
|
||||
expect(await sql`SELECT subject_id FROM project_access_members WHERE project_id = ${legacyProjectId} ORDER BY subject_id`)
|
||||
.toEqual([{ subject_id: 'ordinary-reader' }, { subject_id: 'original-owner' }]);
|
||||
|
||||
|
||||
const rows = await sql<{ id: string; issue_id: string | null; scope_kind: string }[]>`
|
||||
SELECT "id", "issue_id", "scope_kind"
|
||||
FROM "heartbeat_runs"
|
||||
WHERE "id" IN (${firstRunId}, ${secondRunId}, ${maintenanceRunId})
|
||||
ORDER BY "id"
|
||||
`;
|
||||
const issueByRun = new Map(rows.map((row) => [row.id, row.issue_id]));
|
||||
expect(issueByRun.get(firstRunId)).toBe(firstIssueId);
|
||||
expect(issueByRun.get(secondRunId)).toBe(secondIssueId);
|
||||
expect(issueByRun.get(maintenanceRunId)).toBeNull();
|
||||
expect(rows.find((row) => row.id === firstRunId)?.scope_kind).toBe("issue");
|
||||
expect(rows.find((row) => row.id === secondRunId)?.scope_kind).toBe("issue");
|
||||
expect(rows.find((row) => row.id === maintenanceRunId)?.scope_kind).toBe("company");
|
||||
|
||||
const [parity] = await sql<{ expected_count: number; populated_count: number }[]>`
|
||||
SELECT
|
||||
count(*) FILTER (WHERE "context_snapshot" ? 'issueId' OR "context_snapshot" ? 'taskId')::int AS "expected_count",
|
||||
count(*) FILTER (WHERE ("context_snapshot" ? 'issueId' OR "context_snapshot" ? 'taskId') AND "issue_id" IS NOT NULL)::int AS "populated_count"
|
||||
FROM "heartbeat_runs"
|
||||
WHERE "id" IN (${firstRunId}, ${secondRunId}, ${maintenanceRunId})
|
||||
`;
|
||||
expect(parity).toEqual({ expected_count: 2, populated_count: 2 });
|
||||
|
||||
const [newRun] = await sql<{ id: string; issue_id: string | null; scope_kind: string }[]>`
|
||||
INSERT INTO heartbeat_runs (company_id, agent_id, status, context_snapshot)
|
||||
VALUES (${companyId}, ${agentId}, 'succeeded', ${sql.json({ taskId: secondIssueId })})
|
||||
RETURNING id, issue_id, scope_kind`;
|
||||
expect(newRun).toMatchObject({ issue_id: secondIssueId, scope_kind: "issue" });
|
||||
await sql`UPDATE heartbeat_runs SET context_snapshot = '{}'::jsonb, scope_kind = 'company' WHERE id = ${newRun.id}`;
|
||||
expect(await sql`SELECT issue_id, scope_kind FROM heartbeat_runs WHERE id = ${newRun.id}`)
|
||||
.toEqual([{ issue_id: secondIssueId, scope_kind: "issue" }]);
|
||||
|
||||
const indexes = await sql<{ indexname: string }[]>`
|
||||
SELECT "indexname"
|
||||
FROM "pg_indexes"
|
||||
WHERE "schemaname" = 'public'
|
||||
AND "indexname" = 'heartbeat_runs_company_issue_created_idx'
|
||||
`;
|
||||
expect(indexes).toHaveLength(1);
|
||||
}, 30_000);
|
||||
|
||||
it("fails closed when a legacy issue claim cannot be resolved", async () => {
|
||||
const database = await startEmbeddedPostgresTestDatabase("paperclip-run-issue-privacy-invalid-");
|
||||
cleanups.push(database.cleanup);
|
||||
const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} });
|
||||
cleanups.push(async () => sql.end());
|
||||
|
||||
await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${await migrationHash()}`;
|
||||
|
||||
await sql`DROP TRIGGER IF EXISTS heartbeat_runs_set_scope_kind ON heartbeat_runs`;
|
||||
const companyId = randomUUID();
|
||||
const otherCompanyId = randomUUID();
|
||||
const agentId = randomUUID();
|
||||
const foreignIssueId = randomUUID();
|
||||
await sql`
|
||||
INSERT INTO "companies" ("id", "name", "issue_prefix")
|
||||
VALUES
|
||||
(${companyId}, 'Run Privacy', 'RPI'),
|
||||
(${otherCompanyId}, 'Other Company', 'RPO')
|
||||
`;
|
||||
await sql`
|
||||
INSERT INTO "agents" ("id", "company_id", "name", "role", "adapter_type", "adapter_config")
|
||||
VALUES (${agentId}, ${companyId}, 'Runner', 'engineer', 'process', '{}'::jsonb)
|
||||
`;
|
||||
await sql`
|
||||
INSERT INTO "issues" ("id", "company_id", "title", "identifier")
|
||||
VALUES (${foreignIssueId}, ${otherCompanyId}, 'Foreign task', 'RPO-1')
|
||||
`;
|
||||
await sql`
|
||||
INSERT INTO "heartbeat_runs" ("company_id", "agent_id", "status", "context_snapshot")
|
||||
VALUES
|
||||
(${companyId}, ${agentId}, 'succeeded', ${sql.json({ issueId: "not-a-uuid" })}),
|
||||
(${companyId}, ${agentId}, 'succeeded', ${sql.json({ issueId: randomUUID() })}),
|
||||
(${companyId}, ${agentId}, 'succeeded', ${sql.json({ issueId: foreignIssueId })}),
|
||||
(${companyId}, ${agentId}, 'succeeded', ${sql.json({ taskId: "not-a-uuid" })}),
|
||||
(${companyId}, ${agentId}, 'succeeded', ${sql.json({ taskId: randomUUID() })}),
|
||||
(${companyId}, ${agentId}, 'succeeded', ${sql.json({ taskId: foreignIssueId })}),
|
||||
(${companyId}, ${agentId}, 'succeeded', ${sql.json({ taskId: null })})
|
||||
`;
|
||||
|
||||
await applyPendingMigrations(database.connectionString);
|
||||
const rows = await sql<{ issue_id: string | null; scope_kind: string }[]>`
|
||||
SELECT issue_id, scope_kind FROM heartbeat_runs WHERE company_id = ${companyId}`;
|
||||
expect(rows).toHaveLength(7);
|
||||
expect(rows.every(row => row.scope_kind === "issue" && row.issue_id === null)).toBe(true);
|
||||
// Re-running the migration preserves fail-closed tombstones and constraints.
|
||||
await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${await migrationHash()}`;
|
||||
await applyPendingMigrations(database.connectionString);
|
||||
}, 30_000);
|
||||
|
||||
it("releases schema and completed-batch row locks and resumes after interruption", async () => {
|
||||
const database = await startEmbeddedPostgresTestDatabase("paperclip-privacy-batch-commits-");
|
||||
cleanups.push(database.cleanup);
|
||||
const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} });
|
||||
cleanups.push(async () => sql.end());
|
||||
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID();
|
||||
const runId = (n: number) => `00000000-0000-0000-0000-${String(n).padStart(12, "0")}`;
|
||||
await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${companyId}, 'Batch commits', 'BCH')`;
|
||||
await sql`INSERT INTO agents (id, company_id, name, adapter_type) VALUES (${agentId}, ${companyId}, 'Runner', 'process')`;
|
||||
await sql`INSERT INTO issues (id, company_id, title, visibility) VALUES (${issueId}, ${companyId}, 'Private task', 'private')`;
|
||||
await sql`DROP TRIGGER heartbeat_runs_set_scope_kind ON heartbeat_runs`;
|
||||
await sql`INSERT INTO heartbeat_runs (id, company_id, agent_id, status, context_snapshot)
|
||||
SELECT ('00000000-0000-0000-0000-' || lpad(n::text, 12, '0'))::uuid,
|
||||
${companyId}::uuid, ${agentId}::uuid, 'succeeded', ${sql.json({ taskId: issueId })}::jsonb
|
||||
FROM generate_series(1, 1001) n`;
|
||||
// A failed concurrent build must be repaired rather than skipped by
|
||||
// CREATE INDEX IF NOT EXISTS when the migration is retried.
|
||||
await sql`DROP INDEX heartbeat_runs_company_issue_created_idx`;
|
||||
await expect(sql.unsafe("CREATE UNIQUE INDEX CONCURRENTLY heartbeat_runs_company_issue_created_idx ON heartbeat_runs (company_id)"))
|
||||
.rejects.toThrow();
|
||||
await sql.unsafe(`CREATE FUNCTION interrupt_privacy_batch_fixture() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
PERFORM pg_advisory_xact_lock(736319937);
|
||||
RAISE EXCEPTION 'fixture interrupted second batch';
|
||||
END $$`);
|
||||
await sql.unsafe(`CREATE TRIGGER zzz_interrupt_privacy_batch_fixture BEFORE UPDATE ON heartbeat_runs
|
||||
FOR EACH ROW WHEN (OLD.scope_kind = 'company' AND NEW.id = '${runId(1001)}'::uuid)
|
||||
EXECUTE FUNCTION interrupt_privacy_batch_fixture()`);
|
||||
const hash = await migrationHash();
|
||||
await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`;
|
||||
await sql`SELECT pg_advisory_lock(736319937)`;
|
||||
const migration = applyPendingMigrations(database.connectionString).then(() => null, error => error);
|
||||
let contender: Promise<unknown> | undefined;
|
||||
try {
|
||||
// The second batch is blocked while another session can see the first
|
||||
// committed batch and write a row whose lock has already been released.
|
||||
await expect.poll(async () => {
|
||||
const [row] = await sql`SELECT count(*)::int AS n FROM heartbeat_runs
|
||||
WHERE company_id = ${companyId} AND scope_kind = 'issue'`;
|
||||
return row.n;
|
||||
}, { timeout: 10_000 }).toBe(1000);
|
||||
// The session lock survives batch commits and blocks another migrator.
|
||||
contender = applyPendingMigrations(database.connectionString).then(() => null, error => error);
|
||||
await expect.poll(async () => {
|
||||
const [row] = await sql`SELECT count(*)::int AS n FROM pg_stat_activity
|
||||
WHERE datname = current_database() AND wait_event = 'advisory'
|
||||
AND strpos(query, 'paperclip:migrations') > 0`;
|
||||
return row.n;
|
||||
}, { timeout: 10_000 }).toBe(1);
|
||||
expect(await sql`SELECT hash FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`).toHaveLength(0);
|
||||
await sql`SET lock_timeout = '500ms'`;
|
||||
await sql`UPDATE heartbeat_runs SET context_snapshot = context_snapshot || '{"probe":"visible"}'::jsonb
|
||||
WHERE id = ${runId(1)}`;
|
||||
expect(await sql`SELECT context_snapshot->>'probe' AS probe FROM heartbeat_runs WHERE id = ${runId(1)}`)
|
||||
.toEqual([{ probe: "visible" }]);
|
||||
} finally {
|
||||
await sql`SELECT pg_advisory_unlock(736319937)`;
|
||||
await sql`RESET lock_timeout`;
|
||||
await migration;
|
||||
await contender;
|
||||
}
|
||||
expect(await migration).toMatchObject({ message: "fixture interrupted second batch" });
|
||||
expect(await contender).toMatchObject({ message: "fixture interrupted second batch" });
|
||||
expect(await sql`SELECT hash FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`).toHaveLength(0);
|
||||
await sql`DROP TRIGGER zzz_interrupt_privacy_batch_fixture ON heartbeat_runs`;
|
||||
await sql`DROP FUNCTION interrupt_privacy_batch_fixture()`;
|
||||
await Promise.all([applyPendingMigrations(database.connectionString), applyPendingMigrations(database.connectionString)]);
|
||||
const [finished] = await sql`SELECT count(*)::int AS n FROM heartbeat_runs
|
||||
WHERE company_id = ${companyId} AND scope_kind = 'issue' AND issue_id = ${issueId}`;
|
||||
expect(finished.n).toBe(1001);
|
||||
expect(await sql`SELECT indisvalid FROM pg_index WHERE indexrelid = 'heartbeat_runs_company_issue_created_idx'::regclass`)
|
||||
.toEqual([{ indisvalid: true }]);
|
||||
expect(await sql`SELECT hash FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`).toHaveLength(1);
|
||||
}, 30_000);
|
||||
|
||||
it("keeps all privacy triggers installed when replacement is interrupted", async () => {
|
||||
const database = await startEmbeddedPostgresTestDatabase("paperclip-privacy-trigger-atomic-");
|
||||
cleanups.push(database.cleanup);
|
||||
const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} });
|
||||
cleanups.push(async () => sql.end());
|
||||
const content = await fs.promises.readFile(new URL(`./migrations/${MIGRATION_FILE}`, import.meta.url), "utf8");
|
||||
const replacements = content.split("--> statement-breakpoint").filter(statement => /DROP TRIGGER IF EXISTS/.test(statement));
|
||||
expect(replacements).toHaveLength(4);
|
||||
for (const statement of replacements) {
|
||||
const name = statement.match(/DROP TRIGGER IF EXISTS ([A-Za-z_]+)/)![1];
|
||||
const interrupted = statement.replace("CREATE TRIGGER", "RAISE EXCEPTION 'fixture interrupted trigger replacement';\n CREATE TRIGGER");
|
||||
await expect(sql.unsafe(interrupted)).rejects.toThrow("fixture interrupted trigger replacement");
|
||||
expect(await sql`SELECT tgname FROM pg_trigger WHERE tgname = ${name} AND NOT tgisinternal`).toEqual([{ tgname: name }]);
|
||||
}
|
||||
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID();
|
||||
await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${companyId}, 'Atomic triggers', 'ATR')`;
|
||||
await sql`INSERT INTO agents (id, company_id, name, adapter_type) VALUES (${agentId}, ${companyId}, 'Runner', 'process')`;
|
||||
await sql`INSERT INTO issues (id, company_id, title, visibility) VALUES (${issueId}, ${companyId}, 'Private', 'private')`;
|
||||
expect(await sql`INSERT INTO heartbeat_runs (company_id, agent_id, status, context_snapshot)
|
||||
VALUES (${companyId}, ${agentId}, 'succeeded', ${sql.json({ taskId: issueId })}) RETURNING issue_id, scope_kind`)
|
||||
.toEqual([{ issue_id: issueId, scope_kind: "issue" }]);
|
||||
}, 30_000);
|
||||
|
||||
});
|
||||
@@ -0,0 +1,278 @@
|
||||
-- Runs through the Paperclip migration executor outside a file-wide transaction.
|
||||
-- Each idempotent keyset batch commits before advancing; history is recorded last.
|
||||
CREATE TABLE IF NOT EXISTS "issue_access_grants" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"issue_id" uuid NOT NULL,
|
||||
"subject_type" text NOT NULL,
|
||||
"subject_id" text NOT NULL,
|
||||
"source" text NOT NULL,
|
||||
"granted_by_user_id" text,
|
||||
"granted_by_agent_id" uuid,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"revoked_at" timestamp with time zone,
|
||||
CONSTRAINT "issue_access_grants_subject_type_check" CHECK ("issue_access_grants"."subject_type" in ('user', 'agent')),
|
||||
CONSTRAINT "issue_access_grants_source_check" CHECK ("issue_access_grants"."source" in ('explicit', 'assignment', 'project'))
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE IF NOT EXISTS "project_access_members" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"company_id" uuid NOT NULL,
|
||||
"project_id" uuid NOT NULL,
|
||||
"subject_type" text NOT NULL,
|
||||
"subject_id" text NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "project_access_members_subject_type_check" CHECK ("project_access_members"."subject_type" in ('user', 'agent'))
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "workspace_operations" DROP CONSTRAINT IF EXISTS "workspace_operations_heartbeat_run_id_heartbeat_runs_id_fk";
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "workspace_operations" DROP CONSTRAINT IF EXISTS "workspace_operations_issue_id_issues_id_fk";
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "heartbeat_runs" ADD COLUMN IF NOT EXISTS "scope_kind" text DEFAULT 'company' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "heartbeat_runs" ADD COLUMN IF NOT EXISTS "issue_id" uuid;--> statement-breakpoint
|
||||
ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "visibility" text DEFAULT 'open' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "privacy_root_issue_id" uuid;--> statement-breakpoint
|
||||
ALTER TABLE "issues" ADD COLUMN IF NOT EXISTS "privacy_parent_issue_id" uuid;--> statement-breakpoint
|
||||
ALTER TABLE "projects" ADD COLUMN IF NOT EXISTS "visibility" text DEFAULT 'open' NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "projects" ADD COLUMN IF NOT EXISTS "personal_owner_user_id" text;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'issue_access_grants_issue_id_issues_id_fk' AND conrelid = 'public.issue_access_grants'::regclass) THEN
|
||||
ALTER TABLE "issue_access_grants" ADD CONSTRAINT "issue_access_grants_issue_id_issues_id_fk" FOREIGN KEY ("issue_id") REFERENCES "public"."issues"("id") ON DELETE cascade ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'issue_access_grants_granted_by_agent_id_agents_id_fk' AND conrelid = 'public.issue_access_grants'::regclass) THEN
|
||||
ALTER TABLE "issue_access_grants" ADD CONSTRAINT "issue_access_grants_granted_by_agent_id_agents_id_fk" FOREIGN KEY ("granted_by_agent_id") REFERENCES "public"."agents"("id") ON DELETE set null ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'project_access_members_company_id_companies_id_fk' AND conrelid = 'public.project_access_members'::regclass) THEN
|
||||
ALTER TABLE "project_access_members" ADD CONSTRAINT "project_access_members_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'project_access_members_project_id_projects_id_fk' AND conrelid = 'public.project_access_members'::regclass) THEN
|
||||
ALTER TABLE "project_access_members" ADD CONSTRAINT "project_access_members_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
CREATE INDEX IF NOT EXISTS "issue_access_grants_subject_active_issue_idx" ON "issue_access_grants" USING btree ("subject_type","subject_id","revoked_at","issue_id");--> statement-breakpoint
|
||||
CREATE INDEX IF NOT EXISTS "issue_access_grants_issue_idx" ON "issue_access_grants" USING btree ("issue_id","created_at");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS "project_access_members_project_subject_uq" ON "project_access_members" USING btree ("project_id","subject_type","subject_id");--> statement-breakpoint
|
||||
CREATE INDEX IF NOT EXISTS "project_access_members_subject_lookup_idx" ON "project_access_members" USING btree ("company_id","subject_type","subject_id","project_id");--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'heartbeat_runs_issue_id_issues_id_fk' AND conrelid = 'public.heartbeat_runs'::regclass) THEN
|
||||
ALTER TABLE "heartbeat_runs" ADD CONSTRAINT "heartbeat_runs_issue_id_issues_id_fk" FOREIGN KEY ("issue_id") REFERENCES "public"."issues"("id") ON DELETE set null ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'issues_privacy_root_issue_id_issues_id_fk' AND conrelid = 'public.issues'::regclass) THEN
|
||||
ALTER TABLE "issues" ADD CONSTRAINT "issues_privacy_root_issue_id_issues_id_fk" FOREIGN KEY ("privacy_root_issue_id") REFERENCES "public"."issues"("id") ON DELETE no action ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'issues_privacy_parent_issue_id_issues_id_fk' AND conrelid = 'public.issues'::regclass) THEN
|
||||
ALTER TABLE "issues" ADD CONSTRAINT "issues_privacy_parent_issue_id_issues_id_fk" FOREIGN KEY ("privacy_parent_issue_id") REFERENCES "public"."issues"("id") ON DELETE set null ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'workspace_operations_heartbeat_run_id_heartbeat_runs_id_fk' AND conrelid = 'public.workspace_operations'::regclass) THEN
|
||||
ALTER TABLE "workspace_operations" ADD CONSTRAINT "workspace_operations_heartbeat_run_id_heartbeat_runs_id_fk" FOREIGN KEY ("heartbeat_run_id") REFERENCES "public"."heartbeat_runs"("id") ON DELETE set null ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'workspace_operations_issue_id_issues_id_fk' AND conrelid = 'public.workspace_operations'::regclass) THEN
|
||||
ALTER TABLE "workspace_operations" ADD CONSTRAINT "workspace_operations_issue_id_issues_id_fk" FOREIGN KEY ("issue_id") REFERENCES "public"."issues"("id") ON DELETE set null ON UPDATE no action;
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS "heartbeat_runs_company_issue_created_idx" ON "heartbeat_runs" USING btree ("company_id","issue_id","created_at");--> statement-breakpoint
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS "issues_company_privacy_parent_idx" ON "issues" USING btree ("company_id","privacy_parent_issue_id");--> statement-breakpoint
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS "issues_company_privacy_root_idx" ON "issues" USING btree ("company_id","privacy_root_issue_id");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "projects_company_personal_owner_uq" ON "projects" USING btree ("company_id","personal_owner_user_id") WHERE "projects"."personal_owner_user_id" is not null;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'heartbeat_runs_scope_binding_check' AND conrelid = 'public.heartbeat_runs'::regclass) THEN
|
||||
ALTER TABLE "heartbeat_runs" ADD CONSTRAINT "heartbeat_runs_scope_binding_check" CHECK (("heartbeat_runs"."scope_kind" = 'company' AND "heartbeat_runs"."issue_id" IS NULL)
|
||||
OR "heartbeat_runs"."scope_kind" = 'issue');
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'issues_visibility_check' AND conrelid = 'public.issues'::regclass) THEN
|
||||
ALTER TABLE "issues" ADD CONSTRAINT "issues_visibility_check" CHECK ("issues"."visibility" in ('open', 'private'));
|
||||
END IF;
|
||||
END $$;--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'projects_visibility_check' AND conrelid = 'public.projects'::regclass) THEN
|
||||
ALTER TABLE "projects" ADD CONSTRAINT "projects_visibility_check" CHECK ("projects"."visibility" in ('open', 'private'));
|
||||
END IF;
|
||||
END $$;
|
||||
--> statement-breakpoint
|
||||
CREATE OR REPLACE FUNCTION set_heartbeat_run_scope_kind() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE candidate uuid;
|
||||
BEGIN
|
||||
-- A private run never becomes a company run through context edits or deletion.
|
||||
IF TG_OP = 'UPDATE' AND OLD.scope_kind = 'issue' THEN
|
||||
IF OLD.issue_id IS NOT NULL AND NEW.issue_id IS NOT NULL AND OLD.issue_id <> NEW.issue_id THEN
|
||||
RAISE EXCEPTION 'run task binding is immutable';
|
||||
END IF;
|
||||
IF OLD.issue_id IS NOT NULL AND NEW.native_issue_id IS NOT NULL AND OLD.issue_id <> NEW.native_issue_id THEN
|
||||
RAISE EXCEPTION 'native run task binding disagrees with privacy binding';
|
||||
END IF;
|
||||
NEW.scope_kind := 'issue';
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
candidate := coalesce(NEW.native_issue_id, NEW.issue_id);
|
||||
IF candidate IS NULL AND coalesce(NEW.context_snapshot->>'issueId', NEW.context_snapshot->>'taskId') ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN
|
||||
candidate := coalesce(NEW.context_snapshot->>'issueId', NEW.context_snapshot->>'taskId')::uuid;
|
||||
END IF;
|
||||
IF candidate IS NOT NULL OR NEW.context_snapshot ? 'issueId' OR NEW.context_snapshot ? 'taskId' OR NEW.scope_kind = 'issue' THEN
|
||||
NEW.scope_kind := 'issue';
|
||||
SELECT id INTO NEW.issue_id FROM issues WHERE id = candidate AND company_id = NEW.company_id;
|
||||
ELSE
|
||||
NEW.scope_kind := 'company';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
DROP TRIGGER IF EXISTS heartbeat_runs_set_scope_kind ON heartbeat_runs;
|
||||
CREATE TRIGGER heartbeat_runs_set_scope_kind BEFORE INSERT OR UPDATE OF issue_id, native_issue_id, context_snapshot, scope_kind
|
||||
ON heartbeat_runs FOR EACH ROW EXECUTE FUNCTION set_heartbeat_run_scope_kind();
|
||||
END $$;
|
||||
--> statement-breakpoint
|
||||
-- Indexed primary-key keyset batches visit each historical run once. Missing
|
||||
-- source tasks become issue-scoped tombstones, never company-visible run content.
|
||||
DO $$ DECLARE cursor_id uuid := '00000000-0000-0000-0000-000000000000'; next_id uuid;
|
||||
BEGIN LOOP
|
||||
WITH batch AS MATERIALIZED (SELECT id FROM heartbeat_runs WHERE id > cursor_id ORDER BY id LIMIT 1000),
|
||||
changed AS (UPDATE heartbeat_runs r SET scope_kind = r.scope_kind FROM batch b WHERE r.id = b.id RETURNING r.id)
|
||||
SELECT id INTO next_id FROM changed ORDER BY id DESC LIMIT 1;
|
||||
EXIT WHEN next_id IS NULL;
|
||||
cursor_id := next_id;
|
||||
COMMIT;
|
||||
END LOOP; END $$;
|
||||
--> statement-breakpoint
|
||||
-- Existing structural children acquire downward inheritance without widening
|
||||
-- any task's visibility. New provenance edges are written at task creation.
|
||||
DO $$ DECLARE cursor_id uuid := '00000000-0000-0000-0000-000000000000'; next_id uuid;
|
||||
BEGIN LOOP
|
||||
WITH batch AS MATERIALIZED (SELECT id FROM issues WHERE id > cursor_id ORDER BY id LIMIT 1000),
|
||||
changed AS (UPDATE issues i SET privacy_parent_issue_id = coalesce(i.privacy_parent_issue_id, i.parent_id)
|
||||
FROM batch b WHERE i.id = b.id RETURNING i.id)
|
||||
SELECT id INTO next_id FROM changed ORDER BY id DESC LIMIT 1;
|
||||
EXIT WHEN next_id IS NULL;
|
||||
cursor_id := next_id;
|
||||
COMMIT;
|
||||
END LOOP; END $$;
|
||||
--> statement-breakpoint
|
||||
-- Keep workspace provenance after reassignment/deletion. A previous task may
|
||||
-- have left files behind; losing the live FK must not publish those files.
|
||||
CREATE OR REPLACE FUNCTION retain_workspace_privacy_sources() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE sources jsonb := '{}'::jsonb; linked jsonb;
|
||||
BEGIN
|
||||
IF TG_OP = 'UPDATE' AND jsonb_typeof(OLD.metadata->'_issuePrivacySources') = 'object' THEN
|
||||
sources := OLD.metadata->'_issuePrivacySources';
|
||||
END IF;
|
||||
IF NEW.source_issue_id IS NOT NULL THEN
|
||||
sources := sources || jsonb_build_object(NEW.source_issue_id::text, true);
|
||||
END IF;
|
||||
SELECT jsonb_object_agg(id::text, true) INTO linked FROM issues
|
||||
WHERE execution_workspace_id = NEW.id AND company_id = NEW.company_id;
|
||||
sources := sources || coalesce(linked, '{}'::jsonb);
|
||||
NEW.metadata := coalesce(NEW.metadata, '{}'::jsonb) || jsonb_build_object('_issuePrivacySources', sources);
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
DROP TRIGGER IF EXISTS execution_workspaces_privacy_sources ON execution_workspaces;
|
||||
CREATE TRIGGER execution_workspaces_privacy_sources BEFORE INSERT OR UPDATE OF source_issue_id, metadata
|
||||
ON execution_workspaces FOR EACH ROW EXECUTE FUNCTION retain_workspace_privacy_sources();
|
||||
END $$;
|
||||
--> statement-breakpoint
|
||||
CREATE OR REPLACE FUNCTION record_issue_workspace_privacy_source() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.execution_workspace_id IS NOT NULL THEN
|
||||
UPDATE execution_workspaces SET metadata = metadata
|
||||
WHERE id = NEW.execution_workspace_id AND company_id = NEW.company_id;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
DROP TRIGGER IF EXISTS issues_record_workspace_privacy_source ON issues;
|
||||
CREATE TRIGGER issues_record_workspace_privacy_source AFTER INSERT OR UPDATE OF execution_workspace_id
|
||||
ON issues FOR EACH ROW EXECUTE FUNCTION record_issue_workspace_privacy_source();
|
||||
END $$;
|
||||
--> statement-breakpoint
|
||||
DO $$ DECLARE cursor_id uuid := '00000000-0000-0000-0000-000000000000'; next_id uuid;
|
||||
BEGIN LOOP
|
||||
WITH batch AS MATERIALIZED (SELECT id FROM execution_workspaces WHERE id > cursor_id ORDER BY id LIMIT 1000),
|
||||
changed AS (UPDATE execution_workspaces w SET metadata = metadata FROM batch b WHERE w.id = b.id RETURNING w.id)
|
||||
SELECT id INTO next_id FROM changed ORDER BY id DESC LIMIT 1;
|
||||
EXIT WHEN next_id IS NULL;
|
||||
cursor_id := next_id;
|
||||
COMMIT;
|
||||
END LOOP; END $$;
|
||||
|
||||
--> statement-breakpoint
|
||||
-- Preserve operation history while retaining every original task/run boundary.
|
||||
CREATE OR REPLACE FUNCTION paperclip_keep_operation_privacy_sources() RETURNS trigger AS $$
|
||||
DECLARE issue_sources jsonb := '{}'::jsonb; run_sources jsonb := '{}'::jsonb;
|
||||
BEGIN
|
||||
IF TG_OP = 'UPDATE' THEN
|
||||
issue_sources := COALESCE(OLD.metadata->'_issuePrivacySources', '{}'::jsonb);
|
||||
run_sources := COALESCE(OLD.metadata->'_runPrivacySources', '{}'::jsonb);
|
||||
IF OLD.issue_id IS NOT NULL THEN issue_sources := issue_sources || jsonb_build_object(OLD.issue_id::text, true); END IF;
|
||||
IF OLD.heartbeat_run_id IS NOT NULL THEN run_sources := run_sources || jsonb_build_object(OLD.heartbeat_run_id::text, true); END IF;
|
||||
END IF;
|
||||
IF NEW.issue_id IS NOT NULL THEN issue_sources := issue_sources || jsonb_build_object(NEW.issue_id::text, true); END IF;
|
||||
IF NEW.heartbeat_run_id IS NOT NULL THEN run_sources := run_sources || jsonb_build_object(NEW.heartbeat_run_id::text, true); END IF;
|
||||
NEW.metadata := COALESCE(NEW.metadata, '{}'::jsonb) || jsonb_build_object('_issuePrivacySources', issue_sources, '_runPrivacySources', run_sources);
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
DROP TRIGGER IF EXISTS workspace_operations_keep_privacy_sources ON workspace_operations;
|
||||
CREATE TRIGGER workspace_operations_keep_privacy_sources BEFORE INSERT OR UPDATE ON workspace_operations
|
||||
FOR EACH ROW EXECUTE FUNCTION paperclip_keep_operation_privacy_sources();
|
||||
END $$;
|
||||
--> statement-breakpoint
|
||||
DO $$
|
||||
DECLARE cursor_id uuid := '00000000-0000-0000-0000-000000000000'; batch_ids uuid[];
|
||||
BEGIN
|
||||
LOOP
|
||||
SELECT array_agg(id ORDER BY id) INTO batch_ids FROM (
|
||||
SELECT id FROM workspace_operations WHERE id > cursor_id ORDER BY id LIMIT 1000
|
||||
) batch;
|
||||
EXIT WHEN batch_ids IS NULL;
|
||||
UPDATE workspace_operations SET metadata = metadata WHERE id = ANY(batch_ids);
|
||||
cursor_id := batch_ids[array_length(batch_ids, 1)];
|
||||
COMMIT;
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE projects ADD COLUMN IF NOT EXISTS privacy_owner_user_id text;
|
||||
--> statement-breakpoint
|
||||
-- Recover management authority from creation evidence, never from read grants.
|
||||
DO $$
|
||||
DECLARE cursor_id uuid := '00000000-0000-0000-0000-000000000000'; batch_ids uuid[];
|
||||
BEGIN
|
||||
LOOP
|
||||
SELECT array_agg(id ORDER BY id) INTO batch_ids FROM (
|
||||
SELECT id FROM projects WHERE id > cursor_id ORDER BY id LIMIT 1000
|
||||
) batch;
|
||||
EXIT WHEN batch_ids IS NULL;
|
||||
UPDATE projects p SET privacy_owner_user_id = COALESCE(p.personal_owner_user_id, (
|
||||
SELECT CASE WHEN a.actor_type = 'user' THEN a.actor_id ELSE coalesce(a.responsible_user_id, r.responsible_user_id) END
|
||||
FROM activity_log a LEFT JOIN heartbeat_runs r ON r.id = a.run_id AND r.company_id = a.company_id
|
||||
WHERE a.company_id = p.company_id AND a.entity_type = 'project' AND a.entity_id = p.id::text AND a.action = 'project.created'
|
||||
ORDER BY a.created_at, a.id LIMIT 1
|
||||
)) WHERE p.id = ANY(batch_ids) AND p.privacy_owner_user_id IS NULL;
|
||||
INSERT INTO project_access_members (company_id, project_id, subject_type, subject_id)
|
||||
SELECT company_id, id, 'user', privacy_owner_user_id FROM projects
|
||||
WHERE id = ANY(batch_ids) AND visibility = 'private' AND privacy_owner_user_id IS NOT NULL
|
||||
ON CONFLICT (project_id, subject_type, subject_id) DO NOTHING;
|
||||
cursor_id := batch_ids[array_length(batch_ids, 1)];
|
||||
COMMIT;
|
||||
END LOOP;
|
||||
END $$;
|
||||
File renamed without changes.
+502
-28
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"id": "819c82c7-c8e7-45d8-acef-349d4fa201a8",
|
||||
"id": "adf783f2-c391-4fd5-b93a-d85e6d3c60a0",
|
||||
"prevId": "9134843c-7e84-421e-915b-beab3c30acb3",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
@@ -11352,31 +11352,6 @@
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"owner_type": {
|
||||
"name": "owner_type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'personal'"
|
||||
},
|
||||
"owner_login": {
|
||||
"name": "owner_login",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"app_name": {
|
||||
"name": "app_name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"handoff": {
|
||||
"name": "handoff",
|
||||
"type": "jsonb",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
@@ -26298,6 +26273,19 @@
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"scope_kind": {
|
||||
"name": "scope_kind",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'company'"
|
||||
},
|
||||
"issue_id": {
|
||||
"name": "issue_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"invocation_source": {
|
||||
"name": "invocation_source",
|
||||
"type": "text",
|
||||
@@ -26855,6 +26843,33 @@
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"heartbeat_runs_company_issue_created_idx": {
|
||||
"name": "heartbeat_runs_company_issue_created_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "issue_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "created_at",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"heartbeat_runs_company_responsible_user_idx": {
|
||||
"name": "heartbeat_runs_company_responsible_user_idx",
|
||||
"columns": [
|
||||
@@ -27093,6 +27108,19 @@
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"heartbeat_runs_issue_id_issues_id_fk": {
|
||||
"name": "heartbeat_runs_issue_id_issues_id_fk",
|
||||
"tableFrom": "heartbeat_runs",
|
||||
"tableTo": "issues",
|
||||
"columnsFrom": [
|
||||
"issue_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"heartbeat_runs_wakeup_request_id_agent_wakeup_requests_id_fk": {
|
||||
"name": "heartbeat_runs_wakeup_request_id_agent_wakeup_requests_id_fk",
|
||||
"tableFrom": "heartbeat_runs",
|
||||
@@ -27143,7 +27171,12 @@
|
||||
}
|
||||
},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"checkConstraints": {
|
||||
"heartbeat_runs_scope_binding_check": {
|
||||
"name": "heartbeat_runs_scope_binding_check",
|
||||
"value": "(\"heartbeat_runs\".\"scope_kind\" = 'company' AND \"heartbeat_runs\".\"issue_id\" IS NULL)\n OR \"heartbeat_runs\".\"scope_kind\" = 'issue'"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.inbox_dismissals": {
|
||||
@@ -28586,6 +28619,166 @@
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.issue_access_grants": {
|
||||
"name": "issue_access_grants",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"issue_id": {
|
||||
"name": "issue_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"subject_type": {
|
||||
"name": "subject_type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"subject_id": {
|
||||
"name": "subject_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"source": {
|
||||
"name": "source",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"granted_by_user_id": {
|
||||
"name": "granted_by_user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"granted_by_agent_id": {
|
||||
"name": "granted_by_agent_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
},
|
||||
"revoked_at": {
|
||||
"name": "revoked_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"issue_access_grants_subject_active_issue_idx": {
|
||||
"name": "issue_access_grants_subject_active_issue_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "subject_type",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "subject_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "revoked_at",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "issue_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"issue_access_grants_issue_idx": {
|
||||
"name": "issue_access_grants_issue_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "issue_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "created_at",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"issue_access_grants_issue_id_issues_id_fk": {
|
||||
"name": "issue_access_grants_issue_id_issues_id_fk",
|
||||
"tableFrom": "issue_access_grants",
|
||||
"tableTo": "issues",
|
||||
"columnsFrom": [
|
||||
"issue_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"issue_access_grants_granted_by_agent_id_agents_id_fk": {
|
||||
"name": "issue_access_grants_granted_by_agent_id_agents_id_fk",
|
||||
"tableFrom": "issue_access_grants",
|
||||
"tableTo": "agents",
|
||||
"columnsFrom": [
|
||||
"granted_by_agent_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {
|
||||
"issue_access_grants_subject_type_check": {
|
||||
"name": "issue_access_grants_subject_type_check",
|
||||
"value": "\"issue_access_grants\".\"subject_type\" in ('user', 'agent')"
|
||||
},
|
||||
"issue_access_grants_source_check": {
|
||||
"name": "issue_access_grants_source_check",
|
||||
"value": "\"issue_access_grants\".\"source\" in ('explicit', 'assignment', 'project')"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.issue_approvals": {
|
||||
"name": "issue_approvals",
|
||||
"schema": "",
|
||||
@@ -33458,6 +33651,25 @@
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"visibility": {
|
||||
"name": "visibility",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'open'"
|
||||
},
|
||||
"privacy_root_issue_id": {
|
||||
"name": "privacy_root_issue_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"privacy_parent_issue_id": {
|
||||
"name": "privacy_parent_issue_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"title": {
|
||||
"name": "title",
|
||||
"type": "text",
|
||||
@@ -33942,6 +34154,48 @@
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"issues_company_privacy_parent_idx": {
|
||||
"name": "issues_company_privacy_parent_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "privacy_parent_issue_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"issues_company_privacy_root_idx": {
|
||||
"name": "issues_company_privacy_root_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "privacy_root_issue_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"issues_company_project_idx": {
|
||||
"name": "issues_company_project_idx",
|
||||
"columns": [
|
||||
@@ -34511,6 +34765,32 @@
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"issues_privacy_root_issue_id_issues_id_fk": {
|
||||
"name": "issues_privacy_root_issue_id_issues_id_fk",
|
||||
"tableFrom": "issues",
|
||||
"tableTo": "issues",
|
||||
"columnsFrom": [
|
||||
"privacy_root_issue_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "no action",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"issues_privacy_parent_issue_id_issues_id_fk": {
|
||||
"name": "issues_privacy_parent_issue_id_issues_id_fk",
|
||||
"tableFrom": "issues",
|
||||
"tableTo": "issues",
|
||||
"columnsFrom": [
|
||||
"privacy_parent_issue_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"issues_assignee_agent_id_agents_id_fk": {
|
||||
"name": "issues_assignee_agent_id_agents_id_fk",
|
||||
"tableFrom": "issues",
|
||||
@@ -34590,6 +34870,10 @@
|
||||
},
|
||||
"policies": {},
|
||||
"checkConstraints": {
|
||||
"issues_visibility_check": {
|
||||
"name": "issues_visibility_check",
|
||||
"value": "\"issues\".\"visibility\" in ('open', 'private')"
|
||||
},
|
||||
"issues_conversation_identity_check": {
|
||||
"name": "issues_conversation_identity_check",
|
||||
"value": "(\n \"issues\".\"conversation_agent_id\" is null and \"issues\".\"conversation_user_id\" is null and \"issues\".\"conversation_state\" is null\n ) or (\n \"issues\".\"conversation_agent_id\" is not null and \"issues\".\"conversation_user_id\" is not null\n and \"issues\".\"assignee_agent_id\" = \"issues\".\"conversation_agent_id\" and \"issues\".\"assignee_agent_id\" is not null\n and \"issues\".\"assignee_user_id\" is null and \"issues\".\"conversation_state\" is not null\n and \"issues\".\"conversation_state\" in ('active', 'waiting')\n and \"issues\".\"status\" not in ('done', 'cancelled')\n )"
|
||||
@@ -39879,6 +40163,150 @@
|
||||
"checkConstraints": {},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.project_access_members": {
|
||||
"name": "project_access_members",
|
||||
"schema": "",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "uuid",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"default": "gen_random_uuid()"
|
||||
},
|
||||
"company_id": {
|
||||
"name": "company_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"project_id": {
|
||||
"name": "project_id",
|
||||
"type": "uuid",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"subject_type": {
|
||||
"name": "subject_type",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"subject_id": {
|
||||
"name": "subject_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamp with time zone",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "now()"
|
||||
}
|
||||
},
|
||||
"indexes": {
|
||||
"project_access_members_project_subject_uq": {
|
||||
"name": "project_access_members_project_subject_uq",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "project_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "subject_type",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "subject_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"project_access_members_subject_lookup_idx": {
|
||||
"name": "project_access_members_subject_lookup_idx",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "subject_type",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "subject_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "project_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": false,
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
"project_access_members_company_id_companies_id_fk": {
|
||||
"name": "project_access_members_company_id_companies_id_fk",
|
||||
"tableFrom": "project_access_members",
|
||||
"tableTo": "companies",
|
||||
"columnsFrom": [
|
||||
"company_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
},
|
||||
"project_access_members_project_id_projects_id_fk": {
|
||||
"name": "project_access_members_project_id_projects_id_fk",
|
||||
"tableFrom": "project_access_members",
|
||||
"tableTo": "projects",
|
||||
"columnsFrom": [
|
||||
"project_id"
|
||||
],
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {
|
||||
"project_access_members_subject_type_check": {
|
||||
"name": "project_access_members_subject_type_check",
|
||||
"value": "\"project_access_members\".\"subject_type\" in ('user', 'agent')"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.project_goals": {
|
||||
"name": "project_goals",
|
||||
"schema": "",
|
||||
@@ -40508,6 +40936,25 @@
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"visibility": {
|
||||
"name": "visibility",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"default": "'open'"
|
||||
},
|
||||
"privacy_owner_user_id": {
|
||||
"name": "privacy_owner_user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"personal_owner_user_id": {
|
||||
"name": "personal_owner_user_id",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false
|
||||
},
|
||||
"status": {
|
||||
"name": "status",
|
||||
"type": "text",
|
||||
@@ -40599,6 +41046,28 @@
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
},
|
||||
"projects_company_personal_owner_uq": {
|
||||
"name": "projects_company_personal_owner_uq",
|
||||
"columns": [
|
||||
{
|
||||
"expression": "company_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
},
|
||||
{
|
||||
"expression": "personal_owner_user_id",
|
||||
"isExpression": false,
|
||||
"asc": true,
|
||||
"nulls": "last"
|
||||
}
|
||||
],
|
||||
"isUnique": true,
|
||||
"where": "\"projects\".\"personal_owner_user_id\" is not null",
|
||||
"concurrently": false,
|
||||
"method": "btree",
|
||||
"with": {}
|
||||
}
|
||||
},
|
||||
"foreignKeys": {
|
||||
@@ -40645,7 +41114,12 @@
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"policies": {},
|
||||
"checkConstraints": {},
|
||||
"checkConstraints": {
|
||||
"projects_visibility_check": {
|
||||
"name": "projects_visibility_check",
|
||||
"value": "\"projects\".\"visibility\" in ('open', 'private')"
|
||||
}
|
||||
},
|
||||
"isRLSEnabled": false
|
||||
},
|
||||
"public.provider_trace_records": {
|
||||
|
||||
+2380
-14
File diff suppressed because it is too large.
Load diff
+9
-2
@@ -2182,8 +2182,15 @@
|
||||
{
|
||||
"idx": 313,
|
||||
"version": "7",
|
||||
"when": 1791352043149,
|
||||
"tag": "0313_wonderful_ben_parker",
|
||||
"when": 1791371746435,
|
||||
"tag": "0313_private_task_access",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 314,
|
||||
"version": "7",
|
||||
"when": 1791374848340,
|
||||
"tag": "0314_loving_ezekiel",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
|
||||
@@ -10,12 +10,14 @@ import {
|
||||
integer,
|
||||
bigint,
|
||||
boolean,
|
||||
check,
|
||||
unique,
|
||||
uniqueIndex,
|
||||
} from "drizzle-orm/pg-core";
|
||||
import { companies } from "./companies.js";
|
||||
import { agents } from "./agents.js";
|
||||
import { agentWakeupRequests } from "./agent_wakeup_requests.js";
|
||||
import { issues } from "./issues.js";
|
||||
|
||||
export const heartbeatRuns = pgTable(
|
||||
"heartbeat_runs",
|
||||
@@ -23,6 +25,11 @@ export const heartbeatRuns = pgTable(
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
companyId: uuid("company_id").notNull().references(() => companies.id),
|
||||
agentId: uuid("agent_id").notNull().references(() => agents.id),
|
||||
scopeKind: text("scope_kind")
|
||||
.$type<"company" | "issue">()
|
||||
.notNull()
|
||||
.default("company"),
|
||||
issueId: uuid("issue_id").references((): AnyPgColumn => issues.id, { onDelete: "set null" }),
|
||||
invocationSource: text("invocation_source").notNull().default("on_demand"),
|
||||
triggerDetail: text("trigger_detail"),
|
||||
status: text("status").notNull().default("queued"),
|
||||
@@ -104,6 +111,11 @@ export const heartbeatRuns = pgTable(
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(table) => ({
|
||||
scopeBindingCheck: check(
|
||||
"heartbeat_runs_scope_binding_check",
|
||||
sql`(${table.scopeKind} = 'company' AND ${table.issueId} IS NULL)
|
||||
OR ${table.scopeKind} = 'issue'`,
|
||||
),
|
||||
costAccountingPendingIdx: index("heartbeat_runs_cost_accounting_pending_idx").on(table.updatedAt, table.id).where(sql`${table.costAccountingPending} = true`),
|
||||
executionStatusDeliveryIdx: index("heartbeat_runs_execution_status_delivery_idx")
|
||||
.on(table.executionStatusDeliveryId).where(sql`${table.executionStatusDeliveryId} is not null`),
|
||||
@@ -130,6 +142,11 @@ export const heartbeatRuns = pgTable(
|
||||
table.agentId,
|
||||
table.startedAt,
|
||||
),
|
||||
companyIssueCreatedIdx: index("heartbeat_runs_company_issue_created_idx").on(
|
||||
table.companyId,
|
||||
table.issueId,
|
||||
table.createdAt,
|
||||
),
|
||||
companyResponsibleUserIdx: index("heartbeat_runs_company_responsible_user_idx").on(
|
||||
table.companyId,
|
||||
table.responsibleUserId,
|
||||
|
||||
@@ -26,6 +26,7 @@ export { agentTaskSessions, agentSessionGoalActions } from "./agent_task_session
|
||||
export { agentWakeupRequests } from "./agent_wakeup_requests.js";
|
||||
export { projects } from "./projects.js";
|
||||
export { projectMemberships } from "./project_memberships.js";
|
||||
export { projectAccessMembers } from "./project_access_members.js";
|
||||
export { documentMemberships } from "./document_memberships.js";
|
||||
export { projectWorkspaces } from "./project_workspaces.js";
|
||||
export { executionWorkspaces } from "./execution_workspaces.js";
|
||||
@@ -41,6 +42,7 @@ export { projectGoals } from "./project_goals.js";
|
||||
export { goals } from "./goals.js";
|
||||
export { folders } from "./folders.js";
|
||||
export { issues } from "./issues.js";
|
||||
export { issueAccessGrants } from "./issue_access_grants.js";
|
||||
export { issueWatchdogs } from "./issue_watchdogs.js";
|
||||
export { issuePlanDecompositions } from "./issue_plan_decompositions.js";
|
||||
export { issueRecoveryActions } from "./issue_recovery_actions.js";
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { sql } from "drizzle-orm";
|
||||
import { check, index, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
|
||||
import { agents } from "./agents.js";
|
||||
import { issues } from "./issues.js";
|
||||
|
||||
export const issueAccessGrants = pgTable(
|
||||
"issue_access_grants",
|
||||
{
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
issueId: uuid("issue_id").notNull().references(() => issues.id, { onDelete: "cascade" }),
|
||||
subjectType: text("subject_type").notNull(),
|
||||
subjectId: text("subject_id").notNull(),
|
||||
source: text("source").notNull(),
|
||||
grantedByUserId: text("granted_by_user_id"),
|
||||
grantedByAgentId: uuid("granted_by_agent_id").references(() => agents.id, { onDelete: "set null" }),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
revokedAt: timestamp("revoked_at", { withTimezone: true }),
|
||||
},
|
||||
(table) => ({
|
||||
subjectTypeCheck: check(
|
||||
"issue_access_grants_subject_type_check",
|
||||
sql`${table.subjectType} in ('user', 'agent')`,
|
||||
),
|
||||
sourceCheck: check(
|
||||
"issue_access_grants_source_check",
|
||||
sql`${table.source} in ('explicit', 'assignment', 'project')`,
|
||||
),
|
||||
predicateIdx: index("issue_access_grants_subject_active_issue_idx").on(
|
||||
table.subjectType,
|
||||
table.subjectId,
|
||||
table.revokedAt,
|
||||
table.issueId,
|
||||
),
|
||||
issueIdx: index("issue_access_grants_issue_idx").on(table.issueId, table.createdAt),
|
||||
}),
|
||||
);
|
||||
@@ -38,6 +38,9 @@ export const issues = pgTable(
|
||||
projectWorkspaceId: uuid("project_workspace_id").references(() => projectWorkspaces.id, { onDelete: "set null" }),
|
||||
goalId: uuid("goal_id").references(() => goals.id),
|
||||
parentId: uuid("parent_id").references((): AnyPgColumn => issues.id),
|
||||
visibility: text("visibility").notNull().default("open"),
|
||||
privacyRootIssueId: uuid("privacy_root_issue_id").references((): AnyPgColumn => issues.id),
|
||||
privacyParentIssueId: uuid("privacy_parent_issue_id").references((): AnyPgColumn => issues.id, { onDelete: "set null" }),
|
||||
title: text("title").notNull(),
|
||||
titleNeedsGeneration: boolean("title_needs_generation").notNull().default(false),
|
||||
description: text("description"),
|
||||
@@ -92,6 +95,7 @@ export const issues = pgTable(
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(table) => ({
|
||||
visibilityCheck: check("issues_visibility_check", sql`${table.visibility} in ('open', 'private')`),
|
||||
conversationIdentityIdx: uniqueIndex("issues_conversation_identity_idx").on(table.companyId, table.conversationAgentId, table.conversationUserId),
|
||||
conversationIdentityCheck: check("issues_conversation_identity_check", sql`(
|
||||
${table.conversationAgentId} is null and ${table.conversationUserId} is null and ${table.conversationState} is null
|
||||
@@ -117,6 +121,8 @@ export const issues = pgTable(
|
||||
),
|
||||
responsibleUserIdx: index("issues_company_responsible_user_idx").on(table.companyId, table.responsibleUserId),
|
||||
parentIdx: index("issues_company_parent_idx").on(table.companyId, table.parentId),
|
||||
privacyParentIdx: index("issues_company_privacy_parent_idx").on(table.companyId, table.privacyParentIssueId),
|
||||
privacyRootIdx: index("issues_company_privacy_root_idx").on(table.companyId, table.privacyRootIssueId),
|
||||
projectIdx: index("issues_company_project_idx").on(table.companyId, table.projectId),
|
||||
originIdx: index("issues_company_origin_idx").on(table.companyId, table.originKind, table.originId),
|
||||
projectWorkspaceIdx: index("issues_company_project_workspace_idx").on(table.companyId, table.projectWorkspaceId),
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { sql } from "drizzle-orm";
|
||||
import { check, index, pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
|
||||
import { companies } from "./companies.js";
|
||||
import { projects } from "./projects.js";
|
||||
|
||||
/** Authorization membership for private projects; unrelated to sidebar project_memberships. */
|
||||
export const projectAccessMembers = pgTable(
|
||||
"project_access_members",
|
||||
{
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
|
||||
projectId: uuid("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
subjectType: text("subject_type").notNull(),
|
||||
subjectId: text("subject_id").notNull(),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(table) => ({
|
||||
subjectTypeCheck: check(
|
||||
"project_access_members_subject_type_check",
|
||||
sql`${table.subjectType} in ('user', 'agent')`,
|
||||
),
|
||||
projectSubjectUq: uniqueIndex("project_access_members_project_subject_uq").on(
|
||||
table.projectId,
|
||||
table.subjectType,
|
||||
table.subjectId,
|
||||
),
|
||||
subjectLookupIdx: index("project_access_members_subject_lookup_idx").on(
|
||||
table.companyId,
|
||||
table.subjectType,
|
||||
table.subjectId,
|
||||
table.projectId,
|
||||
),
|
||||
}),
|
||||
);
|
||||
@@ -1,4 +1,5 @@
|
||||
import { pgTable, uuid, text, timestamp, date, index, jsonb } from "drizzle-orm/pg-core";
|
||||
import { sql } from "drizzle-orm";
|
||||
import { pgTable, uuid, text, timestamp, date, index, jsonb, check, uniqueIndex } from "drizzle-orm/pg-core";
|
||||
import type { AgentEnvConfig } from "@paperclipai/shared";
|
||||
import { companies } from "./companies.js";
|
||||
import { goals } from "./goals.js";
|
||||
@@ -12,6 +13,9 @@ export const projects = pgTable(
|
||||
goalId: uuid("goal_id").references(() => goals.id),
|
||||
name: text("name").notNull(),
|
||||
description: text("description"),
|
||||
visibility: text("visibility").notNull().default("open"),
|
||||
privacyOwnerUserId: text("privacy_owner_user_id"),
|
||||
personalOwnerUserId: text("personal_owner_user_id"),
|
||||
status: text("status").notNull().default("backlog"),
|
||||
leadAgentId: uuid("lead_agent_id").references(() => agents.id),
|
||||
targetDate: date("target_date"),
|
||||
@@ -27,5 +31,9 @@ export const projects = pgTable(
|
||||
},
|
||||
(table) => ({
|
||||
companyIdx: index("projects_company_idx").on(table.companyId),
|
||||
visibilityCheck: check("projects_visibility_check", sql`${table.visibility} in ('open', 'private')`),
|
||||
personalOwnerUq: uniqueIndex("projects_company_personal_owner_uq")
|
||||
.on(table.companyId, table.personalOwnerUserId)
|
||||
.where(sql`${table.personalOwnerUserId} is not null`),
|
||||
}),
|
||||
);
|
||||
@@ -183,6 +183,71 @@ fn runtime_context_session_identity(context: &Value) -> Option<Value> {
|
||||
Some(identity)
|
||||
}
|
||||
|
||||
// Mirrors only the canonical asset suffix from composeNativeSystemInstructions.
|
||||
// No replacement is allowed inside the prompt or a user's custom entry.
|
||||
fn registered_asset_suffix(context: &Value) -> Option<String> {
|
||||
let instructions = context.get("instructions")?;
|
||||
let root = instructions.pointer("/bundle/rootPath")?.as_str()?;
|
||||
if root.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut blocks = Vec::new();
|
||||
if let Some(copy) = instructions
|
||||
.get("workingCopy")
|
||||
.filter(|value| !value.is_null())
|
||||
{
|
||||
let path = copy.get("rootPath")?.as_str()?;
|
||||
let entry = copy.get("entryPath")?.as_str()?;
|
||||
if path.is_empty() || entry.is_empty() {
|
||||
return None;
|
||||
}
|
||||
blocks.push(if copy.get("kind").and_then(Value::as_str) == Some("agent_files") {
|
||||
format!("Your persistent agent directory (AGENT_HOME) is {path}. Your instruction entry is {entry}, relative to that directory. All supported files and subfolders there are restored across tasks and sessions, and collected after this provider stops. Write task deliverables in the task working directory. Only changed or deleted files synchronize; the last sync wins for the same file. Temporary copies are cleaned up without retaining file history. Check the save receipt before claiming persistence.")
|
||||
} else {
|
||||
format!("Your editable agent instruction file is {path}/{entry}. Edit this registered private copy normally. After this run stops, Paperclip saves changed content as a persistent revision if your responsible user still has permission and the baseline has not changed. Check the run's instruction-save receipt before claiming persistence. Conflicts are preserved for explicit resolution. Repository instruction files, skills, and this run's loaded prompt are separate and are not collected.")
|
||||
});
|
||||
}
|
||||
blocks.push(format!("Read-only instruction sibling root: {root}"));
|
||||
Some(blocks.join("\n\n"))
|
||||
}
|
||||
|
||||
fn only_registered_asset_text_changed(
|
||||
current: &AcpxProviderDescriptor,
|
||||
prior: &AcpxProviderDescriptor,
|
||||
) -> bool {
|
||||
if current.instructions == prior.instructions
|
||||
&& current
|
||||
.runtime_context
|
||||
.pointer("/instructions/workingCopy/rootPath")
|
||||
== prior
|
||||
.runtime_context
|
||||
.pointer("/instructions/workingCopy/rootPath")
|
||||
&& current
|
||||
.runtime_context
|
||||
.pointer("/instructions/bundle/rootPath")
|
||||
== prior
|
||||
.runtime_context
|
||||
.pointer("/instructions/bundle/rootPath")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let Some(current_suffix) = registered_asset_suffix(¤t.runtime_context) else {
|
||||
return false;
|
||||
};
|
||||
let Some(prior_suffix) = registered_asset_suffix(&prior.runtime_context) else {
|
||||
return false;
|
||||
};
|
||||
current
|
||||
.instructions
|
||||
.strip_suffix(&format!("\n\n{current_suffix}"))
|
||||
.zip(
|
||||
prior
|
||||
.instructions
|
||||
.strip_suffix(&format!("\n\n{prior_suffix}")),
|
||||
)
|
||||
.is_some_and(|(current_prefix, prior_prefix)| current_prefix == prior_prefix)
|
||||
}
|
||||
|
||||
impl AcpxProviderDescriptor {
|
||||
fn validate_session(
|
||||
&self,
|
||||
@@ -1055,7 +1120,8 @@ impl AcpxCommandExecutor {
|
||||
object.remove("aggregateDigest");
|
||||
}
|
||||
}
|
||||
if run_attachment_policy(&descriptor.agent) == RunAttachmentPolicy::AuthenticatedRunGrants {
|
||||
let attachment_policy = run_attachment_policy(&descriptor.agent);
|
||||
if attachment_policy != RunAttachmentPolicy::ImmutableInstructions {
|
||||
// New runs rotate authenticated instruction text and registered
|
||||
// file-copy grants. Preserve mainline MCP refresh while comparing
|
||||
// every remaining context identity, including unknown policy fields.
|
||||
@@ -1066,7 +1132,12 @@ impl AcpxCommandExecutor {
|
||||
.is_some_and(|(current, prior)| current == prior);
|
||||
let grants_changed = descriptor.instructions != state.descriptor.instructions
|
||||
|| descriptor.runtime_context != state.descriptor.runtime_context;
|
||||
if !compatible || (grants_changed && descriptor.run_id == state.descriptor.run_id) {
|
||||
let text_compatible = attachment_policy == RunAttachmentPolicy::AuthenticatedRunGrants
|
||||
|| only_registered_asset_text_changed(&descriptor, &state.descriptor);
|
||||
if !compatible
|
||||
|| !text_compatible
|
||||
|| (grants_changed && descriptor.run_id == state.descriptor.run_id)
|
||||
{
|
||||
return Err(DurableRunnerError::invalid(
|
||||
"ACPX run.attach changed runtime context outside a new authenticated run",
|
||||
));
|
||||
@@ -2953,6 +3024,30 @@ mod tests {
|
||||
fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attachment_asset_suffix_matches_typescript_composer() {
|
||||
let fixtures: Value = serde_json::from_str(include_str!(
|
||||
"../../../../test/fixtures/registered-asset-instructions.json"
|
||||
))
|
||||
.unwrap();
|
||||
for fixture in fixtures.as_array().unwrap() {
|
||||
let suffix = registered_asset_suffix(&fixture["context"]).unwrap();
|
||||
assert_eq!(
|
||||
fixture["instructions"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.strip_suffix(&format!("\n\n{suffix}")),
|
||||
Some(
|
||||
format!(
|
||||
"Pinned prompt.\n\n{}\n\nPinned connection policy.",
|
||||
fixture["entry"].as_str().unwrap()
|
||||
)
|
||||
.as_str()
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn restores_settled_session_for_explicit_run_attachment_only() {
|
||||
@@ -3157,6 +3252,17 @@ mod tests {
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn cursor_attachment_rotates_only_authenticated_run_grants() {
|
||||
authenticated_run_grant_attachment("cursor");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn claude_attachment_rotates_only_authenticated_asset_paths() {
|
||||
authenticated_run_grant_attachment("claude");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn authenticated_run_grant_attachment(agent: &str) {
|
||||
let directory = temporary_directory("cursor-cross-run-attach");
|
||||
let runtime = directory.join("runtime");
|
||||
let workspace = directory.join("workspace");
|
||||
@@ -3177,7 +3283,7 @@ mod tests {
|
||||
args: Vec::new(),
|
||||
artifacts: vec![artifact(&command)],
|
||||
};
|
||||
let mut descriptor_value = descriptor("cursor");
|
||||
let mut descriptor_value = descriptor(agent);
|
||||
descriptor_value["sidecarCommand"] = json!(command);
|
||||
descriptor_value["runtimeContext"] = json!({ "instructions": { "digest": "stable" }, "mcp": { "digest": "before" }, "aggregateDigest": "before" });
|
||||
descriptor_value["sidecarArgs"] = json!([]);
|
||||
@@ -3203,6 +3309,12 @@ mod tests {
|
||||
"mcp": {"assignmentSetId": "assignment-1", "digest": "e".repeat(64), "bindingId": "old-run-binding"},
|
||||
"futurePolicy": {"companyId": "company-1"},
|
||||
});
|
||||
if agent == "claude" {
|
||||
descriptor_value["instructions"] = json!(format!(
|
||||
"Pinned prompt. Custom entry mentioning /old-bundle.\n\n{}",
|
||||
registered_asset_suffix(&descriptor_value["runtimeContext"]).unwrap()
|
||||
));
|
||||
}
|
||||
let original_descriptor: AcpxProviderDescriptor =
|
||||
serde_json::from_value(descriptor_value.clone()).unwrap();
|
||||
let identity = AcpxProviderSessionIdentity {
|
||||
@@ -3330,6 +3442,52 @@ mod tests {
|
||||
json!("/new-bundle");
|
||||
descriptor_value["runtimeContext"]["skills"][0]["bundle"]["rootPath"] = json!("/new-skill");
|
||||
descriptor_value["runtimeContext"]["mcp"]["bindingId"] = json!("new-run-binding");
|
||||
if agent == "claude" {
|
||||
descriptor_value["instructions"] = json!(format!(
|
||||
"Pinned prompt. Custom entry mentioning /old-bundle.\n\n{}",
|
||||
registered_asset_suffix(&descriptor_value["runtimeContext"]).unwrap()
|
||||
));
|
||||
let mut stale_text = descriptor_value.clone();
|
||||
stale_text["instructions"] =
|
||||
json!(original.state.as_ref().unwrap().descriptor.instructions);
|
||||
assert!(attached
|
||||
.attach_run(&json!({"provider": stale_text}))
|
||||
.is_err());
|
||||
let mut changed_text = descriptor_value.clone();
|
||||
changed_text["instructions"] = json!(descriptor_value["instructions"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.replace("Custom entry", "Changed entry"));
|
||||
assert!(attached
|
||||
.attach_run(&json!({"provider": changed_text}))
|
||||
.is_err());
|
||||
// A path inside the custom entry is content, not a relocatable grant.
|
||||
let mut changed_example = descriptor_value.clone();
|
||||
changed_example["instructions"] = json!(descriptor_value["instructions"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.replace("mentioning /old-bundle", "mentioning /new-bundle"));
|
||||
assert!(attached
|
||||
.attach_run(&json!({"provider": changed_example}))
|
||||
.is_err());
|
||||
for pointer in [
|
||||
"/prompt/digest",
|
||||
"/instructions/bundle/digest",
|
||||
"/skills/0/bundle/digest",
|
||||
"/futurePolicy/companyId",
|
||||
] {
|
||||
let mut changed_identity = descriptor_value.clone();
|
||||
*changed_identity["runtimeContext"]
|
||||
.pointer_mut(pointer)
|
||||
.unwrap() = json!("changed");
|
||||
assert!(
|
||||
attached
|
||||
.attach_run(&json!({"provider": changed_identity}))
|
||||
.is_err(),
|
||||
"{pointer}"
|
||||
);
|
||||
}
|
||||
}
|
||||
attached
|
||||
.attach_run(&json!({"provider": descriptor_value}))
|
||||
.unwrap();
|
||||
|
||||
+7
-1
@@ -6,11 +6,13 @@
|
||||
pub(crate) enum RunAttachmentPolicy {
|
||||
ImmutableInstructions,
|
||||
AuthenticatedRunGrants,
|
||||
AuthenticatedAssetPaths,
|
||||
}
|
||||
|
||||
pub(crate) fn run_attachment_policy(agent: &str) -> RunAttachmentPolicy {
|
||||
match agent {
|
||||
"cursor" => RunAttachmentPolicy::AuthenticatedRunGrants,
|
||||
"claude" => RunAttachmentPolicy::AuthenticatedAssetPaths,
|
||||
_ => RunAttachmentPolicy::ImmutableInstructions,
|
||||
}
|
||||
}
|
||||
@@ -25,7 +27,11 @@ mod tests {
|
||||
run_attachment_policy("cursor"),
|
||||
RunAttachmentPolicy::AuthenticatedRunGrants
|
||||
);
|
||||
for agent in ["claude", "codex", "grok", "pi", "copilot", "unknown"] {
|
||||
assert_eq!(
|
||||
run_attachment_policy("claude"),
|
||||
RunAttachmentPolicy::AuthenticatedAssetPaths
|
||||
);
|
||||
for agent in ["codex", "grok", "pi", "copilot", "unknown"] {
|
||||
assert_eq!(
|
||||
run_attachment_policy(agent),
|
||||
RunAttachmentPolicy::ImmutableInstructions
|
||||
|
||||
@@ -4916,6 +4916,18 @@ mod tests {
|
||||
assert!(block_message.len() <= 512);
|
||||
assert!(!block_message.chars().any(char::is_control));
|
||||
|
||||
let question_result = schema_rejection(
|
||||
"request_human_input",
|
||||
json!({"PRIVATE_FIELD": "PRIVATE_VALUE"}),
|
||||
);
|
||||
let question_message = question_result.result["error"]["message"].as_str().unwrap();
|
||||
assert!(question_message.contains("payload.questionSet"));
|
||||
assert!(question_message.contains("/required (missing \"requiredField\")"));
|
||||
assert!(!question_message.contains("PRIVATE_FIELD"));
|
||||
assert!(!question_result.result.to_string().contains("PRIVATE_VALUE"));
|
||||
assert!(question_message.len() <= 512);
|
||||
assert_eq!(question_result.result["error"]["retryable"], false);
|
||||
|
||||
let ordinary_result = schema_rejection("get_task_context", json!({}));
|
||||
assert_eq!(
|
||||
ordinary_result.result["error"]["message"],
|
||||
|
||||
@@ -40,6 +40,7 @@ const REPLAY_FILTER_WORDS: usize = 32_768;
|
||||
const ACTIVE_TURN_RECEIPT_LIMIT_MESSAGE: &str =
|
||||
"durable provider tool receipt limit reached for the active turn";
|
||||
const COMPLETION_INPUT_SCHEMA_HINT: &str = "Invalid paperclip_finish arguments. Required fields: reportedWorkDisposition, summary, completionClaim, evidence, and verification. When reportedWorkDisposition is yielded, continuation must include kind=response_wake, summary, and idempotencyKey.";
|
||||
const QUESTION_INPUT_SCHEMA_HINT: &str = "Invalid request_human_input arguments. Required fields: idempotencyKey, interactionKind, title, prompt, and continuationPolicy. For questions, use payload.version=1 and a complete payload.questionSet matching the authorized schema. Preserve the supplied question and option IDs.";
|
||||
const BLOCK_INPUT_SCHEMA_HINT: &str = "Invalid paperclip_block arguments. Required fields: reportedWorkDisposition=blocked, summary, completionClaim, evidence, verification, and blocker. blocker must include reasonCode, owner, unblockAction, and scope.";
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
|
||||
@@ -242,6 +243,7 @@ impl ProviderBridgeError {
|
||||
let safe_provider_message = match operation_id {
|
||||
"paperclip_finish" => Some(COMPLETION_INPUT_SCHEMA_HINT),
|
||||
"paperclip_block" => Some(BLOCK_INPUT_SCHEMA_HINT),
|
||||
"request_human_input" => Some(QUESTION_INPUT_SCHEMA_HINT),
|
||||
_ => None,
|
||||
};
|
||||
Self {
|
||||
@@ -251,7 +253,7 @@ impl ProviderBridgeError {
|
||||
}
|
||||
|
||||
fn with_schema_locations(mut self, validator: &jsonschema::Validator, input: &Value) -> Self {
|
||||
// Only completion tools have a provider-safe hint. Report bounded paths
|
||||
// Only the reserved tools above have a provider-safe hint. Report bounded paths
|
||||
// into the authorized schema, never the submitted values or unknown keys.
|
||||
if let Some(message) = self.safe_provider_message.as_mut() {
|
||||
let locations = validator
|
||||
|
||||
@@ -875,7 +875,7 @@ pub fn normalize_codex_notification(method: &str, params: &Value) -> Vec<Normali
|
||||
"text": bounded_text(string(params.get("delta")), MAX_TEXT_CHARS),
|
||||
}),
|
||||
),
|
||||
"item/started" | "item/completed" => {
|
||||
"item/started" | "item/updated" | "item/completed" => {
|
||||
let provider_item = item(params);
|
||||
let item_id = stable_id(string(provider_item.get("id")), "codex-item");
|
||||
let item_type = string(provider_item.get("type"));
|
||||
@@ -883,12 +883,12 @@ pub fn normalize_codex_notification(method: &str, params: &Value) -> Vec<Normali
|
||||
let completed = method == "item/completed";
|
||||
if matches!(
|
||||
item_type,
|
||||
"commandExecution" | "mcpToolCall" | "dynamicToolCall"
|
||||
"commandExecution" | "mcpToolCall" | "dynamicToolCall" | "builtinToolCall"
|
||||
) {
|
||||
let mut payload = json!({
|
||||
"schema": "paperclip.tool.execution.v1",
|
||||
"executionId": item_id,
|
||||
"transport": match item_type { "mcpToolCall" => "mcp", "dynamicToolCall" => "dynamic", _ => "process" },
|
||||
"transport": match item_type { "mcpToolCall" => "mcp", "dynamicToolCall" => "dynamic", "builtinToolCall" => "builtin", _ => "process" },
|
||||
"operation": if item_type == "commandExecution" { "execute" } else { "unknown" },
|
||||
"name": provider_item.get("tool").or_else(|| provider_item.get("command")).and_then(Value::as_str).map(|value| bounded_text(value, 240)),
|
||||
"target": Value::Null,
|
||||
@@ -913,6 +913,8 @@ pub fn normalize_codex_notification(method: &str, params: &Value) -> Vec<Normali
|
||||
&mut events,
|
||||
if completed {
|
||||
"tool.execution.completed"
|
||||
} else if method == "item/updated" {
|
||||
"tool.execution.progressed"
|
||||
} else {
|
||||
"tool.execution.started"
|
||||
},
|
||||
@@ -1752,6 +1754,36 @@ mod tests {
|
||||
assert!(!events[0].payload.to_string().contains("top-secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_opencode_builtin_tool_activity_and_bounded_errors() {
|
||||
for (method, event_type, status) in [
|
||||
("item/started", "tool.execution.started", "running"),
|
||||
("item/updated", "tool.execution.progressed", "running"),
|
||||
("item/completed", "tool.execution.completed", "failed"),
|
||||
] {
|
||||
let events = normalize_codex_notification(
|
||||
method,
|
||||
&json!({
|
||||
"threadId": "session-1", "turnId": "turn-1", "item": {
|
||||
"id": "part-invalid", "type": "builtinToolCall", "tool": "invalid",
|
||||
"status": status, "output": "Tool not found: fixture_missing; token=top-secret",
|
||||
}
|
||||
}),
|
||||
);
|
||||
assert_eq!(events[0].event_type, event_type);
|
||||
assert_eq!(events[0].payload["executionId"], "part-invalid");
|
||||
assert_eq!(events[0].payload["transport"], "builtin");
|
||||
assert_eq!(events[0].payload["name"], "invalid");
|
||||
assert_eq!(events[0].payload["status"], status);
|
||||
assert!(events[0].payload["output"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("fixture_missing"));
|
||||
assert!(!events[0].payload.to_string().contains("top-secret"));
|
||||
assert!(events[0].payload.get("callId").is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_codex_final_answer_as_final_agent_message() {
|
||||
let final_answer = normalize_codex_notification(
|
||||
|
||||
@@ -13,6 +13,7 @@ import { parseNativeRuntimeContext } from "../contracts/runtime-context.js";
|
||||
import { openCodeProxyTaskEnvelope } from "./opencode-proxy-task-envelope.js";
|
||||
import {
|
||||
openCodeProxyItemNotification,
|
||||
openCodeProxyToolNotification,
|
||||
openCodeProxyTerminalNotification,
|
||||
shouldAnnounceOpenCodeProxyTurn,
|
||||
shouldForwardOpenCodeProxyItem,
|
||||
@@ -192,7 +193,11 @@ function announceTurnStarted(opened: HarnessSession, turnId: string): void {
|
||||
async function pumpEvents(opened: HarnessSession): Promise<void> {
|
||||
for await (const event of opened.events()) {
|
||||
const payload = record(event.payload);
|
||||
if (event.eventType === "turn.started") {
|
||||
const toolActivity = openCodeProxyToolNotification({ eventType: event.eventType,
|
||||
threadId: opened.ids().driverSessionId, turnId: event.turnId, payload });
|
||||
if (toolActivity) {
|
||||
send(toolActivity);
|
||||
} else if (event.eventType === "turn.started") {
|
||||
if (typeof event.turnId === "string")
|
||||
announceTurnStarted(opened, event.turnId);
|
||||
} else if (
|
||||
|
||||
@@ -1,3 +1,24 @@
|
||||
/** Forward bounded tool activity without inventing a host-call identity or arguments. */
|
||||
export function openCodeProxyToolNotification(input: {
|
||||
eventType: string; threadId: string; turnId?: string; payload: Record<string, unknown>;
|
||||
}): { method: string; params: Record<string, unknown> } | null {
|
||||
const phase = ({ "tool.execution.started": "started", "tool.execution.progressed": "updated", "tool.execution.completed": "completed" } as Record<string, string>)[input.eventType];
|
||||
if (!phase) return null;
|
||||
const p = input.payload;
|
||||
if (!input.turnId || typeof p.executionId !== "string" || !p.executionId || p.schema !== "paperclip.tool.execution.v1")
|
||||
throw new Error("OpenCode tool activity omitted its bound identity");
|
||||
const type = ({ builtin: "builtinToolCall", mcp: "mcpToolCall", dynamic: "dynamicToolCall", process: "commandExecution" } as Record<string, string>)[String(p.transport)];
|
||||
if (!type) throw new Error("OpenCode tool activity has an unsupported transport");
|
||||
return { method: `item/${phase}`, params: {
|
||||
threadId: input.threadId, turnId: input.turnId, itemId: p.executionId,
|
||||
item: { id: p.executionId, type, tool: p.name, server: p.namespace,
|
||||
readOnlyHint: p.readOnly, status: p.status, durationMs: p.durationMs, exitCode: p.exitCode,
|
||||
// This is the already bounded provider-visible result, not raw input or a private trace.
|
||||
output: typeof p.output === "string" ? p.output.slice(0, 16_384) : "",
|
||||
},
|
||||
} };
|
||||
}
|
||||
|
||||
export function shouldForwardOpenCodeProxyItem(input: {
|
||||
turnId?: string;
|
||||
kind?: unknown;
|
||||
|
||||
@@ -106,11 +106,17 @@ it.each([true, false])("settles a real proxy interrupt with controller feedback
|
||||
await response(1);
|
||||
send({ id: 2, method: "thread/start", params: { cwd: root, model: "openrouter/deepseek/deepseek-v4-flash-0731", completionContract: { revision: "proxy-v1", criterionIds: ["objective"] }, conversationMode: "prepared" } });
|
||||
await response(2);
|
||||
send({ id: 3, method: "turn/start", params: { input: [{ type: "text", text: JSON.stringify({ schema: "paperclip.native-model-envelope.v3", task: { prompt: "completion-feedback" }, completionContract: { revision: "proxy-v1", criteria: [{ id: "objective", requirement: "Complete the fixture." }] } }) }] } });
|
||||
send({ id: 3, method: "turn/start", params: { input: [{ type: "text", text: JSON.stringify({ schema: "paperclip.native-model-envelope.v3", task: { prompt: "invalid-tool-feedback completion-feedback" }, completionContract: { revision: "proxy-v1", criteria: [{ id: "objective", requirement: "Complete the fixture." }] } }) }] } });
|
||||
await response(3);
|
||||
await expect.poll(() => messages.find(message => message.method === "item/tool/call"), { timeout: 5_000 }).toBeDefined();
|
||||
const call = messages.find(message => message.method === "item/tool/call")!;
|
||||
expect(call.params!.tool).toBe("paperclip_finish");
|
||||
const toolFrames = messages.filter(message => (message.params?.item as { id?: string } | undefined)?.id === "part-invalid");
|
||||
expect(toolFrames.map(message => message.method)).toEqual(["item/started", "item/updated", "item/completed"]);
|
||||
expect(toolFrames.at(-1)?.params).toMatchObject({
|
||||
threadId: call.params!.threadId, turnId: call.params!.turnId,
|
||||
item: { id: "part-invalid", type: "builtinToolCall", tool: "invalid", status: "failed", output: "Tool not found: fixture_missing" },
|
||||
});
|
||||
const feedback = "Accepted. Include [Saved document](/PAP/issues/PAP-1#document-plan).";
|
||||
// The interrupt is ahead of the response on stdin. Commands stay serial,
|
||||
// but their awaited response must not queue behind the command itself.
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { expect, it } from "vitest";
|
||||
import { composeNativeSystemInstructions, type NativeRuntimeContextSnapshot } from "./runtime-context.js";
|
||||
|
||||
it("keeps the TypeScript instruction composer and Rust attachment fixture in sync", () => {
|
||||
const fixtures = JSON.parse(readFileSync(new URL("../../test/fixtures/registered-asset-instructions.json", import.meta.url), "utf8")) as Array<{context: NativeRuntimeContextSnapshot; entry: string; instructions: string}>;
|
||||
for (const fixture of fixtures) expect(composeNativeSystemInstructions(fixture.context, fixture.entry)).toBe(fixture.instructions);
|
||||
});
|
||||
@@ -619,6 +619,15 @@ const server = createServer(async (request, response) => {
|
||||
},
|
||||
},
|
||||
});
|
||||
if (String(parsedPrompt.message ?? parsedPrompt.task?.prompt ?? "").includes("invalid-tool-feedback")) {
|
||||
for (const [status, state] of [
|
||||
["pending", {}], ["running", { title: "Checking tool name" }],
|
||||
["error", { error: "Tool not found: fixture_missing" }],
|
||||
]) emit({ type: "message.part.updated", id: `event-invalid-${status}`, properties: {
|
||||
sessionID: session.id, part: { id: "part-invalid", messageID: "message-assistant",
|
||||
type: "tool", tool: "invalid", callID: "call-invalid", state: { status, ...state } },
|
||||
} });
|
||||
}
|
||||
emit({
|
||||
type: "message.part.updated",
|
||||
id: "event-patch",
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
[
|
||||
{
|
||||
"context": {
|
||||
"prompt": {
|
||||
"text": "Pinned prompt."
|
||||
},
|
||||
"connectionInstructions": {
|
||||
"text": "Pinned connection policy."
|
||||
},
|
||||
"instructions": {
|
||||
"bundle": {
|
||||
"rootPath": "/registered/bundle"
|
||||
},
|
||||
"workingCopy": {
|
||||
"kind": "agent_files",
|
||||
"rootPath": "/registered/run-copy",
|
||||
"entryPath": "AGENTS.md"
|
||||
}
|
||||
}
|
||||
},
|
||||
"entry": "Custom entry quoting /registered/run-copy stays unchanged.",
|
||||
"instructions": "Pinned prompt.\n\nCustom entry quoting /registered/run-copy stays unchanged.\n\nPinned connection policy.\n\nYour persistent agent directory (AGENT_HOME) is /registered/run-copy. Your instruction entry is AGENTS.md, relative to that directory. All supported files and subfolders there are restored across tasks and sessions, and collected after this provider stops. Write task deliverables in the task working directory. Only changed or deleted files synchronize; the last sync wins for the same file. Temporary copies are cleaned up without retaining file history. Check the save receipt before claiming persistence.\n\nRead-only instruction sibling root: /registered/bundle"
|
||||
},
|
||||
{
|
||||
"context": {
|
||||
"prompt": {
|
||||
"text": "Pinned prompt."
|
||||
},
|
||||
"connectionInstructions": {
|
||||
"text": "Pinned connection policy."
|
||||
},
|
||||
"instructions": {
|
||||
"bundle": {
|
||||
"rootPath": "/registered/bundle"
|
||||
},
|
||||
"workingCopy": {
|
||||
"kind": "instruction_file",
|
||||
"rootPath": "/registered/run-copy",
|
||||
"entryPath": "AGENTS.md"
|
||||
}
|
||||
}
|
||||
},
|
||||
"entry": "Custom entry quoting /registered/run-copy stays unchanged.",
|
||||
"instructions": "Pinned prompt.\n\nCustom entry quoting /registered/run-copy stays unchanged.\n\nPinned connection policy.\n\nYour editable agent instruction file is /registered/run-copy/AGENTS.md. Edit this registered private copy normally. After this run stops, Paperclip saves changed content as a persistent revision if your responsible user still has permission and the baseline has not changed. Check the run's instruction-save receipt before claiming persistence. Conflicts are preserved for explicit resolution. Repository instruction files, skills, and this run's loaded prompt are separate and are not collected.\n\nRead-only instruction sibling root: /registered/bundle"
|
||||
},
|
||||
{
|
||||
"context": {
|
||||
"prompt": {
|
||||
"text": "Pinned prompt."
|
||||
},
|
||||
"connectionInstructions": {
|
||||
"text": "Pinned connection policy."
|
||||
},
|
||||
"instructions": {
|
||||
"bundle": {
|
||||
"rootPath": "/registered/bundle"
|
||||
},
|
||||
"workingCopy": null
|
||||
}
|
||||
},
|
||||
"entry": "Custom entry quoting /registered/run-copy stays unchanged.",
|
||||
"instructions": "Pinned prompt.\n\nCustom entry quoting /registered/run-copy stays unchanged.\n\nPinned connection policy.\n\nRead-only instruction sibling root: /registered/bundle"
|
||||
}
|
||||
]
|
||||
@@ -15,6 +15,8 @@ function issue(input: Partial<Issue> & Pick<Issue, "id" | "companyId" | "title">
|
||||
projectWorkspaceId: null,
|
||||
goalId: null,
|
||||
parentId: null,
|
||||
visibility: "open",
|
||||
privacyRootIssueId: null,
|
||||
title,
|
||||
description: null,
|
||||
status: "todo",
|
||||
|
||||
@@ -566,6 +566,8 @@ function paperclipIssue(overrides: Partial<Issue> = {}): Issue {
|
||||
projectWorkspaceId: null,
|
||||
goalId: null,
|
||||
parentId: null,
|
||||
visibility: "open",
|
||||
privacyRootIssueId: null,
|
||||
title: "Design event ingestion controls",
|
||||
description: "Decide which Paperclip issues, comments, and documents can be ingested into the wiki.",
|
||||
status: "todo",
|
||||
|
||||
@@ -1634,6 +1634,8 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness {
|
||||
projectWorkspaceId: null,
|
||||
goalId: input.goalId ?? null,
|
||||
parentId: input.parentId ?? null,
|
||||
visibility: "open",
|
||||
privacyRootIssueId: null,
|
||||
title: input.title,
|
||||
description: input.description ?? null,
|
||||
status: input.status ?? "todo",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type {
|
||||
AskUserQuestionsQuestion,
|
||||
PaperclipQuestionSetPayload,
|
||||
ConnectionSearchResultItem,
|
||||
} from "./types/index.js";
|
||||
import {
|
||||
@@ -338,6 +339,20 @@ export function aggregatorProviderQuestion(
|
||||
};
|
||||
}
|
||||
|
||||
/** Native question form, preserving the exact saved-answer authorization contract. */
|
||||
export function aggregatorProviderQuestionSet(question: AskUserQuestionsQuestion): PaperclipQuestionSetPayload {
|
||||
return {
|
||||
schema: "paperclip.question_set.v1",
|
||||
questions: [{
|
||||
id: question.id,
|
||||
prompt: question.prompt,
|
||||
required: true,
|
||||
answerMode: "single_select",
|
||||
options: question.options.map(({ id, label, description }) => ({ id, label, ...(description != null ? { description } : {}) })),
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
export function aggregatorContinuationInstruction(
|
||||
provider: RemoteMcpConnectorId,
|
||||
targetName: string,
|
||||
|
||||
@@ -964,6 +964,8 @@ export type {
|
||||
SetupTokenTransportAdvisoryCode,
|
||||
AssetImage,
|
||||
Project,
|
||||
ProjectAccessMember,
|
||||
ProjectAccessSubjectType,
|
||||
ProjectDiscoverySummary,
|
||||
ProjectDiscoveryPage,
|
||||
ProjectBudgetSummary,
|
||||
@@ -973,6 +975,7 @@ export type {
|
||||
ProjectCodebaseOrigin,
|
||||
ProjectGoalRef,
|
||||
ProjectManagedByPlugin,
|
||||
ProjectVisibility,
|
||||
ProjectWorkspace,
|
||||
CompanySearchCountType,
|
||||
CompanySearchExtractIssueResult,
|
||||
@@ -1101,6 +1104,12 @@ export type {
|
||||
ExternalObjectSummaryItem,
|
||||
CompactIssue,
|
||||
Issue,
|
||||
IssueVisibility,
|
||||
IssueAccessGrant,
|
||||
IssueAccessGrantAgentVisibility,
|
||||
IssueAccessGrantSubjectType,
|
||||
IssueAccessGrantSource,
|
||||
IssueLockedStub,
|
||||
IssueChangeReceiptEntry,
|
||||
IssueChanges,
|
||||
IssueAssigneeAdapterOverrides,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ConnectionIntentInteraction } from "./issue.js";
|
||||
import type { ToolConnection } from "./tool-access.js";
|
||||
import type { AskUserQuestionsQuestion } from "./issue.js";
|
||||
import type { AskUserQuestionsQuestion, PaperclipQuestionSetPayload } from "./issue.js";
|
||||
import type { RemoteMcpConnectorId } from "../remote-mcp-connectors.js";
|
||||
|
||||
export type ConnectionAvailabilityState =
|
||||
@@ -44,6 +44,8 @@ export interface ConnectionsSearchResult {
|
||||
/** Paperclip-authored next step; provider content must never supply this field. */
|
||||
instruction?: string;
|
||||
providerQuestion?: AskUserQuestionsQuestion;
|
||||
/** Canonical native form of the same provider choice; IDs and disclosure are identical. */
|
||||
providerQuestionSet?: PaperclipQuestionSetPayload;
|
||||
selectionInteractionId?: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -158,6 +158,8 @@ export interface HeartbeatRun {
|
||||
id: string;
|
||||
companyId: string;
|
||||
agentId: string;
|
||||
scopeKind: "company" | "issue";
|
||||
issueId: string | null;
|
||||
invocationSource: HeartbeatInvocationSource;
|
||||
triggerDetail: WakeupTriggerDetail | null;
|
||||
status: HeartbeatRunStatus;
|
||||
@@ -222,6 +224,10 @@ export interface HeartbeatRun {
|
||||
contextSnapshot: Record<string, unknown> | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
/** Metadata-only company-list row for a run bound to an unreadable private issue. */
|
||||
redacted?: boolean;
|
||||
durationMs?: number | null;
|
||||
costUsd?: number | null;
|
||||
outputSilence?: HeartbeatRunOutputSilence;
|
||||
/**
|
||||
* Ephemeral, process-local current status message for an active run. Resolved
|
||||
|
||||
@@ -352,7 +352,22 @@ export type {
|
||||
DocumentTextRange,
|
||||
UpdateDocumentAnnotationThreadRequest,
|
||||
} from "./document-annotation.js";
|
||||
export type { Project, ProjectDiscoverySummary, ProjectDiscoveryPage, ProjectRepository, ProjectRepositoryOptions, ProjectBudgetSummary, ProjectCodebase, ProjectCodebaseOrigin, ProjectGoalRef, ProjectManagedByPlugin, ProjectWorkspace } from "./project.js";
|
||||
export type {
|
||||
Project,
|
||||
ProjectRepository,
|
||||
ProjectRepositoryOptions,
|
||||
ProjectAccessMember,
|
||||
ProjectAccessSubjectType,
|
||||
ProjectDiscoverySummary,
|
||||
ProjectDiscoveryPage,
|
||||
ProjectBudgetSummary,
|
||||
ProjectCodebase,
|
||||
ProjectCodebaseOrigin,
|
||||
ProjectGoalRef,
|
||||
ProjectManagedByPlugin,
|
||||
ProjectVisibility,
|
||||
ProjectWorkspace,
|
||||
} from "./project.js";
|
||||
export type {
|
||||
CompanySearchCountType,
|
||||
CompanySearchExtractIssueResult,
|
||||
@@ -664,6 +679,12 @@ export type {
|
||||
IssueSubtreeDiagnosticNode,
|
||||
IssueSubtreeDiagnosticEdge,
|
||||
IssueSubtreeDiagnosticsResponse,
|
||||
IssueVisibility,
|
||||
IssueAccessGrant,
|
||||
IssueAccessGrantAgentVisibility,
|
||||
IssueAccessGrantSubjectType,
|
||||
IssueAccessGrantSource,
|
||||
IssueLockedStub,
|
||||
IssueBlockerAttention,
|
||||
IssueBlockerAttentionIssueSummary,
|
||||
IssueBlockerAttentionReason,
|
||||
|
||||
@@ -46,6 +46,41 @@ import type {
|
||||
|
||||
export type { IssueWorkMode };
|
||||
|
||||
export type IssueVisibility = "open" | "private";
|
||||
export type IssueAccessGrantSubjectType = "user" | "agent";
|
||||
export type IssueAccessGrantSource = "explicit" | "assignment" | "project" | "owner";
|
||||
export type IssueAccessGrantAgentVisibility = "discoverable" | "private";
|
||||
|
||||
export interface IssueAccessGrant {
|
||||
id: string;
|
||||
issueId: string;
|
||||
subjectType: IssueAccessGrantSubjectType;
|
||||
subjectId: string;
|
||||
source: IssueAccessGrantSource;
|
||||
/** Effective access inherited from a parent or private project; not revocable here. */
|
||||
inherited?: boolean;
|
||||
grantedByUserId: string | null;
|
||||
grantedByAgentId: string | null;
|
||||
createdAt: Date;
|
||||
revokedAt: Date | null;
|
||||
subjectDisplayName: string | null;
|
||||
subjectAvatarUrl: string | null;
|
||||
subjectInitials: string | null;
|
||||
agentVisibility: IssueAccessGrantAgentVisibility | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Existence-only projection used when a readable issue references an issue the
|
||||
* current principal cannot read. Edge projections may return this exact shape
|
||||
* in place of an IssueRelationIssueSummary; direct reads and list/search rows
|
||||
* never return locked stubs.
|
||||
*/
|
||||
export interface IssueLockedStub {
|
||||
id: string;
|
||||
identifier: string | null;
|
||||
locked: true;
|
||||
}
|
||||
|
||||
export interface IssueAncestorProject {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -792,6 +827,11 @@ export interface Issue {
|
||||
projectWorkspaceId: string | null;
|
||||
goalId: string | null;
|
||||
parentId: string | null;
|
||||
/** Present on current API responses; optional for compatibility with older plugin payloads. */
|
||||
visibility?: IssueVisibility;
|
||||
privacyRootIssueId?: string | null;
|
||||
/** Immediate task from which private access flows downward, including chat handoffs. */
|
||||
privacyParentIssueId?: string | null;
|
||||
ancestors?: IssueAncestor[];
|
||||
title: string;
|
||||
description: string | null;
|
||||
@@ -884,6 +924,8 @@ export type CompactIssue = Pick<
|
||||
| "projectWorkspaceId"
|
||||
| "goalId"
|
||||
| "parentId"
|
||||
| "visibility"
|
||||
| "privacyRootIssueId"
|
||||
| "title"
|
||||
| "description"
|
||||
| "status"
|
||||
|
||||
@@ -8,6 +8,19 @@ import type { AgentEnvConfig } from "./secrets.js";
|
||||
|
||||
export type ProjectWorkspaceSourceType = "local_path" | "git_repo" | "remote_managed" | "non_git_path";
|
||||
export type ProjectWorkspaceVisibility = "default" | "advanced";
|
||||
export type ProjectVisibility = "open" | "private";
|
||||
export type ProjectAccessSubjectType = "user" | "agent";
|
||||
|
||||
export interface ProjectAccessMember {
|
||||
id: string;
|
||||
companyId: string;
|
||||
projectId: string;
|
||||
subjectType: ProjectAccessSubjectType;
|
||||
subjectId: string;
|
||||
subjectDisplayName: string | null;
|
||||
subjectAvatarUrl: string | null;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export interface ProjectGoalRef {
|
||||
id: string;
|
||||
@@ -98,6 +111,12 @@ export interface Project {
|
||||
goals: ProjectGoalRef[];
|
||||
name: string;
|
||||
description: string | null;
|
||||
/** Omitted by older servers/fixtures; clients must treat omission as open. */
|
||||
visibility?: ProjectVisibility;
|
||||
/** Present only for the lazily-created per-user "My private tasks" project. */
|
||||
personalOwnerUserId?: string | null;
|
||||
/** Only this user and administrators may change the project audience. */
|
||||
privacyOwnerUserId?: string | null;
|
||||
status: ProjectStatus;
|
||||
leadAgentId: string | null;
|
||||
targetDate: string | null;
|
||||
|
||||
Reference in new issue
Block a user