mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
feat: add internal agent complaints and suggestions (#15367)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents use legacy skills or native runner tools to work on tasks. > - Those agents can encounter friction that does not belong in the task thread. > - A complaint should preserve the raw reaction. A suggestion should describe an improvement. > - This pull request adds attributed local storage and both submission paths. > - Agents can submit feedback once and continue their primary work. ## Linked Issues or Issue Description **Subsystem affected** Server, database, shared contracts, runtime skills, and native runner tools. **Problem or motivation** Agents have no default internal channel for incidental complaints and suggestions. Sending this feedback through task comments adds noise and can alter task workflows. **Proposed solution** Store free-form feedback in the current instance database. Derive agent, run, company, and task attribution from active authority. Provide default legacy skills and provider-neutral native actions. Keep the instructions close to Warp's MIT-licensed originals. **Alternatives considered** Task comments and external Slack delivery add unwanted side effects. Mandatory suggestion fields and short editorial limits would discard useful feedback. This release has no listing API, UI, read tool, automatic triage, or external forwarding. **Roadmap alignment** This is a maintainer-requested addition to the existing runtime skills and runner tool paths. It does not duplicate a listed roadmap milestone. Searches for complaint tooling, suggestion-box, and agent commentary found no overlapping public PR or issue. ## What Changed - Add the company-scoped `agent_commentary` table, shared validation, and idempotent migration `0310`. - Add one transactional service and the agent-only POST route. Validate active authority before writes or replay. Redact known credentials. Commit a content-free audit with each new record. - Add `submit_complaint` and `submit_suggestion` to standard, ask, and planning modes. Keep review, revocation, and completion restrictions. Store replay identity on the commentary row. - Mount `complain` and `suggestion-box` by default for legacy agents. Bundle a dependency-free Node.js stdin helper in the operational skill and allow its POST through the sandbox bridge. - Preserve Warp's complaint voice and suggestion guidance, with attribution and local transport adaptations. Keep source attribution and MIT notices in each skill's LICENSE, outside runtime instructions. - Document custom-runtime HTTP use and database inspection. Add real-database tests and a repeatable live Codex smoke for local and Daytona execution. - Pin the lagging-source migration fixture before the identity-repair migration so later migrations preserve its regression coverage. ## Verification - Personally ran real Codex submissions in all four environments on 2026-10-06. Local runs passed at 20:35 UTC. Daytona native passed at 20:31 UTC; Daytona legacy passed at 20:33 UTC. Each stored exactly two rows with company, agent, run, and task attribution, wrote the continuation marker, exited zero, created no task comments, and left task status unchanged. Each recorded two content-free activity entries. - Daytona used production provider hooks, real remote execution and file transfer, the legacy queue callback bridge, and native private WebSocket ingress. The current Linux runner was built from `abf47b595`, staged, and verified against controller contracts. Both sandboxes were confirmed deleted. This is a focused feedback transport smoke; it does not claim full Runner E2E catalog or browser qualification. - The immutable base image and Linux binary digest are recorded in [the verification documentation](https://github.com/paperclipai/paperclip/blob/codex/agent-commentary/doc/agent-commentary.md#verification). The smoke script can save content-free JSON evidence. No credentials or feedback bodies are in these reports. | Environment | Runner | Complaint row | Suggestion row | | --- | --- | --- | --- | | local | legacy Codex | `59413a00-1de2-4bb1-bcc6-9c4b54c64aa6` | `3db2364d-3e15-4f47-846f-875d3902999d` | | local | native Codex | `5da22b5f-41df-4de5-8ba0-d9345ab01267` | `2d5abe17-dd41-403c-a5ee-4729f2d58921` | | daytona | legacy Codex | `27c9d0aa-8477-409f-9da0-e8ffa48dee50` | `209681c9-d1e9-4ce1-999e-48fa07692389` | | daytona | native Codex | `6eb001bb-4bcf-43f7-8717-f662f53dc7c3` | `77c383d8-a997-49e5-a33e-25c70e15c0b2` | - Run the local check with `node cli/node_modules/tsx/dist/cli.mjs server/scripts/verify-agent-commentary-live.ts`. The documentation gives the Daytona invocation. Both use disposable instance databases and normal Codex provider usage. - Repository `pnpm -r typecheck` and `pnpm build` passed after the test extension. The build includes runner generation, contracts, and replay checks. The smoke scripts also passed a separate TypeScript check. The lagging-source migration regression passed. All equivalent current-head Vitest CI shards passed. The local monolithic `pnpm test:run` invocation was stopped after CI supplied that coverage; it did not complete locally. - Focused tests cover company isolation, spoofing, revoked credentials, stale ownership, post-finish rejection, concurrent replay, conflicting keys, atomic rollback, and deletion through existing services. Boundary tests cover empty text, Unicode, text beyond 8,000 characters, and the 524,288-character ceiling without truncation. Mounting tests cover Codex, Claude, and sandbox staging. Helper tests cover standalone Node execution, stdin, invalid UTF-8, redirects, HTTP failure, and its deadline. Privacy and bridge tests cover successful and rejected requests. - Instructions were compared with Warp's originals. MIT notices and source credits live only in LICENSE files. Native tools preserve truthful disclosure when asked, without routine announcements. - [Full CI](https://github.com/paperclipai/paperclip/actions/runs/37508559190) and Greptile 5/5 passed on the earlier feature commit `5209c3501`. The later head found the migration-fixture assumption fixed in this update. On `8a4965164`, all 55 check contexts passed after one browser shard rerun. Its initial reviewer signoff failure also passed an isolated local browser run (1 test). Greptile scored that head 5/5 and identified one smoke cleanup gap. `6ecbafb0b` fixes failed-acquisition cleanup with four passing tests and a passing smoke-script typecheck. Fresh CI is pending for this final test-only fix. No commentary production code changed during verification. ## Risks - Feedback is internally attributed. It is not anonymous. Existing redaction removes known credentials, but agents must still omit sensitive content. Normal provider transcripts can include their submitted arguments. - Default skill availability changes for existing legacy agents. Runtime policy filtering still applies. The helper uses the existing Node.js runtime with no extra dependencies; custom runtimes can call the HTTP endpoint. - Feedback is removed with its run, agent, or company. Task deletion clears only the issue pointer. Normal database backups include the table. - The migration is additive and has no backfill. Writes serialize on the active run for replay consistency. No server suggestion quota is imposed. ## Model Used OpenAI `gpt-6-astra` through Codex, with `xhigh` reasoning effort and a reported 258,400-token context window. Capabilities used: repository inspection, code execution, and live runtime verification. No subagents were used. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
fe9d865250
commit
b508a05c43
65 files changed
+2115
-51
No files matched your search
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { PluginEnvironmentCreationCleanupError } from "@paperclipai/plugin-sdk";
|
||||
import { acquireDaytonaLeaseWithCleanup } from "../../scripts/agent-commentary-daytona.js";
|
||||
|
||||
const scope = { companyId: "company", environmentId: "environment", runId: "run" };
|
||||
const cleanup = { ...scope, providerLeaseId: "failed-create-attempt", observedProviderLeaseId: "sandbox",
|
||||
attemptId: "attempt", accountFingerprint: "a".repeat(64), labels: { "paperclip-run": "run" } };
|
||||
const failure = () => new PluginEnvironmentCreationCleanupError([new Error("setup timeout")], "cleanup pending", cleanup);
|
||||
|
||||
describe("feedback smoke Daytona acquisition cleanup", () => {
|
||||
it("destroys a created allocation and preserves the original setup failure", async () => {
|
||||
const error = failure();
|
||||
const destroy = vi.fn(async () => ({ providerLeaseId: cleanup.providerLeaseId, state: "destroyed" as const }));
|
||||
await expect(acquireDaytonaLeaseWithCleanup({ ...scope, acquire: async () => { throw error; }, destroy })).rejects.toBe(error);
|
||||
expect(destroy).toHaveBeenCalledExactlyOnceWith(cleanup);
|
||||
});
|
||||
|
||||
it("fails when the provider does not acknowledge deletion", async () => {
|
||||
await expect(acquireDaytonaLeaseWithCleanup({ ...scope, acquire: async () => { throw failure(); },
|
||||
destroy: async () => undefined })).rejects.toThrow("must be cleaned up");
|
||||
});
|
||||
|
||||
it("does not destroy an allocation from another company, environment, or run", async () => {
|
||||
for (const field of ["companyId", "environmentId", "runId"] as const) {
|
||||
const error = new PluginEnvironmentCreationCleanupError([], "foreign scope", { ...cleanup, [field]: "foreign" });
|
||||
const destroy = vi.fn();
|
||||
await expect(acquireDaytonaLeaseWithCleanup({ ...scope, acquire: async () => { throw error; }, destroy })).rejects.toBe(error);
|
||||
expect(destroy).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not fabricate cleanup for an ordinary acquisition error", async () => {
|
||||
const error = new Error("authentication rejected");
|
||||
const destroy = vi.fn();
|
||||
await expect(acquireDaytonaLeaseWithCleanup({ ...scope, acquire: async () => { throw error; }, destroy })).rejects.toBe(error);
|
||||
expect(destroy).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { copyFile, mkdtemp, rm } from "node:fs/promises";
|
||||
import { createServer, type Server, type ServerResponse } from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
const diagnostic = "Feedback could not be confirmed. Ignore this failure, do not retry, and continue the primary task.\n";
|
||||
|
||||
describe("standalone Node commentary helper", () => {
|
||||
let root: string;
|
||||
let helper: string;
|
||||
const servers: Server[] = [];
|
||||
const companyId = randomUUID();
|
||||
const runId = randomUUID();
|
||||
const token = "private-helper-test-token";
|
||||
|
||||
beforeAll(async () => {
|
||||
root = await mkdtemp(join(tmpdir(), "paperclip-node-feedback-"));
|
||||
helper = join(root, "submit-agent-commentary.mjs");
|
||||
// An installed skill must work outside the repository/package boundary.
|
||||
await copyFile(fileURLToPath(new URL("../../../skills/paperclip/scripts/submit-agent-commentary.mjs", import.meta.url)), helper);
|
||||
});
|
||||
afterAll(async () => { await rm(root, { recursive: true, force: true }); });
|
||||
afterEach(async () => {
|
||||
await Promise.all(servers.splice(0).map(server => new Promise<void>((resolve, reject) => {
|
||||
server.close(error => error ? reject(error) : resolve());
|
||||
server.closeAllConnections();
|
||||
})));
|
||||
});
|
||||
|
||||
async function endpoint(reply: (response: ServerResponse) => void = response => {
|
||||
response.writeHead(201, { "Content-Type": "application/json" });
|
||||
response.end(JSON.stringify({ id: randomUUID() }));
|
||||
}) {
|
||||
const requests: { url: string | undefined; method: string | undefined; authorization: string | undefined; runId: string | string[] | undefined; payload: Record<string, string> }[] = [];
|
||||
const server = createServer(async (request, response) => {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of request) chunks.push(chunk);
|
||||
requests.push({ url: request.url, method: request.method, authorization: request.headers.authorization, runId: request.headers["x-paperclip-run-id"], payload: JSON.parse(Buffer.concat(chunks).toString("utf8")) });
|
||||
reply(response);
|
||||
});
|
||||
servers.push(server);
|
||||
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Missing server port");
|
||||
return { url: `http://127.0.0.1:${address.port}`, requests };
|
||||
}
|
||||
|
||||
function run(apiUrl: string, body: string | Buffer, args = ["complaint"], env: NodeJS.ProcessEnv = {}) {
|
||||
return new Promise<{ code: number | null; out: string; err: string }>((resolve, reject) => {
|
||||
const child = spawn(process.execPath, [helper, ...args], {
|
||||
cwd: root,
|
||||
// No Python, shell, or other executable is available through PATH.
|
||||
env: { ...process.env, PATH: "", PAPERCLIP_API_URL: apiUrl, PAPERCLIP_API_KEY: token, PAPERCLIP_COMPANY_ID: companyId, PAPERCLIP_RUN_ID: runId, ...env },
|
||||
stdio: "pipe",
|
||||
});
|
||||
let out = "", err = "";
|
||||
child.stdout.on("data", chunk => { out += chunk; });
|
||||
child.stderr.on("data", chunk => { err += chunk; });
|
||||
child.on("error", reject);
|
||||
child.on("close", code => resolve({ code, out, err }));
|
||||
child.stdin.on("error", error => { if ((error as NodeJS.ErrnoException).code !== "EPIPE") reject(error); });
|
||||
child.stdin.end(body);
|
||||
});
|
||||
}
|
||||
|
||||
it.each(["complaint", "suggestion"])("submits %s from stdin at the Unicode document boundary without additional executables", async kind => {
|
||||
const target = await endpoint();
|
||||
const prefix = "\uFEFFQuotes, `backticks`, $(printf should-not-run), and emoji 😭 stay text.\n";
|
||||
const body = prefix + "😎".repeat(Math.floor((524288 - prefix.length) / 2)) + "x".repeat((524288 - prefix.length) % 2);
|
||||
const args = kind === "complaint" ? [kind, "stable-key"] : [kind];
|
||||
expect(await run(`${target.url}/api/`, body, args)).toEqual({ code: 0, out: "Feedback stored.\n", err: "" });
|
||||
expect(target.requests).toEqual([{
|
||||
url: `/api/companies/${companyId}/agent-commentary`, method: "POST", authorization: `Bearer ${token}`, runId,
|
||||
payload: { kind, body, idempotencyKey: kind === "complaint" ? "stable-key" : expect.stringMatching(/^[0-9a-f-]{36}$/) },
|
||||
}]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["empty input", ""],
|
||||
["whitespace", " \n\t"],
|
||||
["oversized Unicode", "😎".repeat(262144) + "x"],
|
||||
["oversized bytes", Buffer.alloc(4 * 524288 + 1, 120)],
|
||||
["malformed UTF-8", Buffer.from([0xc3, 0x28])],
|
||||
])("rejects %s without making a request", async (_name, body) => {
|
||||
const target = await endpoint();
|
||||
expect(await run(target.url, body)).toEqual({ code: 0, out: "", err: diagnostic });
|
||||
expect(target.requests).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["invalid kind", ["unknown"], {}],
|
||||
["missing credential", ["complaint"], { PAPERCLIP_API_KEY: "" }],
|
||||
["invalid run", ["complaint"], { PAPERCLIP_RUN_ID: "not-a-run" }],
|
||||
] as const)("rejects %s without making a request", async (_name, args, env) => {
|
||||
const target = await endpoint();
|
||||
expect(await run(target.url, "private body", [...args], env)).toEqual({ code: 0, out: "", err: diagnostic });
|
||||
expect(target.requests).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[503, "private error body"],
|
||||
[200, "invalid JSON"],
|
||||
[201, "{}"],
|
||||
[201, JSON.stringify({ id: "x".repeat(4096) })],
|
||||
])("sanitizes HTTP %s / invalid acknowledgements and never retries", async (status, body) => {
|
||||
const target = await endpoint(response => { response.writeHead(status); response.end(body); });
|
||||
expect(await run(target.url, "private body")).toEqual({ code: 0, out: "", err: diagnostic });
|
||||
expect(target.requests).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not follow redirects or forward credentials", async () => {
|
||||
const destination = await endpoint();
|
||||
const target = await endpoint(response => { response.writeHead(307, { Location: destination.url }); response.end(); });
|
||||
expect(await run(target.url, "private body")).toEqual({ code: 0, out: "", err: diagnostic });
|
||||
expect(target.requests).toHaveLength(1);
|
||||
expect(destination.requests).toEqual([]);
|
||||
});
|
||||
|
||||
it("bounds a stalled HTTP response and exits successfully without retrying", async () => {
|
||||
const target = await endpoint(() => {});
|
||||
expect(await run(target.url, "private body")).toEqual({ code: 0, out: "", err: diagnostic });
|
||||
expect(target.requests).toHaveLength(1);
|
||||
}, 20_000);
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { ensureCodexSkillsInjected, listCodexSkills } from "@paperclipai/adapter-codex-local/server";
|
||||
import { listClaudeSkills } from "@paperclipai/adapter-claude-local/server";
|
||||
import { readPaperclipRuntimeSkillEntries, resolveLegacyPaperclipDesiredSkillNames } from "@paperclipai/adapter-utils/server-utils";
|
||||
import { prepareClaudePromptBundle } from "../../../packages/adapters/claude-local/src/server/prompt-cache.js";
|
||||
import { stageCodexHomeForSync } from "../../../packages/adapters/codex-local/src/server/codex-home.js";
|
||||
|
||||
describe("default feedback skill delivery", () => {
|
||||
const cleanup: string[] = [];
|
||||
const keys = ["paperclip", "complain", "suggestion-box"].map(name => `paperclipai/paperclip/${name}`);
|
||||
afterEach(async () => {
|
||||
vi.unstubAllEnvs();
|
||||
await Promise.all(cleanup.splice(0).map(root => rm(root, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
it.each([undefined, []])("resolves defaults for Codex and Claude with selection %s", async (desiredSkills) => {
|
||||
const config = desiredSkills ? { paperclipSkillSync: { desiredSkills } } : {};
|
||||
for (const [adapterType, list] of [["codex_local", listCodexSkills], ["claude_local", listClaudeSkills]] as const) {
|
||||
const snapshot = await list({ agentId: "agent", companyId: "company", adapterType, config });
|
||||
expect(snapshot.desiredSkills).toEqual(expect.arrayContaining(keys));
|
||||
expect(snapshot.entries.filter(e => keys.includes(e.key)).every(e => e.state === "configured")).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("mounts both skills and their shared helper for Codex, Claude and the Codex sandbox home", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "paperclip-commentary-skills-"));
|
||||
cleanup.push(root);
|
||||
vi.stubEnv("PAPERCLIP_HOME", root);
|
||||
const entries = await readPaperclipRuntimeSkillEntries({}, import.meta.dirname, [fileURLToPath(new URL("../../../skills", import.meta.url))]);
|
||||
const desiredSkillNames = resolveLegacyPaperclipDesiredSkillNames({}, entries);
|
||||
const selected = entries.filter(e => desiredSkillNames.includes(e.key));
|
||||
const codexHome = join(root, "codex");
|
||||
await ensureCodexSkillsInjected(async () => {}, { skillsHome: join(codexHome, "skills"), skillsEntries: entries, desiredSkillNames });
|
||||
const claude = await prepareClaudePromptBundle({ companyId: "company", skills: selected, instructionsContents: null, onLog: async () => {} });
|
||||
const staged = await stageCodexHomeForSync(codexHome, { runId: "commentary-test" });
|
||||
cleanup.push(staged);
|
||||
for (const skills of [join(codexHome, "skills"), join(claude.addDir, ".claude", "skills"), join(staged, "skills")]) {
|
||||
for (const name of ["complain", "suggestion-box"]) {
|
||||
expect(await readFile(join(skills, name, "SKILL.md"), "utf8")).toContain("scripts/submit-agent-commentary.mjs");
|
||||
}
|
||||
expect(await readFile(join(skills, "paperclip", "scripts", "submit-agent-commentary.mjs"), "utf8")).toContain("process.stdin");
|
||||
}
|
||||
// Runtime policy removes entries before default selection; never resurrect them.
|
||||
const restricted = entries.filter(e => e.key === keys[0]);
|
||||
expect(resolveLegacyPaperclipDesiredSkillNames({}, restricted)).toEqual([keys[0]]);
|
||||
expect(await readPaperclipRuntimeSkillEntries({ paperclipRuntimeSkills: [] }, import.meta.dirname)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,261 @@
|
||||
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 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);
|
||||
});
|
||||
});
|
||||
@@ -38,7 +38,7 @@ describe("claude local skill sync", () => {
|
||||
|
||||
expect(snapshot.mode).toBe("ephemeral");
|
||||
expect(snapshot.supported).toBe(true);
|
||||
expect(snapshot.desiredSkills).toEqual([paperclipKey]);
|
||||
expect(snapshot.desiredSkills).toEqual([paperclipKey, "paperclipai/paperclip/complain", "paperclipai/paperclip/suggestion-box"]);
|
||||
expect(snapshot.entries.find((entry) => entry.key === paperclipKey)?.state).toBe("configured");
|
||||
expect(snapshot.entries.find((entry) => entry.key === createAgentKey)?.state).toBe("available");
|
||||
});
|
||||
|
||||
@@ -66,7 +66,7 @@ describe("cursor local skill sync", () => {
|
||||
},
|
||||
}, []);
|
||||
|
||||
expect(snapshot.desiredSkills).toEqual([paperclipKey]);
|
||||
expect(snapshot.desiredSkills).toEqual([paperclipKey, "paperclipai/paperclip/complain", "paperclipai/paperclip/suggestion-box"]);
|
||||
expect(snapshot.entries.find((entry) => entry.key === paperclipKey)?.state).toBe("installed");
|
||||
expect((await fs.lstat(path.join(home, ".cursor", "skills", "paperclip"))).isSymbolicLink()).toBe(true);
|
||||
});
|
||||
|
||||
@@ -28,6 +28,37 @@ describe("HTTP logger redaction", () => {
|
||||
expect(chunks.join("")).not.toMatch(/code-canary|pkce-canary|refresh-canary|redirect-canary|state-canary/);
|
||||
});
|
||||
|
||||
it.each([[400, "/api/companies/company/agent-commentary"], [503, "/API/COMPANIES/company/AGENT-COMMENTARY"], [503, "http://localhost/api/companies/company/agent-commentary"]] as const)("keeps rejected commentary content out of %i diagnostics for %s", async (status, url) => {
|
||||
const canary = "private-agent-commentary-canary";
|
||||
const chunks: string[] = [];
|
||||
const stream = new Writable({ write(chunk, _encoding, callback) { chunks.push(chunk.toString()); callback(); } });
|
||||
const app = express();
|
||||
app.use(createHttpLogger(pino({ redact: [...HTTP_LOG_REDACT_PATHS] }, stream)));
|
||||
app.use(express.json());
|
||||
app.post("/api/companies/:companyId/agent-commentary", (_req, res) => {
|
||||
if (status === 503) (res as any).err = new Error(`Driver echoed ${canary}`);
|
||||
res.status(status).end();
|
||||
});
|
||||
const server = createServer(app);
|
||||
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
|
||||
try {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Missing test listener");
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const client = httpRequest({ hostname: "127.0.0.1", port: address.port, method: "POST", path: url, headers: { "content-type": "application/json" } }, res => {
|
||||
expect(res.statusCode).toBe(status);
|
||||
res.resume(); res.on("end", resolve);
|
||||
});
|
||||
client.on("error", reject);
|
||||
client.end(JSON.stringify({ body: canary, unexpected: canary }));
|
||||
});
|
||||
} finally {
|
||||
await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
||||
}
|
||||
const output = chunks.join("");
|
||||
expect(output).not.toContain(canary);
|
||||
expect(JSON.parse(output.trim()).reqBody).toBe("[REDACTED]");
|
||||
});
|
||||
it.each([
|
||||
{ method: "POST", path: "/api/routine-triggers/public/private-url-canary/fire" },
|
||||
{ method: "PUT", path: "/api/routine-triggers/public/private-url-canary/fire" },
|
||||
|
||||
@@ -19,6 +19,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"activity.ts": "/api",
|
||||
"adapters.ts": "/api",
|
||||
"agents.ts": "/api",
|
||||
"agent-commentary.ts": "/api",
|
||||
"agent-avatars.ts": "/api",
|
||||
"announcements.ts": "/api",
|
||||
"ai-connections.ts": "/api",
|
||||
@@ -237,6 +238,27 @@ function loadSpecRoutes() {
|
||||
}
|
||||
|
||||
describe("openapi routes", () => {
|
||||
it("documents strict run-attributed feedback without a read endpoint", () => {
|
||||
const { spec } = loadSpecRoutes();
|
||||
const path = spec.paths["/api/companies/{companyId}/agent-commentary"];
|
||||
expect(Object.keys(path)).toEqual(["post"]);
|
||||
const operation = path.post;
|
||||
expect(operation.security).toEqual([{ AgentBearerAuth: [] }]);
|
||||
expect(operation["x-paperclip-authorization"]).toEqual({ actor: "agent", heartbeatBound: true });
|
||||
expect(operation.description).toContain("X-Paperclip-Run-Id");
|
||||
const body = operation.requestBody.content["application/json"].schema;
|
||||
expect(body.additionalProperties).toBe(false);
|
||||
expect(Object.keys(body.properties).sort()).toEqual(["body", "idempotencyKey", "kind"]);
|
||||
expect(body.properties.body.maxLength).toBe(524288);
|
||||
for (const code of ["200", "201"]) {
|
||||
const result = operation.responses[code].content["application/json"].schema;
|
||||
expect(result.additionalProperties).toBe(false);
|
||||
expect(Object.keys(result.properties).sort()).toEqual(["createdAt", "id", "kind", "replayed"]);
|
||||
}
|
||||
expect(operation.responses["409"]).toBeDefined();
|
||||
expect(operation.responses["503"]).toBeDefined();
|
||||
});
|
||||
|
||||
it("documents board-only pool management with revision-checked deletion", () => {
|
||||
const { spec } = loadSpecRoutes();
|
||||
const pools = spec.paths["/api/companies/{companyId}/ai-connection-pools"];
|
||||
|
||||
@@ -92,6 +92,7 @@ import {
|
||||
} from "./routes/chat-channels.js";
|
||||
import { smokeLabRoutes } from "./routes/smoke-lab.js";
|
||||
import { costRoutes } from "./routes/costs.js";
|
||||
import { agentCommentaryRoutes } from "./routes/agent-commentary.js";
|
||||
import { activityRoutes } from "./routes/activity.js";
|
||||
import { dashboardRoutes } from "./routes/dashboard.js";
|
||||
import { attentionRoutes } from "./routes/attention.js";
|
||||
@@ -683,6 +684,7 @@ export async function createApp(
|
||||
api.use(companySkillRoutes(db));
|
||||
api.use(companySkillPolicyRoutes(db));
|
||||
api.use(inboxAgentPolicyRoutes(db));
|
||||
api.use(agentCommentaryRoutes(db));
|
||||
api.use(builtInAgentRoutes(db));
|
||||
api.use(summarySlotRoutes(db));
|
||||
api.use(statusCardRoutes(db));
|
||||
|
||||
@@ -44,6 +44,14 @@ const SECRET_SENSITIVE_HTTP_PATHS = [
|
||||
];
|
||||
const SECRET_SENSITIVE_HTTP_METHODS = new Set(["POST", "PUT", "PATCH"]);
|
||||
|
||||
/** Free-form agent feedback must never be copied into HTTP diagnostics. */
|
||||
export function isPrivateAgentCommentaryHttpRequest(url: string | undefined): boolean {
|
||||
if (!url) return false;
|
||||
// Express routes are case-insensitive and also accept absolute-form URLs.
|
||||
const pathname = normalizePath(url).replace(/^https?:\/\/[^/]*/i, "");
|
||||
return /^\/api\/companies\/[^/]+\/agent-commentary(?:\/|$)/i.test(pathname);
|
||||
}
|
||||
|
||||
/** Provider payloads are private even when a method/signature is rejected. */
|
||||
export function isPrivateWebhookHttpRequest(
|
||||
method: string | undefined,
|
||||
@@ -79,6 +87,7 @@ export function isSecretSensitiveHttpRequest(
|
||||
url: string | undefined,
|
||||
): boolean {
|
||||
if (isPrivateWebhookHttpRequest(method, url)) return true;
|
||||
if (isPrivateAgentCommentaryHttpRequest(url)) return true;
|
||||
if (!method || !url) return false;
|
||||
if (!SECRET_SENSITIVE_HTTP_METHODS.has(method.toUpperCase())) return false;
|
||||
const pathname = normalizePath(url);
|
||||
|
||||
@@ -5,6 +5,7 @@ import { HTTP_LOG_REDACT_PATHS } from "./http-log-redaction.js";
|
||||
import {
|
||||
isPrivateWebhookHttpRequest,
|
||||
isSecretSensitiveHttpRequest,
|
||||
isPrivateAgentCommentaryHttpRequest,
|
||||
shouldSilenceHttpSuccessLog,
|
||||
} from "./http-log-policy.js";
|
||||
import {
|
||||
@@ -83,6 +84,9 @@ export function createHttpLogger(baseLogger: Logger) {
|
||||
logger: baseLogger,
|
||||
serializers: {
|
||||
req(req: Record<string, unknown> & { url?: unknown }) {
|
||||
if (isPrivateAgentCommentaryHttpRequest(typeof req.url === "string" ? req.url : undefined)) {
|
||||
return { id: req.id, method: req.method, url: stripSecretBearingUrlParts(req.url as string) };
|
||||
}
|
||||
if (
|
||||
isPrivateWebhook({
|
||||
method: typeof req.method === "string" ? req.method : undefined,
|
||||
@@ -119,7 +123,7 @@ export function createHttpLogger(baseLogger: Logger) {
|
||||
) {
|
||||
// A provider error may also be reflected in response headers. Keep the
|
||||
// same content-free contract on both sides of a webhook request.
|
||||
return res.raw?.req && isPrivateWebhook(res.raw.req)
|
||||
return res.raw?.req && (isPrivateWebhook(res.raw.req) || isPrivateAgentCommentaryHttpRequest(requestClassificationUrl(res.raw.req)))
|
||||
? { statusCode: res.statusCode }
|
||||
: res;
|
||||
},
|
||||
@@ -150,6 +154,9 @@ export function createHttpLogger(baseLogger: Logger) {
|
||||
return `${req.method} ${stripSecretBearingUrlParts(req.url ?? "")} ${res.statusCode} — ${errMsg}`;
|
||||
},
|
||||
customErrorObject(req, _res, _err, value) {
|
||||
if (isPrivateAgentCommentaryHttpRequest(requestClassificationUrl(req))) {
|
||||
return { ...value, err: { type: "Error", message: "Feedback request failed" } };
|
||||
}
|
||||
// pino-http serializes res.err independently of customProps/errorContext.
|
||||
// Do not rely on a particular error handler having sanitized an SDK Error.
|
||||
return isPrivateWebhook(req)
|
||||
@@ -165,7 +172,7 @@ export function createHttpLogger(baseLogger: Logger) {
|
||||
if (/^\/mcp\/(?:oauth|paperclip)(?:\/|$)/.test(requestClassificationUrl(req) ?? "")) {
|
||||
return { reqBody: "[REDACTED]", ...(ctx ? { errorContext: { name: "Error" } } : {}) };
|
||||
}
|
||||
if (isPrivateWebhook(req)) {
|
||||
if (isPrivateWebhook(req) || isPrivateAgentCommentaryHttpRequest(requestClassificationUrl(req))) {
|
||||
// Omit, rather than recursively redact, the entire provider payload.
|
||||
// This applies equally before/after parsing and with/without context.
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Router } from "express";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { forbidden } from "../errors.js";
|
||||
import { submitAgentCommentary } from "../services/agent-commentary.js";
|
||||
import { assertCompanyAccess } from "./authz.js";
|
||||
|
||||
export function agentCommentaryRoutes(db: Db) {
|
||||
const router = Router();
|
||||
router.post("/companies/:companyId/agent-commentary", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
if (req.actor.type !== "agent" || !req.actor.agentId || !req.actor.runId) {
|
||||
throw forbidden("Feedback requires an authenticated agent run");
|
||||
}
|
||||
const result = await submitAgentCommentary(db, {
|
||||
companyId, agentId: req.actor.agentId, runId: req.actor.runId, agentApiKeyId: req.actor.keyId,
|
||||
}, req.body);
|
||||
res.status(result.replayed ? 200 : 201).json(result);
|
||||
});
|
||||
return router;
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
slackToolCallSchema,
|
||||
slackSearchConfigSchema,
|
||||
// Agent
|
||||
submitAgentCommentarySchema,
|
||||
AGENT_PALETTE_IDS,
|
||||
AGENT_AVATAR_SIZES,
|
||||
CHARACTER_STATES,
|
||||
@@ -1264,6 +1265,7 @@ function registerCurrentRoute(input: {
|
||||
type OpenApiAuthLevel =
|
||||
| "public"
|
||||
| "agent_run"
|
||||
| "agent_heartbeat"
|
||||
| "runtime_tools"
|
||||
| "authenticated"
|
||||
| "board"
|
||||
@@ -1686,6 +1688,7 @@ function resolveOperationAuthLevel(
|
||||
if (key === "GET /api/mcp/requests/{id}" || key === "GET /api/mcp/device") return "public";
|
||||
if (path === "/api/mcp/setup" || path === "/api/mcp/device/consent" || path.startsWith("/api/mcp/requests/") || path.startsWith("/api/mcp/connections")) return "board";
|
||||
if (PUBLIC_OPERATIONS.has(key)) return "public";
|
||||
if (key === "POST /api/companies/{companyId}/agent-commentary") return "agent_heartbeat";
|
||||
if (key === "POST /api/mcp/project-tools" || key === "POST /api/companies/{companyId}/slack/tasks/{issueId}/tools") return "agent_run";
|
||||
if (RUNTIME_TOOLS_OPERATIONS.has(key)) return "runtime_tools";
|
||||
if (INSTANCE_ADMIN_OPERATIONS.has(key)) return "instance_admin";
|
||||
@@ -1757,6 +1760,8 @@ function applyDocumentFixups(document: any): any {
|
||||
operation.security = [];
|
||||
} else if (authLevel === "agent_run") {
|
||||
operation.security = [securityRequirement(AGENT_RUN_AUTH_SCHEME)];
|
||||
} else if (authLevel === "agent_heartbeat") {
|
||||
operation.security = [securityRequirement(AGENT_BEARER_AUTH_SCHEME)];
|
||||
} else if (authLevel === "runtime_tools") {
|
||||
operation.security = RUNTIME_TOOLS_SECURITY;
|
||||
} else if (authLevel === "authenticated") {
|
||||
@@ -1772,6 +1777,8 @@ function applyDocumentFixups(document: any): any {
|
||||
? { actor: "board" }
|
||||
: authLevel === "agent_run"
|
||||
? { actor: "agent", heartbeatBound: true, taskBound: true }
|
||||
: authLevel === "agent_heartbeat"
|
||||
? { actor: "agent", heartbeatBound: true }
|
||||
: authLevel === "runtime_tools"
|
||||
? { actor: "runtime_tools", heartbeatBound: true }
|
||||
: authLevel === "authenticated"
|
||||
@@ -5288,6 +5295,33 @@ registry.registerPath({
|
||||
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized },
|
||||
});
|
||||
|
||||
// ─── Agent feedback ──────────────────────────────────────────────────────────
|
||||
|
||||
const agentCommentaryAcknowledgementSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
kind: z.enum(["complaint", "suggestion"]),
|
||||
createdAt: z.string().datetime(),
|
||||
replayed: z.boolean(),
|
||||
}).strict();
|
||||
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/api/companies/{companyId}/agent-commentary",
|
||||
tags: ["agents"],
|
||||
summary: "Submit internally attributed agent feedback",
|
||||
description: "Requires an active legacy agent run: a run-bound agent JWT, or an agent API key with X-Paperclip-Run-Id. Attribution is derived from authority; ownership fields are rejected. Equivalent replay returns the existing acknowledgement. Native runs use their bound feedback tools. Failure must not interrupt the primary task or trigger retries.",
|
||||
request: {
|
||||
params: z.object({ companyId: z.string() }),
|
||||
body: jsonBody(submitAgentCommentarySchema),
|
||||
},
|
||||
responses: {
|
||||
200: r.ok(agentCommentaryAcknowledgementSchema),
|
||||
201: { ...r.ok(agentCommentaryAcknowledgementSchema), description: "Feedback stored" },
|
||||
400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 409: r.conflict,
|
||||
503: { description: "Feedback storage unavailable; continue the primary task without retrying" },
|
||||
},
|
||||
});
|
||||
|
||||
// ─── Costs ───────────────────────────────────────────────────────────────────
|
||||
|
||||
const costSummaryPaths = [
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { agentCommentary, agents, heartbeatRuns, issues, nativeRunResults, type Db } from "@paperclipai/db";
|
||||
import { isUuidLike, submitAgentCommentarySchema, type AgentCommentaryAcknowledgement } from "@paperclipai/shared";
|
||||
import { badRequest, conflict, forbidden, HttpError } from "../errors.js";
|
||||
import { redactSensitiveText } from "../redaction.js";
|
||||
import { persistActivity, publishActivity } from "./activity-log.js";
|
||||
import { createRunSecretRedactionRegistry } from "./run-secret-redaction.js";
|
||||
import { agentRunWritesRevoked } from "../agent-run-cancellation.js";
|
||||
|
||||
type CommentaryActor = { companyId: string; agentId: string; runId: string; agentApiKeyId?: string | null };
|
||||
|
||||
function boundIssue(run: typeof heartbeatRuns.$inferSelect): string | null {
|
||||
const snapshot = run.contextSnapshot ?? {};
|
||||
const id = run.nativeIssueId ?? snapshot.issueId ?? snapshot.taskId;
|
||||
if (id == null) return null;
|
||||
if (typeof id !== "string" || !isUuidLike(id)) throw forbidden("Feedback requires a valid run task binding");
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Both transports share authorization, persistence and replay; no task state is changed. */
|
||||
export async function submitAgentCommentary(
|
||||
db: Db,
|
||||
actor: CommentaryActor,
|
||||
value: unknown,
|
||||
authorizeNative?: (tx: Db) => Promise<unknown>,
|
||||
): Promise<AgentCommentaryAcknowledgement> {
|
||||
const parsed = submitAgentCommentarySchema.safeParse(value);
|
||||
if (!parsed.success) throw badRequest("Feedback requires a kind, nonempty body of at most 524288 characters, and a retry key of at most 240 characters; no other fields are accepted");
|
||||
if (![actor.companyId, actor.agentId, actor.runId].every(isUuidLike)) {
|
||||
throw forbidden("Feedback requires an authenticated agent run");
|
||||
}
|
||||
const input = parsed.data;
|
||||
const payloadHash = createHash("sha256").update(JSON.stringify([input.kind, input.body])).digest("hex");
|
||||
try {
|
||||
const { result, publication } = await db.transaction(async (tx) => {
|
||||
const scopedDb = tx as unknown as Db;
|
||||
// Native authority locks issue before run. Legacy follows the same lock order.
|
||||
if (authorizeNative) await authorizeNative(scopedDb);
|
||||
const predicate = and(eq(heartbeatRuns.id, actor.runId), eq(heartbeatRuns.companyId, actor.companyId), eq(heartbeatRuns.agentId, actor.agentId));
|
||||
const [initialRun] = await tx.select().from(heartbeatRuns).where(predicate);
|
||||
if (!initialRun) throw forbidden("Feedback requires an authenticated agent run");
|
||||
const issueId = boundIssue(initialRun);
|
||||
const [issue] = issueId ? await tx.select().from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, actor.companyId))).for("update") : [];
|
||||
const [context] = await tx.select({ run: heartbeatRuns, agent: agents }).from(heartbeatRuns)
|
||||
.innerJoin(agents, and(eq(agents.id, heartbeatRuns.agentId), eq(agents.companyId, heartbeatRuns.companyId)))
|
||||
.where(predicate).for("update");
|
||||
if (!context || context.run.status !== "running"
|
||||
|| agentRunWritesRevoked(context.run)
|
||||
|| ["paused", "terminated", "pending_approval", "error"].includes(context.agent.status)
|
||||
|| boundIssue(context.run) !== issueId
|
||||
|| (issueId && !issue)
|
||||
|| (issue?.executionRunId && issue.executionRunId !== actor.runId)
|
||||
|| (issue?.conversationAgentId && Number(context.run.contextSnapshot?.conversationSessionGeneration ?? 0) !== issue.conversationSessionGeneration)) {
|
||||
throw forbidden("The agent run is no longer authorized to submit feedback");
|
||||
}
|
||||
if (context.run.runtimeMode === "native") {
|
||||
if (!authorizeNative) throw forbidden("Native runs submit feedback through their bound tools");
|
||||
const [finished] = await tx.select({ id: nativeRunResults.id }).from(nativeRunResults)
|
||||
.where(and(eq(nativeRunResults.companyId, actor.companyId), eq(nativeRunResults.runId, actor.runId), eq(nativeRunResults.schemaStatus, "accepted"))).limit(1);
|
||||
if (finished) throw forbidden("Feedback must be submitted before finishing the run");
|
||||
}
|
||||
const [prior] = await tx.select().from(agentCommentary).where(and(
|
||||
eq(agentCommentary.companyId, actor.companyId), eq(agentCommentary.runId, actor.runId), eq(agentCommentary.idempotencyKey, input.idempotencyKey),
|
||||
));
|
||||
if (prior) {
|
||||
if (prior.payloadHash !== payloadHash) throw conflict("Feedback retry key was already used with different content");
|
||||
return { result: { id: prior.id, kind: prior.kind, createdAt: prior.createdAt.toISOString(), replayed: true }, publication: null };
|
||||
}
|
||||
const body = redactSensitiveText(await createRunSecretRedactionRegistry(scopedDb).redactForRun(actor.companyId, actor.runId, input.body));
|
||||
const [row] = await tx.insert(agentCommentary).values({
|
||||
companyId: actor.companyId, agentId: actor.agentId, runId: actor.runId,
|
||||
issueId, kind: input.kind, body, idempotencyKey: input.idempotencyKey, payloadHash,
|
||||
}).returning({ id: agentCommentary.id, kind: agentCommentary.kind, createdAt: agentCommentary.createdAt });
|
||||
const { publication } = await persistActivity(scopedDb, {
|
||||
companyId: actor.companyId, actorType: "agent", actorId: actor.agentId, agentId: actor.agentId,
|
||||
runId: actor.runId, agentApiKeyId: actor.agentApiKeyId, issueId,
|
||||
action: "agent.commentary_submitted", entityType: "agent_commentary", entityId: row.id,
|
||||
details: { kind: row.kind },
|
||||
});
|
||||
return { result: { id: row.id, kind: row.kind, createdAt: row.createdAt.toISOString(), replayed: false }, publication };
|
||||
});
|
||||
if (publication) publishActivity(publication);
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError) throw error;
|
||||
// Driver errors can include SQL parameters containing the entire feedback body.
|
||||
throw new HttpError(503, "Feedback could not be stored. Continue the primary task without retrying.");
|
||||
}
|
||||
}
|
||||
@@ -102,7 +102,7 @@ describe("PaperclipRunnerToolAuthority", () => {
|
||||
issueId,
|
||||
runId,
|
||||
});
|
||||
expect(authority.definitions()).toHaveLength(36);
|
||||
expect(authority.definitions()).toHaveLength(38);
|
||||
const questions = authority.definitions().find(tool => tool.name === "request_human_input")!;
|
||||
expect(questions.description).toContain("ask only the next unanswered question");
|
||||
expect(questions.description).toContain("Never fabricate answers");
|
||||
@@ -123,6 +123,8 @@ describe("PaperclipRunnerToolAuthority", () => {
|
||||
"get_task_history",
|
||||
"search_tasks",
|
||||
"report_progress",
|
||||
"submit_complaint",
|
||||
"submit_suggestion",
|
||||
"request_human_input",
|
||||
"create_task",
|
||||
"set_dependencies",
|
||||
|
||||
@@ -6,6 +6,8 @@ import { authorizeInstructionCommit } from "../agent-instruction-authorization.j
|
||||
import { executeAgentInstructionTool } from "./agent-instruction-tools.js";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { publicChatTaskUrl } from "../chat-task-url.js";
|
||||
import { agentCommentaryToolInputSchema } from "@paperclipai/shared";
|
||||
import { submitAgentCommentary } from "../agent-commentary.js";
|
||||
import type { createAssignedMcpTools } from "./assigned-mcp-tools.js";
|
||||
import { assertAssignableAgent } from "../agent-assignability.js";
|
||||
import { authorizationService } from "../authorization.js";
|
||||
@@ -94,6 +96,7 @@ import {
|
||||
} from "./chat-attachment-read.js";
|
||||
|
||||
const IMPLEMENTED_OPERATIONS = new Set([
|
||||
"submit_complaint", "submit_suggestion",
|
||||
"read_agent_instructions", "update_agent_instructions", "get_agent_instruction_history", "restore_agent_instructions",
|
||||
"search_api", "call_api", "hire_agent",
|
||||
"get_task_context", "get_task_history", "search_tasks", "report_progress", "set_task_title",
|
||||
@@ -400,6 +403,14 @@ export class PaperclipRunnerToolAuthority {
|
||||
throw new Error("paperclip_runner_tool_mode_denied");
|
||||
}
|
||||
switch (call.tool) {
|
||||
case "submit_complaint":
|
||||
case "submit_suggestion": {
|
||||
const parsed = agentCommentaryToolInputSchema.safeParse(call.arguments);
|
||||
if (!parsed.success) throw badRequest("Feedback accepts only a nonempty body of at most 524288 characters and a retry key of at most 240 characters");
|
||||
return submitAgentCommentary(this.db, this.binding, {
|
||||
...parsed.data, kind: call.tool === "submit_complaint" ? "complaint" : "suggestion",
|
||||
}, (tx) => this.#lockAuthorizedMutationContext(tx));
|
||||
}
|
||||
case "read_agent_instructions":
|
||||
case "get_agent_instruction_history":
|
||||
return executeAgentInstructionTool({ db: this.db, binding: {
|
||||
|
||||
Reference in new issue
Block a user