fix(interactions): don't supersede decision cards on machine-authored comments (#9015)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agents and humans coordinate on issue threads, where
`request_confirmation` cards capture pending decisions; a genuine human
comment on the thread is meant to supersede (cancel) a card.
> - Supersession is keyed on `!comment.authorUserId` — the guard assumes
only real human comments carry a user id.
> - But local-CLI agent heartbeats post comments under user auth, so a
machine comment's `authorUserId` is populated **nondeterministically per
run** (the same agent resolves as `agent` on one run and `user` on
another).
> - As a result an agent's own on-thread comment — or a teammate's, from
a different run — can carry `authorUserId` and silently expire a pending
decision card. A card was observed expiring 7ms after its own automated
comment landed, stranding the decision with no live approval path.
> - This PR switches the discriminator to a durable, deterministic
signal already persisted on every comment — `created_by_run_id` — so
only comments with **no run context** (genuine board-UI comments)
supersede.
> - The benefit: machine-authored comments can never again expire
decision cards, while real human supersession is preserved exactly.

## Linked Issues or Issue Description

No public GitHub issue — describing the bug in-PR.

- **What happened:** A pending `request_confirmation` decision card was
expired by an automated, machine-authored comment on the same thread.
Supersession is keyed on `!comment.authorUserId`, but local-CLI agent
heartbeats post under user auth, so a machine comment's `authorUserId`
is set nondeterministically per run. An agent's own comment (or a
teammate's, from a different run) can therefore carry a user id and
expire a pending card — one was observed expiring 7ms after its own
automated comment landed.
- **Expected behavior:** Only genuine interactive human (board-UI)
comments should supersede pending decision cards. Machine-authored
comments must never expire them, regardless of how the adapter's auth
resolves.
- **Steps to reproduce:** With a pending `request_confirmation` card
(`supersedeOnUserComment: true`), post a comment via a local-CLI agent
run whose actor resolves to `user`; the card expires with outcome
`superseded_by_comment`.
- **Deployment mode:** server (self-hosted), reproduced against
`master`.

Related PRs (same lifecycle area, not duplicates): #6094 (auto-resolve
stale `request_confirmation` interactions) and #8799 (expire ask-user
questions superseded by comments, merged).

## What Changed

- Supersession now fires **only on comments with no run context**
(`created_by_run_id` is null), in both paths:
- `expireRequestConfirmationsSupersededByComment` (live post path) —
early-return when `comment.createdByRunId` is set.
- `expireRequestConfirmationsSupersededByHistoricalComments` (repair
sweep) — query filters `isNull(created_by_run_id)`.
- Mirrors the existing `shouldImplicitlyMoveCommentedIssueToTodo` reopen
guard, which already uses run context to solve the same
nondeterministic-identity problem.
- Adds live + historical regression tests asserting a run-originated
comment under user auth does not supersede a pending card.

## Verification

- Interactions service suite: **27 tests pass (1 file)**, including the
two new regression tests.
- CI: all substantive gates green (Build, General tests, serialized
server suites, Typecheck, e2e, verify, security-review, policy).
- Manual: with a pending card, a comment carrying `created_by_run_id`
leaves it `pending`; a comment with null run context still supersedes
it.

## Risks

- Low risk, narrowly scoped to the supersession discriminator. Human
supersession is preserved (comments with no run context still cancel
cards); only the machine-authored case is closed.
- No schema migration — `created_by_run_id` is already persisted by
`addComment`.
- Alternatives considered: (a) ignore only the assignee's own run —
misses cross-run machine comments; (b) default `supersedeOnUserComment:
false` for agent-created cards — would drop the legitimate "human
comment redirects → cancel the card" behavior. The run-context guard
covers all machine comments while preserving human supersession.

## Model Used

Claude Opus 4.8 (Anthropic), model id `claude-opus-4-8`, extended
reasoning + tool use, via Claude Code.

## 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)
- [ ] My branch name describes the change and contains no internal
Paperclip ticket id — **not yet met**; renaming an open PR's branch
risks closing this PR, so it's flagged for a maintainer to rename safely
(or via the GitHub rename-branch API).
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes — N/A
(internal behavior fix, no user-facing docs)
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green (the only red check is the
automated PR-review template gate this revision addresses)
- [ ] Greptile is 5/5 with no open P2s — re-review requested after this
revision
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Andrew Aymeloglu <aaymeloglu@gmail.com>
This commit is contained in:
Nicholas Sollazzo 2026-07-14 22:56:26 +02:00 committed by GitHub
parent 3db2e6bdd2
commit df0e5bd021
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 107 additions and 2 deletions

View File

@ -1627,6 +1627,43 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => {
expect(rows[0]?.status).toBe("pending");
});
it("does not supersede request confirmations for run-originated comments even under user auth", async () => {
// Local-CLI agents post under user auth, so authorUserId is set nondeterministically.
// A comment carrying createdByRunId is machine-originated and must never expire a
// pending decision card.
const { companyId, issueId } = await seedConfirmationIssue("Run-originated comment supersede exclusion");
const created = await interactionsSvc.create({
id: issueId,
companyId,
}, {
kind: "request_confirmation",
payload: {
version: 1,
prompt: "Proceed with the current draft?",
},
}, {
userId: "local-board",
});
const expired = await interactionsSvc.expireRequestConfirmationsSupersededByComment({
id: issueId,
companyId,
}, {
id: randomUUID(),
createdAt: new Date(new Date(created.createdAt).getTime() + 1_000),
authorUserId: "local-board",
createdByRunId: randomUUID(),
}, {
userId: "local-board",
});
expect(expired).toHaveLength(0);
const rows = await db.select().from(issueThreadInteractions);
expect(rows).toHaveLength(1);
expect(rows[0]?.status).toBe("pending");
});
it("repairs historical request confirmations superseded by later user comments idempotently", async () => {
const { companyId, issueId } = await seedConfirmationIssue("Historical comment supersede");
const commentId = randomUUID();
@ -1693,6 +1730,69 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => {
})).resolves.toEqual([]);
});
it("does not repair historical confirmations from run-originated comments", async () => {
// The repair sweep must ignore machine-originated comments (createdByRunId set) even
// when authorUserId is present under user auth.
const { companyId, issueId } = await seedConfirmationIssue("Historical run-originated exclusion");
const agentId = randomUUID();
const runId = randomUUID();
const createdAt = new Date("2026-05-18T12:00:00.000Z");
const created = await interactionsSvc.create({
id: issueId,
companyId,
}, {
kind: "request_confirmation",
payload: {
version: 1,
prompt: "Proceed with the current draft?",
},
}, {
userId: "local-board",
});
await db
.update(issueThreadInteractions)
.set({ createdAt, updatedAt: createdAt })
.where(eq(issueThreadInteractions.id, created.id));
await db.insert(agents).values({
id: agentId,
companyId,
name: "GiskardCoder",
role: "engineer",
status: "active",
adapterType: "claude_local",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
});
await db.insert(heartbeatRuns).values({
id: runId,
companyId,
agentId,
status: "running",
});
await db.insert(issueComments).values({
id: randomUUID(),
companyId,
issueId,
authorUserId: "local-board",
authorType: "user",
createdByRunId: runId,
body: "SLA escalation relay posted from a heartbeat run.",
createdAt: new Date("2026-05-18T12:01:00.000Z"),
updatedAt: new Date("2026-05-18T12:01:00.000Z"),
});
await expect(interactionsSvc.expireRequestConfirmationsSupersededByHistoricalComments({
id: issueId,
companyId,
})).resolves.toEqual([]);
const rows = await db.select().from(issueThreadInteractions);
expect(rows).toHaveLength(1);
expect(rows[0]?.status).toBe("pending");
});
it("expires request confirmations when the watched issue document revision changes", async () => {
const companyId = randomUUID();
const goalId = randomUUID();

View File

@ -1,5 +1,5 @@
import { isDeepStrictEqual } from "node:util";
import { and, asc, eq, inArray, isNotNull } from "drizzle-orm";
import { and, asc, eq, inArray, isNotNull, isNull } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
agents,
@ -1572,10 +1572,13 @@ export function issueThreadInteractionService(db: Db) {
expireRequestConfirmationsSupersededByComment: async (
issue: { id: string; companyId: string },
comment: { id: string; createdAt: Date | string; authorUserId?: string | null },
comment: { id: string; createdAt: Date | string; authorUserId?: string | null; createdByRunId?: string | null },
actor: InteractionActor,
) => {
if (!comment.authorUserId) return [];
// Local-CLI adapters post under user auth, so authorUserId can't tell a human from a
// machine; createdByRunId can. Only genuine human comments (no run context) supersede.
if (comment.createdByRunId) return [];
const rows = await db
.select()
@ -1649,6 +1652,8 @@ export function issueThreadInteractionService(db: Db) {
eq(issueComments.companyId, issue.companyId),
eq(issueComments.issueId, issue.id),
isNotNull(issueComments.authorUserId),
// Only genuine human comments supersede; machine-originated ones carry createdByRunId.
isNull(issueComments.createdByRunId),
))
.orderBy(asc(issueComments.createdAt)),
]);