mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-17 01:25:26 +02:00
## Thinking Path > - Paperclip manages AI agents and their work. > - Agent creation, approval, pause, and termination change whether an agent can work. > - These changes currently use separate service and database paths. > - Some agents need setup after their record exists and before their harness can run. > - This PR adds one module that owns those state changes and their transactions. > - The module records progress and retries incomplete work after a server restart. ## Linked Issues or Issue Description **Problem or motivation** A hire can become active before its execution environment is ready. Direct agent state writes also bypass one common lifecycle boundary. Termination does not have a durable step for resource cleanup. **Proposed solution** Use agent lifecycle commands for hiring, approval, pause, resume, and termination. Keep proposed hires pending until approval. Prepare each approved hire, test its saved harness configuration, and then permit work. Wait for required plugin work before completing a step. **Alternatives considered** A general database commit hook would expose transaction details to callers. A timer alone would delay each new hire. This module owns each command transaction and starts its worker after commit. A periodic scan recovers work after a process stops. **Roadmap alignment** This change adds the lifecycle boundary for the existing agent and plugin systems. It does not add a user interface or a provider implementation. It replaces the lifecycle delivery approach in #15391. Related proposals include #11475 and #13099; this change does not add their external executor protocols. ## What Changed - Add durable approval, preparation, verification, pause, resume, stop, and cleanup states. - Keep agent creation, lifecycle state, configuration writes, and agent record deletion behind `modules/agent-lifecycle`. Keep validation, credential rules, reads, onboarding, invitations, general approvals, and company data deletion in their services. - Commit a hire before the remaining onboarding or invitation work. Serialize requests with the existing dedicated database connection helper. Reuse the hire after a failed attempt. - Keep accepted work in the run queue during setup. Require execution and cleanup evidence before completing pause or termination. - Retain the original credential owner when approving migrated hires. - Start lifecycle work after each command commits. Use database leases and revision checks for retries and late results. - Add a generic required plugin method and capability. Store the required plugin IDs for each agent. Track host and plugin completion separately. - Keep harness verification and credential rules in services. Supply their results to lifecycle through explicit ports. Reject failed logins and incomplete probes. - Remove reverse imports from lifecycle adapters into services. Share record queries and validation below both layers. - Use one hire decision path for agent IDs and approval IDs. Resolve the approval and agent change in one transaction. Expose policy reconciliation on the command object. - Save configuration and verification invalidation through one module operation. Ordinary commands own their transaction. Restrict the shared transaction integration to its listed callers. Reject identity, company, accounting, timestamp, and unknown fields. - Require completed termination before deleting agent records. The company deletion service calls the module through a separate deletion interface. - Save an approved secret before applying its agent binding. A failed binding leaves the secret approved. A retry reuses it. - Remove old permission and metadata export files. Move hire configuration rules out of lifecycle persistence. - Report failed worker steps and scans with operation context and known error codes. Omit provider messages, stacks, and configuration values. Document ordinary application use and extension rules. - Recover expired native owners only after execution stops. Retry cleanup of failed retained leases. Wait for setup in the live smoke script. - Keep manual, budget, and company pause reasons separate. Guard execution status writes with the ready state. - Add a migration, boundary checks, regression tests, and a lifecycle guide. Keep the current UI. - Limit periodic policy checks to 100 eligible agents per minute. Continue from the last agent ID. Exclude pending hires and agents in termination or a final state. Keep explicit company and budget updates immediate. ## Verification - Latest head `ccc3c86b0` aligns the shared status update schema with the PATCH route. All 15 shared tests, 104 server route/OpenAPI tests, 2 CLI tests, and shared/server/CLI TypeScript checks pass. The Greptile comment is fixed. CI is running; no new Apex review was requested for this small fix. - Rebase `75708ac94` rebases onto master at `2eb5187e4`. The backup test uses the shared 90-second timeout from master; the older timeout commit was removed. The affected backup test passes. - Agent budget edits now pass the target agent ID through enforcement. All 50 affected tests, server TypeScript, and 11 boundary tests pass. Both configuration update paths have regression coverage. CI is running on the latest head. No new Apex review was requested for these small fixes. - Rebase `9b568666a` preserves the run-control extraction and delivery-work startup changes from master. All 559 affected tests, server TypeScript, and 11 boundary tests pass. CI and Apex review are running on the final head. - The policy scan fix passes 56 lifecycle and diagnostic tests, 24 policy and caller tests, and 11 boundary tests. A regression test checks the page limit, interval, excluded states, and cursor wraparound. - Rebase `fd4698750` passes all 611 tests in eight affected lifecycle, route, and heartbeat suites. Server TypeScript and all 11 module boundary tests pass. The company deletion rollback and concurrent hire tests are included. - Follow-up `00aac7646` fixes the failed decision deletion test and the public update schema. All 126 affected server tests, 8 shared tests, 2 CLI tests, and 11 boundary tests pass. Shared, server, CLI, and UI TypeScript checks pass. - Server TypeScript passes: `pnpm --filter @paperclipai/server exec tsc --noEmit`. - All 11 boundary tests pass: `node --test scripts/check-module-boundaries.test.mjs`. The repository boundary scan also passes. - All 68 lifecycle, failure diagnostic, and harness verification tests pass. Tests reject forbidden fields through the root command, combined transition command, and restricted transaction integration. They also check invalid fields returned by configuration preparation. - Failure tests cover host work, plugin work, claims, renewals, deferrals, and scans. Log tests check known error codes and exclusion of private error contents. - All 355 tests in 10 existing caller suites pass. These tests cover secret approval, pairing, pending hires, credentials, company import, built-in agents, managed agents, instructions, and skills. - The branch is rebased onto `origin/master` at `2eb5187e4`. The queue guards and cancellation lock fix use the extracted heartbeat queue. Agent cancellation uses the extracted run-control file. The source diff scan found no secrets or private URLs. - Earlier checks cover approval retries, rollback, late verification results, policy holds, deletion rollback, concurrent company deletion, and queue admission during setup. - Before the rebase, CI passed on `00aac7646` and Greptile Apex rated it 5/5 with no open comments. CI and a new Apex review are pending for the rebased commit. The branch has no merge conflicts. - The full local build and native Dot suite were not run. The host has no Cargo. No live provider test was run. ## Risks - Background policy recovery takes more than one minute when more than 100 agents are eligible. Explicit company and budget updates still reconcile immediately. - The restricted configuration integration keeps an agent reference and its dependent records in one transaction. It cannot change a budget or invoke a lifecycle transition. A periodic scan starts pending setup after that transaction commits. - Secret approval and binding use separate transactions. A failed binding can leave an approved secret with no agent binding. - New approved hires remain unavailable until setup and verification complete. Existing clients see `paused` during these steps. This PR does not change the UI. - Migration `0320_daily_onslaught.sql` maps existing statuses and pause reasons. It does not create external resources or claim that an existing harness passed verification. - Use a coordinated server update for this migration. Older server versions can write legacy status without the new lifecycle checks. - A failed onboarding or invitation request can leave a committed hire. A retry reuses that hire and completes the remaining records. - Deletion requires completed termination. Company deletion can require another request while cleanup is pending. - Required plugins must make repeated calls safe and reject older revisions. A disabled or removed required plugin blocks completion until it is restored. - A new hire can run a second harness test after the existing UI test. Some adapters can charge for this test. - No live provider test was run. Provider implementation and resource backfill remain separate work. ## Model Used OpenAI GPT-6 through Codex, with reasoning, code tools, and local test execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have described the issue in this PR with the feature request field labels - [x] I have not referenced internal or instance-local issues or links - [x] My branch name describes the change - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation - [x] I have considered and documented risks - [x] Targeted local tests pass - [x] All Paperclip CI gates are green on the new commit - [x] Greptile Apex is 5/5 with no open comments on the new commit - [x] I will address review comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
265 lines
18 KiB
TypeScript
265 lines
18 KiB
TypeScript
import { spawn } from "node:child_process";
|
|
import { createHash, randomUUID } from "node:crypto";
|
|
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { and, eq, sql } from "drizzle-orm";
|
|
import express from "express";
|
|
import request from "supertest";
|
|
import { activityLog, agentApiKeys, agentCommentary, agents, authUsers, companyMemberships, heartbeatRuns, issues, nativeRunResults } from "@paperclipai/db";
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import { createLocalAgentJwt } from "../agent-auth-jwt.js";
|
|
import { submitAgentCommentary } from "../services/agent-commentary.js";
|
|
import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js";
|
|
import { isSecretSensitiveHttpRequest } from "../middleware/http-log-policy.js";
|
|
import { startRunnerApiTestServer } from "./helpers/runner-api-server.js";
|
|
import { ensureNativeCompletionContract } from "../services/native-runtime/completion-contracts.js";
|
|
import { agentCommentaryRoutes } from "../routes/agent-commentary.js";
|
|
import { errorHandler } from "../middleware/error-handler.js";
|
|
import { agentService } from "../services/agents.js";
|
|
import { companyService } from "../services/companies.js";
|
|
|
|
describe("internal agent commentary through both transports", () => {
|
|
let server: Awaited<ReturnType<typeof startRunnerApiTestServer>>;
|
|
let home: string;
|
|
const oldHome = process.env.PAPERCLIP_HOME;
|
|
const oldSecret = process.env.PAPERCLIP_AGENT_JWT_SECRET;
|
|
beforeAll(async () => {
|
|
home = await mkdtemp(join(tmpdir(), "paperclip-commentary-"));
|
|
process.env.PAPERCLIP_HOME = home;
|
|
process.env.PAPERCLIP_AGENT_JWT_SECRET = randomUUID();
|
|
server = await startRunnerApiTestServer();
|
|
}, 90_000);
|
|
afterAll(async () => {
|
|
await server?.close();
|
|
if (oldHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = oldHome;
|
|
if (oldSecret === undefined) delete process.env.PAPERCLIP_AGENT_JWT_SECRET; else process.env.PAPERCLIP_AGENT_JWT_SECRET = oldSecret;
|
|
if (home) await rm(home, { recursive: true, force: true });
|
|
});
|
|
type Fixture = Awaited<ReturnType<typeof server.fixture>>;
|
|
const input = { body: "The tool returned success before the write finished. Please wait for persistence.", idempotencyKey: "one" };
|
|
const rows = (f: Fixture) => server.db.select().from(agentCommentary).where(eq(agentCommentary.runId, f.runId));
|
|
async function legacy() {
|
|
const f = await server.fixture();
|
|
await server.db.update(heartbeatRuns).set({ runtimeMode: "legacy", nativeIssueId: null }).where(eq(heartbeatRuns.id, f.runId));
|
|
await server.db.update(agents).set({ adapterType: "codex_local" }).where(eq(agents.id, f.agentId));
|
|
return { ...f, token: createLocalAgentJwt(f.agentId, f.companyId, "codex_local", f.runId)! };
|
|
}
|
|
async function post(f: Fixture & { token: string }, value: unknown, companyId = f.companyId) {
|
|
return fetch(`${server.apiUrl}/api/companies/${companyId}/agent-commentary`, {
|
|
method: "POST", headers: { authorization: `Bearer ${f.token}`, "X-Paperclip-Run-Id": f.runId, "Content-Type": "application/json" }, body: JSON.stringify(value),
|
|
});
|
|
}
|
|
|
|
it("can reapply the generated migration without losing data", async () => {
|
|
const f = await legacy();
|
|
await post(f, { ...input, kind: "complaint" });
|
|
const migration = await readFile(new URL("../../../packages/db/src/migrations/0310_agent_commentary.sql", import.meta.url), "utf8");
|
|
for (const statement of migration.split("--> statement-breakpoint")) {
|
|
if (statement.trim()) await server.db.execute(sql.raw(statement));
|
|
}
|
|
expect(await rows(f)).toHaveLength(1);
|
|
});
|
|
|
|
it.each(["standard", "ask", "planning"] as const)("exposes native feedback in %s and persists only feedback plus a content-free audit", async (mode) => {
|
|
const f = await server.fixture({ mode });
|
|
const authority = new PaperclipRunnerToolAuthority(server.db, { ...f, workMode: mode });
|
|
expect(authority.definitions().map(t => t.name)).toEqual(expect.arrayContaining(["submit_complaint", "submit_suggestion"]));
|
|
const before = await f.snapshot();
|
|
for (const tool of ["submit_complaint", "submit_suggestion"]) {
|
|
const result = await authority.execute({ tool, callId: tool, arguments: { ...input, idempotencyKey: tool } });
|
|
expect(result).toMatchObject({ kind: tool === "submit_complaint" ? "complaint" : "suggestion", replayed: false });
|
|
expect(JSON.stringify(result)).not.toContain(input.body);
|
|
}
|
|
expect(await rows(f)).toEqual(expect.arrayContaining([
|
|
expect.objectContaining({ companyId: f.companyId, agentId: f.agentId, issueId: f.issueId, body: input.body, kind: "complaint" }),
|
|
expect.objectContaining({ kind: "suggestion" }),
|
|
]));
|
|
const after = await f.snapshot();
|
|
expect(after.issues).toEqual(before.issues);
|
|
expect(after.comments).toEqual(before.comments);
|
|
const [run] = await server.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
|
|
expect(run.resultJson).toBeNull();
|
|
const audit = await server.db.select().from(activityLog).where(and(eq(activityLog.runId, f.runId), eq(activityLog.action, "agent.commentary_submitted")));
|
|
expect(audit).toHaveLength(2);
|
|
expect(audit.every(a => Object.keys(a.details ?? {}).join() === "kind")).toBe(true);
|
|
});
|
|
|
|
it("deduplicates concurrent replay, rejects changed content, and imposes no suggestion quota", async () => {
|
|
const f = await server.fixture();
|
|
const submit = (args = input) => f.authority.execute({ tool: "submit_suggestion", callId: randomUUID(), arguments: args });
|
|
const results = await Promise.all([submit(), submit(), submit()]) as Array<{ id: string; replayed: boolean }>;
|
|
expect(new Set(results.map(r => r.id)).size).toBe(1);
|
|
expect(results.filter(r => !r.replayed)).toHaveLength(1);
|
|
await expect(submit({ ...input, body: "different" })).rejects.toThrow(/different content/);
|
|
for (let i = 0; i < 4; i++) await submit({ ...input, idempotencyKey: `new-${i}` });
|
|
expect(await rows(f)).toHaveLength(5);
|
|
expect(await server.db.select().from(activityLog).where(and(eq(activityLog.runId, f.runId), eq(activityLog.action, "agent.commentary_submitted")))).toHaveLength(5);
|
|
});
|
|
|
|
it("accepts document-sized text without truncation and redacts credential syntax", async () => {
|
|
const f = await legacy();
|
|
const body = "🙂".repeat(262_144);
|
|
expect((await post(f, { ...input, kind: "suggestion", body })).status).toBe(201);
|
|
expect((await rows(f))[0].body).toBe(body);
|
|
expect((await post(f, { ...input, kind: "suggestion", body: body + "!" })).status).toBe(400);
|
|
const secretBody = "It printed Authorization: Bearer sk-test-very-sensitive-credential before failing.";
|
|
expect((await post(f, { ...input, kind: "complaint", body: secretBody, idempotencyKey: "secret" })).status).toBe(201);
|
|
expect((await rows(f)).find(r => r.idempotencyKey === "secret")?.body).not.toContain("sk-test-very-sensitive-credential");
|
|
});
|
|
|
|
it("rejects spoofed input, cross-company HTTP access, board access, and missing authentication", async () => {
|
|
const f = await legacy();
|
|
for (const spoof of [{ agentId: f.agentId }, { issueId: f.issueId }, { runId: f.runId }, { companyId: f.companyId }, { body: " \n" }]) {
|
|
expect((await post(f, { ...input, kind: "complaint", ...spoof })).status).toBe(400);
|
|
}
|
|
expect((await post(f, { ...input, kind: "complaint" }, f.foreignCompanyId)).status).toBe(403);
|
|
expect((await fetch(`${server.apiUrl}/api/companies/${f.companyId}/agent-commentary`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...input, kind: "complaint" }) })).status).toBe(401);
|
|
const boardApp = express();
|
|
boardApp.use(express.json(), (req, _res, next) => { req.actor = { type: "board", source: "local_implicit", userId: "operator" }; next(); });
|
|
boardApp.use("/api", agentCommentaryRoutes(server.db));
|
|
boardApp.use(errorHandler);
|
|
expect((await request(boardApp).post(`/api/companies/${f.companyId}/agent-commentary`).send({ ...input, kind: "complaint" })).status).toBe(403);
|
|
await expect(submitAgentCommentary(server.db, { ...f, companyId: f.foreignCompanyId }, { ...input, kind: "complaint" })).rejects.toThrow(/authenticated/);
|
|
expect(await rows(f)).toHaveLength(0);
|
|
});
|
|
|
|
it.each(["cancelled", "succeeded", "failed"])("rejects submissions and replay after the run is %s", async (status) => {
|
|
const f = await legacy();
|
|
expect((await post(f, { ...input, kind: "complaint" })).status).toBe(201);
|
|
await server.db.update(heartbeatRuns).set({ status }).where(eq(heartbeatRuns.id, f.runId));
|
|
expect((await post(f, { ...input, kind: "complaint" })).status).toBe(403);
|
|
expect(await rows(f)).toHaveLength(1);
|
|
});
|
|
|
|
it("rejects native spoofing and paused agents without changing task state", async () => {
|
|
const f = await server.fixture();
|
|
await expect(f.authority.execute({ tool: "submit_complaint", callId: "spoof", arguments: { ...input, kind: "suggestion" } })).rejects.toThrow(/accepts only/);
|
|
await server.db.update(agents).set({ status: "paused" }).where(eq(agents.id, f.agentId));
|
|
await expect(f.authority.execute({ tool: "submit_complaint", callId: "paused", arguments: input })).rejects.toThrow(/not_authorized/);
|
|
expect(await rows(f)).toHaveLength(0);
|
|
});
|
|
|
|
it.each(["jwt", "api_key"])("rejects new feedback and replay with %s after Stop revokes a still-running legacy run", async (credential) => {
|
|
const f = await legacy();
|
|
if (credential === "api_key") {
|
|
f.token = `pcp_${randomUUID()}`;
|
|
const responsibleUserId = randomUUID();
|
|
await server.db.insert(authUsers).values({ id: responsibleUserId, name: "Feedback key owner", email: `${responsibleUserId}@fixture.invalid`, emailVerified: true, createdAt: new Date(), updatedAt: new Date() });
|
|
await server.db.insert(companyMemberships).values({ companyId: f.companyId, principalType: "user", principalId: responsibleUserId, status: "active", membershipRole: "member" });
|
|
await server.db.insert(agentApiKeys).values({ companyId: f.companyId, agentId: f.agentId, responsibleUserId, name: "feedback", keyHash: createHash("sha256").update(f.token).digest("hex") });
|
|
}
|
|
expect((await post(f, { ...input, kind: "complaint" })).status).toBe(201);
|
|
await server.db.update(heartbeatRuns).set({ resultJson: { executionCancellation: { state: "requested" } } }).where(eq(heartbeatRuns.id, f.runId));
|
|
for (const idempotencyKey of [input.idempotencyKey, "after-stop"]) {
|
|
const body = { ...input, kind: "complaint", idempotencyKey };
|
|
expect((await post(f, body)).status).toBe(403);
|
|
// The persistence boundary must also reject a request whose middleware
|
|
// authenticated before Stop committed the revocation.
|
|
await expect(submitAgentCommentary(server.db, f, body)).rejects.toThrow(/no longer authorized/);
|
|
}
|
|
expect(await rows(f)).toHaveLength(1);
|
|
expect(await server.db.select().from(activityLog).where(and(eq(activityLog.runId, f.runId), eq(activityLog.action, "agent.commentary_submitted")))).toHaveLength(1);
|
|
});
|
|
|
|
it("rejects revoked legacy credentials, replaced run ownership, and specialized review tools", async () => {
|
|
const f = await legacy();
|
|
const token = `pcp_${randomUUID()}`;
|
|
await server.db.insert(agentApiKeys).values({ companyId: f.companyId, agentId: f.agentId, name: "revoked", keyHash: createHash("sha256").update(token).digest("hex"), revokedAt: new Date() });
|
|
expect((await post({ ...f, token }, { ...input, kind: "complaint" })).status).toBe(401);
|
|
const native = await server.fixture();
|
|
const replacementId = randomUUID();
|
|
await server.db.insert(heartbeatRuns).values({ id: replacementId, companyId: native.companyId, agentId: native.agentId, status: "running", invocationSource: "on_demand" });
|
|
await server.db.update(issues).set({ executionRunId: replacementId }).where(eq(issues.id, native.issueId));
|
|
await expect(native.authority.execute({ tool: "submit_suggestion", callId: "stale", arguments: input })).rejects.toThrow();
|
|
const reviewer = new PaperclipRunnerToolAuthority(server.db, { ...native, nativeReview: { nativeReviewInteractionId: randomUUID(), nativeReviewDecisionId: randomUUID() } });
|
|
expect(reviewer.definitions().map(t => t.name)).not.toContain("submit_complaint");
|
|
expect(reviewer.definitions().map(t => t.name)).not.toContain("submit_suggestion");
|
|
await expect(reviewer.execute({ tool: "submit_complaint", callId: "review", arguments: input })).rejects.toThrow();
|
|
expect(await rows(f)).toHaveLength(0);
|
|
expect(await rows(native)).toHaveLength(0);
|
|
});
|
|
|
|
it("rejects native feedback after an accepted finish even while the provider is still running", async () => {
|
|
const f = await server.fixture();
|
|
const { row: contract } = await ensureNativeCompletionContract({ db: server.db, companyId: f.companyId, issue: { id: f.issueId, title: "Test", description: null }, actorId: "test" });
|
|
await server.db.update(heartbeatRuns).set({ completionContractId: contract.id }).where(eq(heartbeatRuns.id, f.runId));
|
|
await server.db.insert(nativeRunResults).values({
|
|
companyId: f.companyId, issueId: f.issueId, runId: f.runId, completionContractId: contract.id,
|
|
serverFingerprint: randomUUID(), schemaStatus: "accepted", resultJson: {}, canonicalSha256: "test",
|
|
});
|
|
await expect(f.authority.execute({ tool: "submit_complaint", callId: "late", arguments: input })).rejects.toThrow(/before finishing/);
|
|
expect(await rows(f)).toHaveLength(0);
|
|
});
|
|
|
|
it("retains feedback after task deletion and removes it with the run", async () => {
|
|
const f = await legacy();
|
|
await post(f, { ...input, kind: "complaint" });
|
|
await server.db.delete(issues).where(eq(issues.id, f.issueId));
|
|
expect((await rows(f))[0].issueId).toBeNull();
|
|
await server.db.delete(activityLog).where(eq(activityLog.runId, f.runId));
|
|
await server.db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
|
|
expect(await rows(f)).toHaveLength(0);
|
|
});
|
|
|
|
it.each(["agent", "company"])("uses existing %s deletion handling", async (owner) => {
|
|
const f = await legacy();
|
|
// A taskless run also verifies optional issue attribution, without unrelated
|
|
// fixture approval records that deliberately prevent deleting their author.
|
|
const agentId = randomUUID(), runId = randomUUID();
|
|
await server.db.insert(agents).values({ id: agentId, companyId: f.companyId, name: "Feedback author", adapterType: "codex_local", status: "active" });
|
|
await server.db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId, status: "running", invocationSource: "on_demand" });
|
|
await submitAgentCommentary(server.db, { companyId: f.companyId, agentId, runId }, { ...input, kind: "complaint" });
|
|
expect((await rows({ ...f, runId }))[0].issueId).toBeNull();
|
|
if (owner === "agent") {
|
|
await server.db.update(agents).set({ lifecycleState: "terminated", status: "terminated" }).where(eq(agents.id, agentId));
|
|
await agentService(server.db).remove(agentId);
|
|
}
|
|
else await companyService(server.db).remove(f.companyId);
|
|
expect(await rows({ ...f, runId })).toHaveLength(0);
|
|
});
|
|
|
|
it("rolls back feedback when its audit insert fails and sanitizes the database error", async () => {
|
|
const f = await legacy();
|
|
await server.db.execute(sql.raw(`CREATE FUNCTION fail_commentary_audit() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.action = 'agent.commentary_submitted' THEN RAISE EXCEPTION 'private database canary'; END IF; RETURN NEW; END $$`));
|
|
await server.db.execute(sql.raw(`CREATE TRIGGER fail_commentary_audit BEFORE INSERT ON activity_log FOR EACH ROW EXECUTE FUNCTION fail_commentary_audit()`));
|
|
try {
|
|
const response = await post(f, { ...input, kind: "complaint" });
|
|
expect(response.status).toBe(503);
|
|
expect(await response.text()).not.toMatch(/private database canary|The tool returned/);
|
|
expect(await rows(f)).toHaveLength(0);
|
|
const [run] = await server.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
|
|
expect(run.status).toBe("running");
|
|
} finally {
|
|
await server.db.execute(sql.raw("DROP TRIGGER fail_commentary_audit ON activity_log"));
|
|
await server.db.execute(sql.raw("DROP FUNCTION fail_commentary_audit()"));
|
|
}
|
|
});
|
|
|
|
it("runs the legacy stdin helper and handles failure silently without exposing its body", async () => {
|
|
const f = await legacy();
|
|
const helper = fileURLToPath(new URL("../../../skills/paperclip/scripts/submit-agent-commentary.mjs", import.meta.url));
|
|
const body = "Quotes, `backticks`, $(printf should-not-run), and emoji 😭 stay text.\n";
|
|
async function run(apiUrl: string) {
|
|
return new Promise<{ code: number | null; out: string; err: string }>((resolve, reject) => {
|
|
const child = spawn(process.execPath, [helper, "complaint", "helper-one"], { env: { ...process.env, PAPERCLIP_API_URL: apiUrl, PAPERCLIP_API_KEY: f.token, PAPERCLIP_COMPANY_ID: f.companyId, PAPERCLIP_RUN_ID: f.runId }, stdio: "pipe" });
|
|
let out = "", err = "";
|
|
child.stdout.on("data", c => out += c); child.stderr.on("data", c => err += c);
|
|
child.on("error", reject); child.on("close", code => resolve({ code, out, err }));
|
|
child.stdin.end(body);
|
|
});
|
|
}
|
|
expect(await run(server.apiUrl)).toEqual({ code: 0, out: "Feedback stored.\n", err: "" });
|
|
expect(await run(server.apiUrl + "/api/")).toEqual({ code: 0, out: "Feedback stored.\n", err: "" });
|
|
expect(await rows(f)).toHaveLength(1);
|
|
expect((await rows(f))[0].body).toBe(body);
|
|
const failed = await run("http://127.0.0.1:1");
|
|
expect(failed).toMatchObject({ code: 0, out: "" });
|
|
expect(failed.err).toContain("continue the primary task");
|
|
expect(failed.err).not.toContain(f.token);
|
|
expect(failed.err).not.toContain(body);
|
|
expect(isSecretSensitiveHttpRequest("POST", `/api/companies/${f.companyId}/agent-commentary`)).toBe(true);
|
|
});
|
|
});
|