mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The `attention-retention` queue archives old attention items. One
kind is `blocker_attention`: a blocked task whose terminal blocker needs
a person.
> - When the queue loads a page of blocked tasks, it reads `keep` and
`archived_at` from `decision_retention` for each of them, one full-row
`select` per task.
> - A company hint walks every page. On a hosted instance with 2,112
blocker attention items and one active run, these per-task reads ran at
about 16 per second.
> - This pull request reads the retention state for the whole page in
one narrow statement. It also scopes three remaining run-path attention
hints to the task graph.
> - The benefit is one retention read per page instead of one per
blocked task, with the same decisions.
## Linked Issues or Issue Description
No issue exists. This describes the problem with the fields of
`.github/ISSUE_TEMPLATE/enhancement.yml`.
**What existing behavior does this improve?**
The `blocker_attention` eligibility read in
`server/src/services/attention-retention.ts` (`eligible()`), and three
run-path producers of company-wide attention hints.
**Subsystem affected**
Server background retention (`attention-retention.ts`,
`native-runtime/native-provider-capacity-retry.ts`,
`native-runtime/native-review-participant.ts`,
`native-runtime/native-workspace-reconstruction.ts`).
**Current behavior**
- For each blocked task whose blocker attention is terminal (and for the
owner variant), `eligible()` ran `select <all columns> from
decision_retention where company_id = $1 and source_kind = $2 and
source_id = $3`. It did this during `load`, once per task, on every
company hint.
- The hosted statement is identified by that column prefix: `id,
company_id, source_kind, source_id, source_activity_at, …`.
- I checked every other full-row reader of `decision_retention`. None
fires per run event:
- `syncItems`: attention summary and list requests, which a board calls
once per load; retention `check` and the sweep, which run for due
entries only; Keep and Archive actions.
- `getState`: user actions only.
- `archiveReviewedManifest`: proposal acceptance only.
- `decisions.list`: only when archive proposals exist.
- `native-provider-capacity-retry`, `native-review-participant` and
`native-workspace-reconstruction` sent `{ companyId }` attention hints,
which make the queue walk every page.
**Proposed behavior**
- `pageEvidence` reads `source_id`, `keep` and `archived_at` for every
blocker root and every terminal blocker on the page in one statement
(ids passed as one JSON parameter). `eligible()` uses that map when it
has page evidence.
- A missing row means "not kept, not archived", exactly as the per-task
read returning no row did.
- The per-entry `check` path still reads one row, now only `keep` and
`archived_at`.
- The three producers send `notifyIssueAttentionRetentionWork` with
their task (and run). That is the task, its parents and the tasks it
blocks, with a company fallback past 100.
- A capacity retry changes the failed-run items of its task.
- A review participant claim changes the review of its task.
- A workspace reconstruction resolves the recovery action of its task,
which can also change the blocker attention of the tasks it blocks.
- The configuration, lifecycle, import and fallback producers keep their
company hints.
**Reason and benefit**
Background work must not grow with the backlog. A page now costs one
retention read instead of up to 100.
## What Changed
- `server/src/services/attention-retention.ts`: batched and narrowed
blocker retention read; `PageEvidence.blockerRetention`.
-
`server/src/services/native-runtime/native-provider-capacity-retry.ts`,
`native-review-participant.ts`, `native-workspace-reconstruction.ts`:
scoped attention hints.
- Tests in `server/src/__tests__/attention-retention-work.test.ts` and
`server/src/services/native-runtime/native-workspace-reconstruction.test.ts`.
## Verification
- `reads blocker retention state once per page, not once per blocked
task` (I saw it fail first). 160 blocked tasks, each behind its own
unassigned blocker; the blockers' retention rows are kept (40), archived
(40), plain (40) or missing (40). The full-size response capture and the
statement log measure the load of both pages:
- before: one `decision_retention` read per task (160), 26,240 result
bytes;
- after: 2 reads (one per page), 5,480 bytes, none of them selecting
`source_activity_at`.
- The same tasks are listed: only plain and missing.
- `check` still drops the kept and archived ones.
- `scopes the attention retention hint of a reconstruction to the task
graph` (I saw it fail first): before, the reconstruction sent `{
companyId }`; after, it sends a hint that names the task.
- `batches 100 blocker graphs with exact terminal timestamps and fresh
terminal visibility` pinned 200 retention reads per page (one per root
and variant). It now expects 1; the rest of that test is unchanged and
passes.
- Not separately tested: the capacity-retry and review-participant hint
changes. Each is one line that passes the task the function already
holds, the same pattern as the reconstruction test.
- `attention-retention-work` (58), `attention-retention-candidates`,
`native-workspace-reconstruction`, `native-review-participant` and
`heartbeat-run-dispatch-work` pass, each file run alone (in `server/`,
against dedicated local `_test` databases).
- `pnpm check:module-boundaries` passes.
## Risks
- The page read happens once, before the per-entry decisions of that
page. Before, each decision read its row just in time. A Keep or Archive
that lands between the page read and an entry's decision is seen by the
next load or by `check`, which re-reads under a row lock, as before.
- A run-path hint that changes more than its task graph would now miss
the wider effect. The 90-day archive delay makes a missed reload cheap.
- No schema change.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code
execution in 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
- [ ] 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
- [ ] 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>
259 lines
11 KiB
TypeScript
259 lines
11 KiB
TypeScript
import { notifyStatusCardIssueChange } from "../status-card-notifications.js";
|
|
import { notifyIssueAttentionRetentionWork } from "../retention-work-notifications.js";
|
|
import {
|
|
agents,
|
|
heartbeatRuns,
|
|
issueThreadInteractions,
|
|
issues,
|
|
statusDecisions,
|
|
type Db,
|
|
} from "@paperclipai/db";
|
|
import { and, eq, isNull, or } from "drizzle-orm";
|
|
import { evaluateAgentInvokabilityFromDb } from "../agent-invokability.js";
|
|
import { canonicalizeStoredResolverPolicy } from "../issue-thread-interaction-resolution.js";
|
|
|
|
export type NativeReviewAssignmentContext = {
|
|
nativeReviewInteractionId: string;
|
|
nativeReviewDecisionId: string;
|
|
};
|
|
|
|
type ReviewPayload = {
|
|
version?: number;
|
|
prompt?: string;
|
|
target?: { type?: string; key?: string; revisionId?: string } | null;
|
|
toolAction?: unknown;
|
|
secretProposal?: unknown;
|
|
};
|
|
type InteractionFacts = Pick<typeof issueThreadInteractions.$inferSelect,
|
|
"id" | "companyId" | "issueId" | "kind" | "status" | "sourceRunId" | "addresseeAgentId" |
|
|
"addresseeUserId" | "effectiveResolverPolicy" | "resolverPolicyProvenance" |
|
|
"resolvedByAgentId" | "resolvedByRunId"> & { payload: ReviewPayload };
|
|
type DecisionFacts = Pick<typeof statusDecisions.$inferSelect,
|
|
"id" | "companyId" | "issueId" | "runId" | "decisionJson" | "applicationState">;
|
|
type SourceRunFacts = Pick<typeof heartbeatRuns.$inferSelect,
|
|
"id" | "companyId" | "agentId" | "nativeIssueId">;
|
|
|
|
export type NativeReviewAssignmentFacts = {
|
|
companyId: string;
|
|
issueId: string;
|
|
agentId: string;
|
|
issueStatus: string;
|
|
issueStatusVersion: number;
|
|
issueLastStatusDecisionId: string | null;
|
|
issueAssigneeAgentId: string | null;
|
|
issueExecutionRunId?: string | null;
|
|
interaction: InteractionFacts;
|
|
decision: DecisionFacts;
|
|
sourceRun: SourceRunFacts;
|
|
agentInvokable: boolean;
|
|
actingRun?: {
|
|
id: string;
|
|
companyId: string;
|
|
agentId: string;
|
|
status: string;
|
|
nativeIssueId: string | null;
|
|
contextSnapshot: Record<string, unknown> | null;
|
|
};
|
|
allowResolvedByRunId?: string;
|
|
};
|
|
|
|
export type NativeReviewAssignment = {
|
|
interaction: typeof issueThreadInteractions.$inferSelect;
|
|
sourceDecision: typeof statusDecisions.$inferSelect;
|
|
sourceRun: typeof heartbeatRuns.$inferSelect;
|
|
};
|
|
|
|
export function readNativeReviewAssignmentContext(
|
|
snapshot: unknown,
|
|
): NativeReviewAssignmentContext | null {
|
|
if (!snapshot || typeof snapshot !== "object") return null;
|
|
const value = snapshot as Record<string, unknown>;
|
|
const interactionId = value.nativeReviewInteractionId;
|
|
const decisionId = value.nativeReviewDecisionId;
|
|
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
if (typeof interactionId !== "string" || !uuid.test(interactionId)) return null;
|
|
if (typeof decisionId !== "string" || !uuid.test(decisionId)) return null;
|
|
return { nativeReviewInteractionId: interactionId, nativeReviewDecisionId: decisionId };
|
|
}
|
|
|
|
function isNativeCompletionReview(interaction: InteractionFacts, decisionId: string) {
|
|
const target = interaction.payload?.target;
|
|
return target?.type === "custom"
|
|
&& target.key === "native_completion_review"
|
|
&& target.revisionId === decisionId;
|
|
}
|
|
|
|
export function validateNativeReviewAssignmentFacts(input: NativeReviewAssignmentFacts): boolean {
|
|
const { interaction, decision, sourceRun } = input;
|
|
if (!input.agentInvokable) return false;
|
|
if (input.issueAssigneeAgentId !== sourceRun?.agentId) return false;
|
|
if (sourceRun?.agentId === input.agentId) return false;
|
|
if (!interaction || interaction.companyId !== input.companyId || interaction.issueId !== input.issueId) return false;
|
|
if (!decision || decision.companyId !== input.companyId || decision.issueId !== input.issueId) return false;
|
|
if (decision.applicationState !== "applied") return false;
|
|
if (!sourceRun || sourceRun.companyId !== input.companyId || sourceRun.nativeIssueId !== input.issueId) return false;
|
|
if (interaction.kind !== "request_confirmation") return false;
|
|
if (interaction.sourceRunId !== decision.runId || interaction.sourceRunId !== sourceRun.id) return false;
|
|
if (interaction.addresseeAgentId !== input.agentId) return false;
|
|
if (interaction.addresseeUserId) return false;
|
|
if (interaction.payload?.toolAction || interaction.payload?.secretProposal) return false;
|
|
if (!isNativeCompletionReview(interaction, decision.id)) return false;
|
|
|
|
if (input.actingRun) {
|
|
const actingContext = readNativeReviewAssignmentContext(
|
|
input.actingRun.contextSnapshot,
|
|
);
|
|
if (
|
|
input.actingRun.id.length === 0 ||
|
|
input.actingRun.companyId !== input.companyId ||
|
|
input.actingRun.agentId !== input.agentId ||
|
|
input.actingRun.status !== "running" ||
|
|
input.actingRun.nativeIssueId !== input.issueId ||
|
|
(input.issueExecutionRunId !== undefined &&
|
|
input.issueExecutionRunId !== input.actingRun.id) ||
|
|
!actingContext ||
|
|
actingContext.nativeReviewInteractionId !== interaction.id ||
|
|
actingContext.nativeReviewDecisionId !== decision.id
|
|
) return false;
|
|
const context = input.actingRun.contextSnapshot ?? {};
|
|
if (context.issueId !== undefined && context.issueId !== input.issueId)
|
|
return false;
|
|
if (context.sourceRunId !== undefined && context.sourceRunId !== sourceRun.id)
|
|
return false;
|
|
if (context.revisionId !== undefined && context.revisionId !== decision.id)
|
|
return false;
|
|
}
|
|
|
|
const policy = canonicalizeStoredResolverPolicy(
|
|
interaction.effectiveResolverPolicy,
|
|
interaction.resolverPolicyProvenance,
|
|
);
|
|
if (policy === "human_only") return false;
|
|
if (interaction.status === "pending") {
|
|
if (input.issueStatus !== "in_review") return false;
|
|
if (input.issueLastStatusDecisionId !== decision.id) return false;
|
|
const projected = Number(decision.decisionJson?.projectedStatusVersion);
|
|
return Number.isFinite(projected) && input.issueStatusVersion === projected;
|
|
}
|
|
return (interaction.status === "accepted" || interaction.status === "rejected")
|
|
&& typeof input.allowResolvedByRunId === "string"
|
|
&& interaction.resolvedByRunId === input.allowResolvedByRunId
|
|
&& interaction.resolvedByAgentId === input.agentId;
|
|
}
|
|
|
|
export async function getNativeReviewAssignment(
|
|
db: Db,
|
|
input: {
|
|
companyId: string;
|
|
issueId: string;
|
|
agentId: string;
|
|
contextSnapshot: unknown;
|
|
actingRunId?: string;
|
|
issueExecutionRunId?: string | null;
|
|
allowResolvedByRunId?: string;
|
|
},
|
|
): Promise<NativeReviewAssignment | null> {
|
|
const context = readNativeReviewAssignmentContext(input.contextSnapshot);
|
|
if (!context) return null;
|
|
const issue = await db.select().from(issues).where(and(
|
|
eq(issues.companyId, input.companyId), eq(issues.id, input.issueId),
|
|
)).limit(1).then((rows) => rows[0] ?? null);
|
|
const agent = await db.select().from(agents).where(and(
|
|
eq(agents.companyId, input.companyId), eq(agents.id, input.agentId),
|
|
)).limit(1).then((rows) => rows[0] ?? null);
|
|
if (!issue || !agent) return null;
|
|
const interaction = await db.select().from(issueThreadInteractions).where(and(
|
|
eq(issueThreadInteractions.id, context.nativeReviewInteractionId),
|
|
eq(issueThreadInteractions.companyId, input.companyId),
|
|
eq(issueThreadInteractions.issueId, input.issueId),
|
|
)).limit(1).then((rows) => rows[0] ?? null);
|
|
const decision = await db.select().from(statusDecisions).where(and(
|
|
eq(statusDecisions.id, context.nativeReviewDecisionId),
|
|
eq(statusDecisions.companyId, input.companyId),
|
|
eq(statusDecisions.issueId, input.issueId),
|
|
)).limit(1).then((rows) => rows[0] ?? null);
|
|
if (!interaction || !decision) return null;
|
|
const sourceRun = await db.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.id, decision.runId),
|
|
eq(heartbeatRuns.companyId, input.companyId),
|
|
eq(heartbeatRuns.agentId, issue.assigneeAgentId ?? "00000000-0000-0000-0000-000000000000"),
|
|
eq(heartbeatRuns.nativeIssueId, input.issueId),
|
|
)).limit(1).then((rows) => rows[0] ?? null);
|
|
if (!sourceRun) return null;
|
|
const actingRun = input.actingRunId
|
|
? await db.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.id, input.actingRunId),
|
|
eq(heartbeatRuns.companyId, input.companyId),
|
|
eq(heartbeatRuns.agentId, input.agentId),
|
|
)).limit(1).then((rows) => rows[0] ?? null)
|
|
: undefined;
|
|
if (input.actingRunId && !actingRun) return null;
|
|
const invokability = await evaluateAgentInvokabilityFromDb(db, agent);
|
|
const valid = validateNativeReviewAssignmentFacts({
|
|
companyId: input.companyId,
|
|
issueId: input.issueId,
|
|
agentId: input.agentId,
|
|
issueStatus: issue.status,
|
|
issueStatusVersion: Number(issue.statusVersion),
|
|
issueLastStatusDecisionId: issue.lastStatusDecisionId,
|
|
issueAssigneeAgentId: issue.assigneeAgentId,
|
|
interaction: interaction as InteractionFacts,
|
|
decision,
|
|
sourceRun,
|
|
agentInvokable: invokability.invokable,
|
|
actingRun: actingRun
|
|
? {
|
|
id: actingRun.id,
|
|
companyId: actingRun.companyId,
|
|
agentId: actingRun.agentId,
|
|
status: actingRun.status,
|
|
nativeIssueId: actingRun.nativeIssueId,
|
|
contextSnapshot: actingRun.contextSnapshot,
|
|
}
|
|
: undefined,
|
|
issueExecutionRunId: input.issueExecutionRunId,
|
|
allowResolvedByRunId: input.allowResolvedByRunId,
|
|
});
|
|
return valid ? { interaction, sourceDecision: decision, sourceRun } : null;
|
|
}
|
|
|
|
|
|
/** Claim the normal issue execution lock without changing the worker assignee. */
|
|
export async function claimNativeReviewExecutionLock(db: Db, input: {
|
|
companyId: string;
|
|
issueId: string;
|
|
agentId: string;
|
|
runId: string;
|
|
contextSnapshot: unknown;
|
|
agentNameKey: string | null;
|
|
claimedAt: Date;
|
|
}): Promise<boolean> {
|
|
return db.transaction(async (tx) => {
|
|
const issue = await tx.select({ id: issues.id }).from(issues).where(and(
|
|
eq(issues.id, input.issueId), eq(issues.companyId, input.companyId),
|
|
)).for("update").limit(1).then((rows) => rows[0]);
|
|
if (!issue || !await getNativeReviewAssignment(tx as unknown as Db, input)) return false;
|
|
const run = await tx.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId),
|
|
eq(heartbeatRuns.agentId, input.agentId),
|
|
)).limit(1).then((rows) => rows[0]);
|
|
const admitted = readNativeReviewAssignmentContext(run?.contextSnapshot);
|
|
const expected = readNativeReviewAssignmentContext(input.contextSnapshot);
|
|
if (!run || !["queued", "running"].includes(run.status) || !admitted || !expected
|
|
|| admitted.nativeReviewInteractionId !== expected.nativeReviewInteractionId
|
|
|| admitted.nativeReviewDecisionId !== expected.nativeReviewDecisionId) return false;
|
|
await notifyStatusCardIssueChange(tx, input.companyId);
|
|
await notifyIssueAttentionRetentionWork(tx, { companyId: input.companyId, issueId: input.issueId, runId: input.runId });
|
|
const claimed = await tx.update(issues).set({
|
|
executionRunId: input.runId,
|
|
executionAgentNameKey: input.agentNameKey,
|
|
executionLockedAt: input.claimedAt,
|
|
updatedAt: input.claimedAt,
|
|
}).where(and(
|
|
eq(issues.id, input.issueId), eq(issues.companyId, input.companyId),
|
|
or(isNull(issues.executionRunId), eq(issues.executionRunId, input.runId)),
|
|
)).returning({ id: issues.id });
|
|
return claimed.length === 1;
|
|
});
|
|
}
|