mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 20:12:20 +01:00
fix(chat): name document revisions and link runs in replies, and record agent-started routine runs as manual (#21183)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - People talk to their agents in chat, and the chat directive tells the agent how to write replies > - #21081 added a rule that keeps raw IDs and internal codes out of replies. It names only tasks, cases, approvals and people as records to cite > - After #21081, agents stopped saying "revision 4" and stopped linking runs. In a full chat cohort, "revision N" mentions fell from 21 to 11, and run links fell from 9 to 5 > - A person needs the revision number that Paperclip shows and a link to the run that failed. The intended effect held: UUIDs in prose fell from 24 to 7 > - Separately, an agent that started a routine on a person's chat request sent `source: "api"`, so the run was not recorded as a manual run > - This pull request extends the same rule to name document revisions by number and to link runs, and records every agent-started run on the run-now route as manual > - The benefit is replies that point to the records the person can open, and truthful run sources ## Linked Issues or Issue Description Refs #21081 **What happened?** After #21081, a restore reply said "the version before the last edit" and did not name the new revision. A failed-run reply did not link the failed run. In a different case, the agent called `POST /api/routines/{id}/run` with `source: "api"` after two 400 responses. The run was recorded with source `api`, although a person asked for it in chat. **Expected behavior** The reply names the revision as Paperclip shows it ("revision 4") and links a run it discusses. A run that an agent starts on this route is a manual run. **Steps to reproduce** Run the chat-features OpenCode cases `documents-artifacts.restore-document`, `runs-adapters.inspect-failed-run` and `routines.run-now` on master9e910ff9ae, and read the replies and the routine run source. **Paperclip version or commit** `master` at9e910ff9ae. **Agent adapter(s) involved** Not adapter-specific. Seen with the Paperclip runner and OpenCode (`openrouter/deepseek/deepseek-v4.1-flash-1017`). **Deployment mode** The CI chat-eval runner (local server, embedded database). ## What Changed - `AGENT_CHAT_DIRECTIVE` (`server/src/services/agent-conversations.ts`): the "Write replies for the person" paragraph now also says to name a document revision by its number (such as revision 4), and to link a run it discusses, such as `[the failed run](/<prefix>/agents/<agentId>/runs/<runId>)`. The ban on raw IDs in prose does not change. - `POST /api/routines/:id/run` (`server/src/routes/routines.ts`): for an agent actor, the server ignores the `source` value in the body and records `manual`. Board callers keep their `source` value. - `routines.ts` service: for an agent manual run with an `idempotencyKey`, the replay lookup also returns that same agent's earlier `api` receipt (matched by its `routine.run_triggered` activity). A retry across the upgrade does not start the work twice. A board receipt is not matched. - `docs/api/routines.md`: documents the agent rule for the run-now source. ## Verification - Red/green: `server/src/__tests__/agent-conversations.test.ts` asserts the revision-number and run-link sentences and that the raw-ID ban stays. It failed before the directive change. - Red/green: `server/src/__tests__/routines-routes.test.ts` sends `source: "api"` as an agent and expects `manual`; a board caller keeps `api`. It failed with `source: "api"` before the route change. - Red/green: `server/src/__tests__/routines-service.test.ts` checks that a board `api` receipt with the same key does not satisfy an agent's manual request, and that the agent's own earlier `api` receipt is returned. - `server/src/__tests__/routines-e2e.test.ts` (agent routine-to-routine provenance) still passes. - `pnpm --filter @paperclipai/server typecheck` passes. - Paid OpenCode run on the five affected cases (with the companion eval PR): see the comment below. ## Risks - Low risk. The directive grows by two sentences. A model can still omit a revision number or a run link. - An agent can no longer record a run-now call as `api`. The documented contract for this route is a manual run, and provenance uses the caller run, not the source. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used in Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
eba790713c
commit
8a90aa4731
7 files changed
+50
-3
No files matched your search
@@ -187,6 +187,8 @@ POST /api/routines/{routineId}/run
|
||||
|
||||
Fires a run immediately, bypassing the schedule. Concurrency policy still applies.
|
||||
|
||||
A run an agent starts through this endpoint is always recorded with source `manual`; the server ignores a `source` value an agent sends. Board callers may send `manual` or `api`.
|
||||
|
||||
`triggerId` is optional. When supplied, the server validates the trigger belongs to this routine (`403`) and is enabled (`409`), then records the run against that trigger and updates its `lastFiredAt`. Omit it for a generic manual run with no trigger attribution.
|
||||
|
||||
## Fire Public Trigger
|
||||
|
||||
@@ -995,6 +995,11 @@ describe("chat prompt policy", () => {
|
||||
const prompt = buildPaperclipTaskMarkdown({ issue: { id: "chat", identifier: null, title: "Chat", workMode: "ask", conversationAgentId: "agent" } });
|
||||
expect(prompt).toContain("Write replies for the person, not for the API.");
|
||||
});
|
||||
it("tells chat to name a document revision by its number and to link a run it discusses, while keeping raw IDs out of prose", () => {
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("Name a document revision by its number as Paperclip shows it, such as revision 4, including the revision a restore or edit created.");
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("When you discuss a run, such as a failed or retried run, link it, such as [the failed run](/<prefix>/agents/<agentId>/runs/<runId>), instead of describing it without a link.");
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("Do not write raw IDs (UUIDs or their short forms for runs, revisions,");
|
||||
});
|
||||
it("tells chat to record a person's decline with resolve-from-comment whoever created the card, and keeps withdraw for its own obsolete card", () => {
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("A person's explicit decline in chat (for example \"do not publish it\") answers a pending confirmation with reject, whoever created the card");
|
||||
expect(AGENT_CHAT_DIRECTIVE).toContain("Withdraw is only for your own card that later evidence made obsolete; it never records the person's decision");
|
||||
|
||||
@@ -702,6 +702,17 @@ describe("routine routes", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("records an agent-started run as manual whatever source the agent sends, and keeps a board caller's source", async () => {
|
||||
const agentApp = await createApp({ type: "agent", agentId, companyId });
|
||||
const res = await request(agentApp).post(`/api/routines/${routineId}/run`).send({ source: "api" });
|
||||
expect(res.status, JSON.stringify(res.body)).toBe(202);
|
||||
expect(mockRoutineService.runRoutine).toHaveBeenLastCalledWith(routineId, expect.objectContaining({ source: "manual" }), expect.objectContaining({ agentId }));
|
||||
mockAccessService.canUser.mockResolvedValue(true);
|
||||
const boardApp = await createApp({ type: "board", userId: "board-user", source: "session", isInstanceAdmin: false, companyIds: [companyId] });
|
||||
expect((await request(boardApp).post(`/api/routines/${routineId}/run`).send({ source: "api" })).status).toBe(202);
|
||||
expect(mockRoutineService.runRoutine).toHaveBeenLastCalledWith(routineId, expect.objectContaining({ source: "api" }), expect.objectContaining({ userId: "board-user" }));
|
||||
});
|
||||
|
||||
it("allows routine creation when the board user has tasks:assign", async () => {
|
||||
mockAccessService.canUser.mockResolvedValue(true);
|
||||
const app = await createApp({
|
||||
|
||||
@@ -1198,6 +1198,23 @@ describeEmbeddedPostgres("routine service live-execution coalescing", () => {
|
||||
expect(serialized).not.toContain("runtimeConfig");
|
||||
});
|
||||
|
||||
it("returns only the same agent's earlier api receipt when it retries its key as a manual run", async () => {
|
||||
const { companyId, routine, svc, agentId } = await seedFixture();
|
||||
await db.update(routines).set({ concurrencyPolicy: "always_enqueue" }).where(eq(routines.id, routine.id));
|
||||
const boardApi = await svc.runRoutine(routine.id, { source: "api", idempotencyKey: "shared-key" }, { userId: "operator" });
|
||||
await db.insert(activityLog).values({ companyId, actorType: "user", actorId: "operator", action: "routine.run_triggered", entityType: "routine_run", entityId: boardApi.id });
|
||||
await db.update(issues).set({ status: "done" }).where(eq(issues.id, boardApi.linkedIssueId!));
|
||||
const agentRun = await svc.runRoutine(routine.id, { source: "manual", idempotencyKey: "shared-key" }, { agentId });
|
||||
expect(agentRun.id).not.toBe(boardApi.id);
|
||||
const earlier = await svc.runRoutine(routine.id, { source: "api", idempotencyKey: "agent-retry" }, { agentId });
|
||||
await db.insert(activityLog).values({ companyId, actorType: "agent", actorId: agentId, agentId, action: "routine.run_triggered", entityType: "routine_run", entityId: earlier.id });
|
||||
await db.update(issues).set({ status: "done" }).where(eq(issues.id, earlier.linkedIssueId!));
|
||||
const retry = await svc.runRoutine(routine.id, { source: "manual", idempotencyKey: "agent-retry" }, { agentId });
|
||||
expect(retry.id).toBe(earlier.id);
|
||||
const board = await svc.runRoutine(routine.id, { source: "manual", idempotencyKey: "agent-retry" }, { userId: "operator" });
|
||||
expect(board.id).not.toBe(earlier.id);
|
||||
});
|
||||
|
||||
it("versions responsibility transfers and uses the new person only for future automatic tasks", async () => {
|
||||
const { companyId, routine, svc } = await seedFixture();
|
||||
const userId = "new-responsible-person";
|
||||
|
||||
@@ -662,7 +662,8 @@ export function routineRoutes(
|
||||
return;
|
||||
}
|
||||
await assertBoardCanAssignTasks(req, routine.companyId);
|
||||
const run = await svc.runRoutine(routine.id, req.body, {
|
||||
const input = req.actor.type === "agent" ? { ...req.body, source: "manual" as const } : req.body;
|
||||
const run = await svc.runRoutine(routine.id, input, {
|
||||
agentId: req.actor.type === "agent" ? req.actor.agentId : null,
|
||||
userId: req.actor.type === "board" ? req.actor.userId ?? null : null,
|
||||
runId: req.actor.runId ?? null,
|
||||
|
||||
@@ -128,7 +128,7 @@ When a reply concerns a specific agent, such as one you paused, resumed, configu
|
||||
|
||||
When a reply lists many tasks, write each task identifier in full, such as RUN-12, RUN-13, RUN-14. This conversation links each full identifier to its task, but a range such as RUN-12–14 links only its first task and leaves the others without a source link. When a complete list is too long to read in the reply, save it as a document on this conversation's task and link it, such as [Open work by owner](/<prefix>/issues/<identifier>#document-<key>), keeping a short summary with the counts in the reply.
|
||||
|
||||
Write replies for the person, not for the API. Name each record by what the person sees in Paperclip: a task, case or approval by its identifier (such as RUN-12) or title, a person or agent by name, and link it. Do not write raw IDs (UUIDs or their short forms for runs, revisions, handoffs, interactions, routines, triggers, attachments, workspaces, incidents, users or agents), internal codes (status, error, cause or reason codes such as native_session_retry_exhausted or board_access_required), field or setting keys, tool names, internal process names or server file paths in a reply, even in parentheses or inline code. Say what each means in plain words instead, such as "automatic recovery gave up after 3 attempts" or "only a board user can do this". The only exceptions are link targets, values inside a command the person must run, and an ID the person explicitly asks for.
|
||||
Write replies for the person, not for the API. Name each record by what the person sees in Paperclip: a task, case or approval by its identifier (such as RUN-12) or title, a person or agent by name, and link it. Name a document revision by its number as Paperclip shows it, such as revision 4, including the revision a restore or edit created. When you discuss a run, such as a failed or retried run, link it, such as [the failed run](/<prefix>/agents/<agentId>/runs/<runId>), instead of describing it without a link. Do not write raw IDs (UUIDs or their short forms for runs, revisions, handoffs, interactions, routines, triggers, attachments, workspaces, incidents, users or agents), internal codes (status, error, cause or reason codes such as native_session_retry_exhausted or board_access_required), field or setting keys, tool names, internal process names or server file paths in a reply, even in parentheses or inline code. Say what each means in plain words instead, such as "automatic recovery gave up after 3 attempts" or "only a board user can do this". The only exceptions are link targets, values inside a command the person must run, and an ID the person explicitly asks for.
|
||||
|
||||
When the person asks what is in their inbox or what needs their attention, read their own list with GET /api/agents/me/inbox/mine?userId=<their user id>, using the authorUserId of their message. Answer from those tasks only: your own queue and a company-wide task search are not their inbox, so do not name or link tasks outside it. Link each task you cite and their list as [Mine](/<prefix>/inbox/mine), which opens their personal Mine view in every layout; do not send them to look through an inbox page for it. If that read fails, say so and link Mine instead of answering from other tasks.
|
||||
|
||||
|
||||
@@ -1728,6 +1728,7 @@ export function routineService(
|
||||
assigneeAgentId?: string | null;
|
||||
idempotencyKey?: string | null;
|
||||
rejectIdempotencyReplay?: boolean;
|
||||
replayAgentApiReceiptsFor?: string | null;
|
||||
routineIdempotency?: boolean;
|
||||
createdByRunId?: string | null;
|
||||
executionWorkspaceId?: string | null;
|
||||
@@ -1840,7 +1841,16 @@ export function routineService(
|
||||
and(
|
||||
eq(routineRuns.companyId, input.routine.companyId),
|
||||
eq(routineRuns.routineId, input.routine.id),
|
||||
eq(routineRuns.source, input.source),
|
||||
input.replayAgentApiReceiptsFor
|
||||
? or(eq(routineRuns.source, input.source), and(eq(routineRuns.source, "api"), sql`exists (
|
||||
select 1 from ${activityLog}
|
||||
where ${activityLog.companyId} = ${input.routine.companyId}
|
||||
and ${activityLog.entityType} = 'routine_run'
|
||||
and ${activityLog.entityId} = ${routineRuns.id}::text
|
||||
and ${activityLog.action} = 'routine.run_triggered'
|
||||
and ${activityLog.agentId} = ${input.replayAgentApiReceiptsFor}
|
||||
)`))
|
||||
: eq(routineRuns.source, input.source),
|
||||
eq(routineRuns.idempotencyKey, input.idempotencyKey),
|
||||
idempotentRunId ? eq(routineRuns.id, idempotentRunId)
|
||||
: input.trigger ? eq(routineRuns.triggerId, input.trigger.id) : isNull(routineRuns.triggerId),
|
||||
@@ -2969,6 +2979,7 @@ export function routineService(
|
||||
projectWorkspaceId: input.projectWorkspaceId ?? null,
|
||||
assigneeAgentId: input.assigneeAgentId ?? null,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
replayAgentApiReceiptsFor: input.source === "manual" ? actor?.agentId ?? null : null,
|
||||
executionWorkspaceId: input.executionWorkspaceId ?? null,
|
||||
executionWorkspacePreference: input.executionWorkspacePreference ?? null,
|
||||
executionWorkspaceSettings:
|
||||
|
||||
Reference in new issue
Block a user