mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-31 06:04:11 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents act inside heartbeat runs, and the server attributes every
issue comment and task update to a run so the per-run cross-issue
influence cap can be counted
> - A timer heartbeat that wakes an agent with no checked-out issue
stores no `issueId` in the run context snapshot
> - The influence gate treats that missing source issue as "no valid
run" and rejects every comment and PATCH from the run with
`cross_issue_influence_run_context_required`, even though the run row
exists and fully attributes the write
> - Issue creation is not gated, so an unscoped run can open an issue it
then cannot describe, update, or comment on
> - This pull request counts writes from unscoped runs against the
cross-issue cap instead of rejecting them
> - The benefit is that unscoped heartbeat runs keep their write
channels while the anti-spray cap and the audit trail stay fully intact
## Linked Issues or Issue Description
No public issue exists. Description follows the bug report template.
**What happened?**
An agent woken by a plain heartbeat timer (no assigned issue) received a
403 with code `cross_issue_influence_run_context_required` on every
`POST /api/issues/{id}/comments` and `PATCH /api/issues/{id}` request.
The agent JWT was fresh and its `run_id` matched a live `heartbeat_runs`
row. The error text said the request "arrived without a valid run", but
the run was valid. `POST /api/companies/{companyId}/issues` succeeded
with the same token, so the run created an issue it could not then
update.
**Expected behavior**
A live, authenticated run must be able to comment and update issues. A
run with no source issue has no same-issue exemption, so each of its
writes must spend the per-run cross-issue cap. The
`cross_issue_influence_run_context_required` error must fire only for
malformed, unknown, or mismatched run ids.
**Steps to reproduce**
1. Let an agent wake from the heartbeat timer with no checked-out issue.
2. From that run, call `PATCH /api/issues/{id}` or `POST
/api/issues/{id}/comments` with the agent JWT.
3. The server returns 403 `cross_issue_influence_run_context_required`,
because `observeCrossIssueInfluence` throws when `readRunSourceIssueId`
returns null.
**Paperclip version or commit**
master (c7ebc089c); also reproduced on the current published npm
package.
**Deployment mode**
Local single instance (embedded Postgres).
**Installation method**
npx paperclipai
## What Changed
- `observeCrossIssueInfluence` no longer throws when the persisted run
has no source issue. It counts the write as cross-issue influence and
records `sourceIssueId: null` in the activity log entry.
- The same-issue exemption applies only when the run has a source issue.
- Replaced the test that pinned the old rejection with two tests: an
unscoped run's write is counted and allowed, and an unscoped run is
still capped once its budget is spent.
## Verification
- `cd server && pnpm vitest run
src/__tests__/cross-issue-influence-limit.test.ts` — 11 tests pass.
- `cd server && pnpm vitest run
src/__tests__/cross-issue-influence-limit-postgres.test.ts
src/__tests__/interaction-resolution-cross-issue-cap-postgres.test.ts` —
8 tests pass.
- Manual: wake an agent from a plain heartbeat timer, then PATCH any
issue with the run's JWT. Before the fix the server returns 403
`cross_issue_influence_run_context_required`; after the fix the write
succeeds and an `issue.cross_issue_influence_observed` activity row
appears with `sourceIssueId: null`.
## Risks
- Behavioral shift: writes from unscoped runs were rejected and are now
allowed up to the existing per-run cap of 20. This is the conservative
direction — with no source issue there is no same-issue exemption to
abuse, and every write is still attributed to a locked run row and
logged.
- No schema or migration changes. The activity log
`details.sourceIssueId` field can now be null; it was previously always
set on these rows.
## Model Used
- Claude Fable 5 (Anthropic, model id `claude-fable-5`, 1M context,
extended thinking, tool use enabled) authored the change and tests,
driven through 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)
- [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 Fable 5 <noreply@anthropic.com>
209 lines
7.2 KiB
TypeScript
209 lines
7.2 KiB
TypeScript
import { and, count, eq } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import { activityLog, heartbeatRuns } from "@paperclipai/db";
|
|
import { isUuidLike, issueWriteDenialResponse } from "@paperclipai/shared";
|
|
import { forbidden } from "../errors.js";
|
|
import { logger } from "../middleware/logger.js";
|
|
|
|
export const CROSS_ISSUE_INFLUENCE_LIMIT = 20;
|
|
export const CROSS_ISSUE_INFLUENCE_ENFORCE_AT = new Date("2026-08-11T00:00:00.000Z");
|
|
|
|
const CROSS_ISSUE_INFLUENCE_ACTIVITY = "issue.cross_issue_influence_observed";
|
|
const CROSS_ISSUE_INFLUENCE_REJECTED_ACTIVITY = "issue.cross_issue_influence_cap_rejected";
|
|
|
|
/**
|
|
* Every kind shares one per-run counter. `interaction_resolution` covers the
|
|
* issue-thread accept/reject/respond/verdict routes: an open `anyone` resolver
|
|
* audience is not a licence to resolve, wake, and spawn suggested tasks across
|
|
* the whole company from one run.
|
|
*/
|
|
export type CrossIssueInfluenceKind = "comment" | "update" | "interaction_resolution";
|
|
|
|
export type CrossIssueInfluenceDecision = {
|
|
allowed: boolean;
|
|
mode: "log_only" | "enforce";
|
|
count: number;
|
|
cap: number;
|
|
enforceAt: string;
|
|
};
|
|
|
|
export function crossIssueInfluenceRunContextError() {
|
|
// Copy comes from the shared issue-write denial contract (the open cross-task write design (failure UX))
|
|
// so the agent reading this 403 is told the fix, not just the refusal.
|
|
const { body } = issueWriteDenialResponse("cross_issue_influence_run_context_required");
|
|
return forbidden(body.error, body.details);
|
|
}
|
|
|
|
function readRunSourceIssueId(contextSnapshot: unknown) {
|
|
if (!contextSnapshot || typeof contextSnapshot !== "object" || Array.isArray(contextSnapshot)) return null;
|
|
const context = contextSnapshot as Record<string, unknown>;
|
|
for (const candidate of [context.issueId, context.taskId]) {
|
|
if (typeof candidate === "string" && candidate.trim()) return candidate.trim();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export function evaluateCrossIssueInfluenceLimit(input: {
|
|
priorCount: number;
|
|
now?: Date;
|
|
}): CrossIssueInfluenceDecision {
|
|
const now = input.now ?? new Date();
|
|
const mode = now >= CROSS_ISSUE_INFLUENCE_ENFORCE_AT ? "enforce" : "log_only";
|
|
const nextCount = input.priorCount + 1;
|
|
return {
|
|
allowed: mode === "log_only" || nextCount <= CROSS_ISSUE_INFLUENCE_LIMIT,
|
|
mode,
|
|
count: nextCount,
|
|
cap: CROSS_ISSUE_INFLUENCE_LIMIT,
|
|
enforceAt: CROSS_ISSUE_INFLUENCE_ENFORCE_AT.toISOString(),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Atomically observes one cross-issue influence attempt for a heartbeat run.
|
|
*
|
|
* Locking the run row serializes concurrent attempts from the same run. The
|
|
* observation is intentionally recorded before the route mutation: once the
|
|
* rollout reaches enforcement, failures cannot be used to race or probe past
|
|
* the fail-closed backstop.
|
|
*/
|
|
export async function observeCrossIssueInfluence(
|
|
db: Db,
|
|
input: {
|
|
companyId: string;
|
|
runId: string;
|
|
agentId: string;
|
|
responsibleUserId?: string | null;
|
|
targetIssueId: string;
|
|
targetIssueIdentifier?: string | null;
|
|
kind: CrossIssueInfluenceKind;
|
|
now?: Date;
|
|
},
|
|
): Promise<CrossIssueInfluenceDecision | null> {
|
|
// API-key callers control the run header. Reject malformed UUIDs before the
|
|
// database can turn an untrusted identifier into a PostgreSQL cast error.
|
|
if (!isUuidLike(input.runId)) throw crossIssueInfluenceRunContextError();
|
|
|
|
return db.transaction(async (tx) => {
|
|
const run = await tx
|
|
.select({
|
|
id: heartbeatRuns.id,
|
|
companyId: heartbeatRuns.companyId,
|
|
agentId: heartbeatRuns.agentId,
|
|
responsibleUserId: heartbeatRuns.responsibleUserId,
|
|
contextSnapshot: heartbeatRuns.contextSnapshot,
|
|
})
|
|
.from(heartbeatRuns)
|
|
.where(and(
|
|
eq(heartbeatRuns.id, input.runId),
|
|
eq(heartbeatRuns.companyId, input.companyId),
|
|
eq(heartbeatRuns.agentId, input.agentId),
|
|
))
|
|
.for("update")
|
|
.then((rows) => rows[0] ?? null);
|
|
if (
|
|
!run ||
|
|
run.companyId !== input.companyId ||
|
|
run.agentId !== input.agentId
|
|
) {
|
|
throw crossIssueInfluenceRunContextError();
|
|
}
|
|
|
|
// An unscoped run (timer heartbeat with no checked-out issue) has no source
|
|
// issue, so every issue write it makes is cross-issue by definition and
|
|
// spends the cap. The locked run row above is the attribution anchor;
|
|
// rejecting these writes as run-less left live heartbeat runs unable to
|
|
// comment or update any task at all.
|
|
const sourceIssueId = readRunSourceIssueId(run.contextSnapshot);
|
|
if (
|
|
sourceIssueId !== null &&
|
|
(sourceIssueId === input.targetIssueId ||
|
|
(input.targetIssueIdentifier && sourceIssueId.toUpperCase() === input.targetIssueIdentifier.toUpperCase()))
|
|
) {
|
|
return null;
|
|
}
|
|
|
|
const priorCount = await tx
|
|
.select({ count: count() })
|
|
.from(activityLog)
|
|
.where(and(
|
|
eq(activityLog.companyId, input.companyId),
|
|
eq(activityLog.runId, input.runId),
|
|
eq(activityLog.action, CROSS_ISSUE_INFLUENCE_ACTIVITY),
|
|
))
|
|
.then((rows) => Number(rows[0]?.count ?? 0));
|
|
const decision = evaluateCrossIssueInfluenceLimit({ priorCount, now: input.now });
|
|
|
|
await tx.insert(activityLog).values({
|
|
companyId: input.companyId,
|
|
actorType: "agent",
|
|
actorId: input.agentId,
|
|
agentId: input.agentId,
|
|
runId: input.runId,
|
|
responsibleUserId: input.responsibleUserId ?? run.responsibleUserId ?? null,
|
|
action: decision.allowed
|
|
? CROSS_ISSUE_INFLUENCE_ACTIVITY
|
|
: CROSS_ISSUE_INFLUENCE_REJECTED_ACTIVITY,
|
|
entityType: "issue",
|
|
entityId: input.targetIssueId,
|
|
details: {
|
|
kind: input.kind,
|
|
sourceIssueId,
|
|
targetIssueId: input.targetIssueId,
|
|
targetIssueIdentifier: input.targetIssueIdentifier ?? null,
|
|
count: decision.count,
|
|
cap: decision.cap,
|
|
mode: decision.mode,
|
|
enforceAt: decision.enforceAt,
|
|
allowed: decision.allowed,
|
|
},
|
|
});
|
|
|
|
const logContext = {
|
|
event: "cross_issue_influence_cap",
|
|
companyId: input.companyId,
|
|
runId: input.runId,
|
|
agentId: input.agentId,
|
|
sourceIssueId,
|
|
targetIssueId: input.targetIssueId,
|
|
kind: input.kind,
|
|
count: decision.count,
|
|
cap: decision.cap,
|
|
mode: decision.mode,
|
|
enforceAt: decision.enforceAt,
|
|
allowed: decision.allowed,
|
|
};
|
|
if (decision.allowed) {
|
|
logger.info(logContext, "cross-issue influence observed");
|
|
} else {
|
|
logger.warn(logContext, "cross-issue influence cap exceeded");
|
|
}
|
|
|
|
return decision;
|
|
});
|
|
}
|
|
|
|
export function crossIssueInfluenceLimitError(
|
|
decision: CrossIssueInfluenceDecision,
|
|
context: { actorLabel?: string | null; assigneeLabel?: string | null; issueIdentifier?: string | null } = {},
|
|
) {
|
|
// The cap is a rate backstop, not a permission decision — the shared copy
|
|
// contract says so explicitly, and names the next run as the way forward.
|
|
const { body } = issueWriteDenialResponse("cross_issue_influence_cap_exceeded", {
|
|
...context,
|
|
cap: decision.cap,
|
|
count: decision.count,
|
|
enforceAt: decision.enforceAt,
|
|
});
|
|
return {
|
|
error: body.error,
|
|
details: {
|
|
...body.details,
|
|
cap: decision.cap,
|
|
count: decision.count,
|
|
mode: decision.mode,
|
|
enforceAt: decision.enforceAt,
|
|
},
|
|
};
|
|
}
|