mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-26 18:31:34 +01:00
feat(decisions): add desk workflow and retention (#10672)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Decisions desk shows work that needs a human decision > - The queue foundation can group and rank decision work > - Operators also need a focused daily view and a safe way to handle old work > - This pull request adds the desk controls, the aging shelf, and reversible retention > - It also binds bulk archive decisions to the exact reviewed item set > - The benefit is a smaller daily queue without lost or orphaned work ## Linked Issues or Issue Description **Subsystem affected** Cross-cutting: server, UI, database, and shared contracts. **Problem or motivation** Decision work can grow into one large company list. Operators need quick queue and date controls. Old items also need a safe retention path that does not delete work. **Proposed solution** Add queue and date controls to the Decisions desk. Compute the aging shelf on the server. Archive idle items after 90 days unless an operator keeps them. Keep archived items searchable and revivable. Notify origin agents in one batch per sweep. Bind bulk archive proposals to a signed, exact item manifest. **Alternatives considered** Client-only aging can drift across browsers and source kinds. Deleting old rows removes audit and recovery paths. An unsigned dynamic bulk query can archive items that the reviewer did not inspect. **Roadmap alignment** This work supports the Work Queues and decision-memory directions in `ROADMAP.md`. It extends the Decisions and attention-feed foundation from #10651. Related earlier work includes #9380, #10010, and #10474. ## What Changed - Added the queue rail, date chips, decide split, triage strip, queue page, and aging shelf UI. - Added server-owned shelf state with per-queue retention overrides. - Added reversible retention state, archive history, and an idempotent notification outbox. - Added the 90-day archive sweeper, Keep exemption, archived feed query, and revive actions. - Added one origin-agent notification per agent and sweep. - Added signed bulk archive proposals with exact-set and version checks. - Persisted queue-exclusion reasons atomically and kept cross-domain source resolution per-item until it has an exact-set transaction contract. - Added API contracts, OpenAPI entries, migration coverage, focused tests, and Storybook screens. ## Verification - `pnpm -r typecheck` - `pnpm test:run` (server: 329 files and 3,453 tests passed; UI: 408 files and 3,362 tests passed) - `env -u AWS_ACCESS_KEY_ID -u AWS_SECRET_ACCESS_KEY pnpm exec vitest run cli/src/__tests__/secrets.test.ts` - `pnpm build` - `pnpm check:token-gates` - Focused retention, attention, decisions, migration replay, startup, and UI API tests. - Complete queue snapshot regression with 51 items across the normal 50-item page boundary. The unmodified CLI test reports one warning assertion in this runtime because the harness injects static AWS credential variables. The isolated test passes when those two variables are removed. ## Risks - The migration adds retention and notification outbox tables. It uses idempotent table, index, and foreign-key creation. - Retention runs on the heartbeat scheduler interval. Compare-and-set version checks prevent stale archive writes. - Bulk archive acceptance fails closed when authority, activity, version, or the reviewed set changes. - Archive is reversible and does not delete source records. > 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 OpenAI Codex with `gpt-5.6-sol`. The model used tool calls, code execution, database migration generation, and test execution. The context-window size is not exposed in this runtime. ## 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 - [x] All Paperclip CI gates are green - [x] 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: Claude Opus 4.8 <noreply@anthropic.com> Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
46 files changed
+41814
-71
No files matched your search
@@ -14,6 +14,8 @@ import {
|
||||
createDb,
|
||||
decisionQueueItems,
|
||||
decisionQueues,
|
||||
decisionArchiveNotificationOutbox,
|
||||
decisionRetention,
|
||||
decisions,
|
||||
decisionTriage,
|
||||
decisionTriageEvents,
|
||||
@@ -62,6 +64,8 @@ describeEmbeddedPostgres("attention service", () => {
|
||||
|
||||
afterEach(async () => {
|
||||
await db.delete(inboxDismissals);
|
||||
await db.delete(decisionArchiveNotificationOutbox);
|
||||
await db.delete(decisionRetention);
|
||||
await db.delete(decisionTriageEvents);
|
||||
await db.delete(decisionTriage);
|
||||
await db.delete(decisionQueueItems);
|
||||
@@ -1237,6 +1241,15 @@ describeEmbeddedPostgres("attention service", () => {
|
||||
expect(secondPage.items.map((item) => item.subject.id)).toEqual([expiringLaterId]);
|
||||
expect(secondPage.nextCursor).toBeNull();
|
||||
|
||||
const completeSnapshot = await attentionService(db).list(companyId, {
|
||||
userId: "board-user",
|
||||
queue: "urgent-releases",
|
||||
sort: "decide",
|
||||
all: true,
|
||||
});
|
||||
expect(completeSnapshot.items.map((item) => item.subject.id)).toEqual([expiringSoonId, expiringLaterId]);
|
||||
expect(completeSnapshot.nextCursor).toBeNull();
|
||||
|
||||
const dateFiltered = await attentionService(db).list(companyId, {
|
||||
userId: "board-user",
|
||||
queue: "urgent-releases",
|
||||
@@ -1254,6 +1267,73 @@ describeEmbeddedPostgres("attention service", () => {
|
||||
.toBe(new Date(now + 60 * 60_000).toISOString());
|
||||
});
|
||||
|
||||
it("returns a complete queue snapshot beyond the normal page limit", async () => {
|
||||
const { companyId } = await seedCompany("ATS");
|
||||
const queueId = randomUUID();
|
||||
await db.insert(decisionQueues).values({
|
||||
id: queueId,
|
||||
companyId,
|
||||
key: "bulk-review",
|
||||
title: "Bulk review",
|
||||
createdByType: "user",
|
||||
createdByUserId: "board-user",
|
||||
});
|
||||
|
||||
const approvalRows = Array.from({ length: 101 }, (_, index) => ({
|
||||
id: randomUUID(),
|
||||
companyId,
|
||||
type: "hire_agent",
|
||||
status: "pending",
|
||||
payload: { title: `Review ${index + 1}` },
|
||||
createdAt: new Date(Date.UTC(2026, 7, 2, 12, 0, index)),
|
||||
updatedAt: new Date(Date.UTC(2026, 7, 2, 12, 0, index)),
|
||||
}));
|
||||
await db.insert(approvals).values(approvalRows);
|
||||
await db.insert(decisionQueueItems).values(approvalRows.map((approval) => ({
|
||||
companyId,
|
||||
queueId,
|
||||
sourceKind: "approval",
|
||||
sourceId: approval.id,
|
||||
addedByType: "user",
|
||||
addedByUserId: "board-user",
|
||||
})));
|
||||
|
||||
const firstPage = await attentionService(db).list(companyId, {
|
||||
userId: "board-user",
|
||||
queue: "bulk-review",
|
||||
});
|
||||
expect(firstPage.items).toHaveLength(50);
|
||||
expect(firstPage.nextCursor).toBeTruthy();
|
||||
|
||||
const completeSnapshot = await attentionService(db).list(companyId, {
|
||||
userId: "board-user",
|
||||
queue: "bulk-review",
|
||||
all: true,
|
||||
});
|
||||
expect(completeSnapshot.items).toHaveLength(101);
|
||||
expect(new Set(completeSnapshot.items.map((item) => item.id)).size).toBe(101);
|
||||
expect(completeSnapshot.nextCursor).toBeNull();
|
||||
|
||||
const internalSnapshot = await attentionService(db).list(companyId, {
|
||||
userId: "board-user",
|
||||
all: true,
|
||||
allowUnscopedAll: true,
|
||||
});
|
||||
const internalSnapshotIds = new Set(internalSnapshot.items.map((item) => item.subject.id));
|
||||
expect(approvalRows.every((approval) => internalSnapshotIds.has(approval.id))).toBe(true);
|
||||
expect(internalSnapshot.items.length).toBeGreaterThan(100);
|
||||
expect(internalSnapshot.nextCursor).toBeNull();
|
||||
|
||||
await expect(attentionService(db).list(companyId, { userId: "board-user", all: true }))
|
||||
.rejects.toThrow("all requires a queue filter");
|
||||
await expect(attentionService(db).list(companyId, {
|
||||
userId: "board-user",
|
||||
queue: "bulk-review",
|
||||
all: true,
|
||||
limit: 25,
|
||||
})).rejects.toThrow("all cannot be combined with cursor or limit");
|
||||
});
|
||||
|
||||
it("keeps this-week deadlines in the current UTC week", async () => {
|
||||
const { companyId, workerId } = await seedCompany("ATW");
|
||||
const now = Date.parse("2026-08-02T12:00:00.000Z"); // Sunday in an ISO Monday-Sunday week.
|
||||
@@ -1370,4 +1450,93 @@ describeEmbeddedPostgres("attention service", () => {
|
||||
.expect(400, { error: "sort must be 'activity' or 'decide'" });
|
||||
await request(app(agent)).get(`/api/companies/${companyId}/attention`).expect(403);
|
||||
});
|
||||
|
||||
it("computes the aging shelf uniformly across approval, interaction, and review sources", async () => {
|
||||
const { companyId, workerId } = await seedCompany("AGE");
|
||||
const now = Date.parse("2026-08-02T12:00:00.000Z");
|
||||
const idleAt = new Date("2026-06-30T12:00:00.000Z");
|
||||
const interactionIssueId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "AGE-1",
|
||||
title: "Old questions",
|
||||
status: "in_progress",
|
||||
assigneeAgentId: workerId,
|
||||
createdAt: idleAt,
|
||||
updatedAt: idleAt,
|
||||
});
|
||||
const reviewIssueId = await insertIssue({
|
||||
companyId,
|
||||
identifier: "AGE-2",
|
||||
title: "Old review",
|
||||
status: "in_review",
|
||||
assigneeUserId: "board-user",
|
||||
createdAt: idleAt,
|
||||
updatedAt: idleAt,
|
||||
});
|
||||
const approvalId = randomUUID();
|
||||
const queueApprovalId = randomUUID();
|
||||
const interactionId = randomUUID();
|
||||
const queueIdleAt = new Date("2026-07-18T12:00:00.000Z");
|
||||
await db.insert(approvals).values([
|
||||
{
|
||||
id: approvalId,
|
||||
companyId,
|
||||
type: "request_board_approval",
|
||||
requestedByAgentId: workerId,
|
||||
status: "pending",
|
||||
payload: { title: "Old approval" },
|
||||
createdAt: idleAt,
|
||||
updatedAt: idleAt,
|
||||
},
|
||||
{
|
||||
id: queueApprovalId,
|
||||
companyId,
|
||||
type: "request_board_approval",
|
||||
requestedByAgentId: workerId,
|
||||
status: "pending",
|
||||
payload: { title: "Queue-retained approval" },
|
||||
createdAt: queueIdleAt,
|
||||
updatedAt: queueIdleAt,
|
||||
},
|
||||
]);
|
||||
await db.insert(issueThreadInteractions).values({
|
||||
id: interactionId,
|
||||
companyId,
|
||||
issueId: interactionIssueId,
|
||||
kind: "ask_user_questions",
|
||||
status: "pending",
|
||||
createdByAgentId: workerId,
|
||||
payload: { version: 1, questions: [] },
|
||||
createdAt: idleAt,
|
||||
updatedAt: idleAt,
|
||||
});
|
||||
const [queue] = await db.insert(decisionQueues).values({
|
||||
companyId,
|
||||
key: "fast-aging",
|
||||
title: "Fast aging",
|
||||
retentionDays: 10,
|
||||
createdByType: "system",
|
||||
}).returning();
|
||||
await db.insert(decisionQueueItems).values({
|
||||
companyId,
|
||||
queueId: queue!.id,
|
||||
sourceKind: "approval",
|
||||
sourceId: queueApprovalId,
|
||||
addedByType: "system",
|
||||
});
|
||||
|
||||
const feed = await attentionService(db, { now: () => now }).list(companyId, {
|
||||
userId: "board-user",
|
||||
limit: 100,
|
||||
});
|
||||
const byKey = new Map(feed.items.map((item) => [`${item.sourceKind}:${item.subject.id}`, item]));
|
||||
for (const key of [
|
||||
`approval:${approvalId}`,
|
||||
`issue_thread_interaction:${interactionId}`,
|
||||
`review:${reviewIssueId}`,
|
||||
]) {
|
||||
expect(byKey.get(key)).toMatchObject({ shelf: true, retentionDays: 30, archivedAt: null });
|
||||
}
|
||||
expect(byKey.get(`approval:${queueApprovalId}`)).toMatchObject({ shelf: true, retentionDays: 10 });
|
||||
});
|
||||
});
|
||||
@@ -230,11 +230,28 @@ describeEmbeddedPostgres("decision queue routes", () => {
|
||||
|
||||
await request(app(board))
|
||||
.delete(`/api/companies/${companyId}/decision-queues/triage/items/review/${issueId}`)
|
||||
.send({ reason: "Handled in the release review" })
|
||||
.expect(200);
|
||||
expect(await db.select().from(decisionQueueItems).where(and(
|
||||
eq(decisionQueueItems.companyId, companyId),
|
||||
eq(decisionQueueItems.sourceKind, "review"),
|
||||
))).toHaveLength(0);
|
||||
const removalAudit = await db.select().from(activityLog).where(and(
|
||||
eq(activityLog.companyId, companyId),
|
||||
eq(activityLog.action, "decision_queue_item.removed"),
|
||||
)).then((rows) => rows[0]);
|
||||
expect(removalAudit?.details).toMatchObject({
|
||||
sourceKind: "review",
|
||||
sourceId: issueId,
|
||||
reason: "Handled in the release review",
|
||||
});
|
||||
const removalEvent = await db.select().from(decisionTriageEvents).where(and(
|
||||
eq(decisionTriageEvents.companyId, companyId),
|
||||
eq(decisionTriageEvents.sourceKind, "review"),
|
||||
eq(decisionTriageEvents.sourceId, issueId),
|
||||
eq(decisionTriageEvents.action, "queue_item.removed"),
|
||||
)).then((rows) => rows[0]);
|
||||
expect(removalEvent?.details).toEqual({ reason: "Handled in the release review" });
|
||||
|
||||
await db.delete(approvals).where(eq(approvals.id, approvalId));
|
||||
await request(app(board))
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import {
|
||||
activityLog,
|
||||
agents,
|
||||
companies,
|
||||
createDb,
|
||||
decisionArchiveNotificationOutbox,
|
||||
decisionRetention,
|
||||
issues,
|
||||
} from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { attentionService } from "../services/attention.js";
|
||||
import { decisionRetentionService } from "../services/decision-retention.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
const describePg = support.supported ? describe : describe.skip;
|
||||
|
||||
describePg("decision retention", () => {
|
||||
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
|
||||
beforeAll(async () => {
|
||||
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-decision-retention-");
|
||||
db = createDb(tempDb.connectionString);
|
||||
}, 30_000);
|
||||
|
||||
afterEach(async () => {
|
||||
await db.delete(decisionArchiveNotificationOutbox);
|
||||
await db.delete(decisionRetention);
|
||||
await db.delete(activityLog);
|
||||
await db.delete(issues);
|
||||
await db.delete(agents);
|
||||
await db.delete(companies);
|
||||
});
|
||||
|
||||
afterAll(async () => tempDb?.cleanup());
|
||||
|
||||
async function seedReviewItems(count: number) {
|
||||
const companyId = randomUUID();
|
||||
const agentId = randomUUID();
|
||||
await db.insert(companies).values({
|
||||
id: companyId,
|
||||
name: "Retention",
|
||||
issuePrefix: `R${companyId.slice(0, 6)}`,
|
||||
requireBoardApprovalForNewAgents: false,
|
||||
});
|
||||
await db.insert(agents).values({
|
||||
id: agentId,
|
||||
companyId,
|
||||
name: "Origin",
|
||||
role: "engineer",
|
||||
status: "active",
|
||||
adapterType: "codex_local",
|
||||
adapterConfig: {},
|
||||
runtimeConfig: {},
|
||||
permissions: {},
|
||||
});
|
||||
const old = new Date("2026-04-01T00:00:00.000Z");
|
||||
const issueIds = Array.from({ length: count }, () => randomUUID());
|
||||
await db.insert(issues).values(issueIds.map((id, index) => ({
|
||||
id,
|
||||
companyId,
|
||||
identifier: `RET-${index + 1}`,
|
||||
title: `Old review ${index + 1}`,
|
||||
status: "in_review",
|
||||
priority: "medium",
|
||||
assigneeUserId: "board-user",
|
||||
createdByAgentId: agentId,
|
||||
createdAt: old,
|
||||
updatedAt: old,
|
||||
})));
|
||||
return { companyId, agentId, issueIds };
|
||||
}
|
||||
|
||||
const boardActor = (companyId: string) => ({
|
||||
type: "board" as const,
|
||||
source: "local_implicit" as const,
|
||||
userId: "board-user",
|
||||
companyIds: [companyId],
|
||||
isInstanceAdmin: true,
|
||||
});
|
||||
const mutationActor = {
|
||||
actorType: "user" as const,
|
||||
actorId: "board-user",
|
||||
agentId: null,
|
||||
userId: "board-user",
|
||||
runId: null,
|
||||
agentApiKeyId: null,
|
||||
responsibleUserId: "board-user",
|
||||
};
|
||||
|
||||
it("auto-archives, excludes by default, returns archived rows, and revives", async () => {
|
||||
const { companyId, issueIds } = await seedReviewItems(1);
|
||||
const now = new Date("2026-08-02T00:00:00.000Z");
|
||||
const svc = decisionRetentionService(db);
|
||||
const before = await attentionService(db, { now: () => now.getTime() }).list(companyId, { limit: 100 });
|
||||
expect(before.items).toHaveLength(1);
|
||||
|
||||
expect(await svc.autoArchive({ companyId, items: before.items, now })).toBe(1);
|
||||
const current = await attentionService(db, { now: () => now.getTime() }).list(companyId, { limit: 100 });
|
||||
expect(current.items).toHaveLength(0);
|
||||
const archived = await attentionService(db, { now: () => now.getTime() }).list(companyId, { archived: true, limit: 100 });
|
||||
expect(archived.items[0]).toMatchObject({ subject: { id: issueIds[0] }, archivedAt: now.toISOString() });
|
||||
|
||||
await svc.revive({
|
||||
companyId,
|
||||
sourceKind: "review",
|
||||
sourceId: issueIds[0]!,
|
||||
authActor: boardActor(companyId),
|
||||
actor: mutationActor,
|
||||
});
|
||||
const revived = await attentionService(db, { now: () => now.getTime() }).list(companyId, { limit: 100 });
|
||||
expect(revived.items[0]).toMatchObject({ subject: { id: issueIds[0] }, archivedAt: null });
|
||||
});
|
||||
|
||||
it("exempts Keep rows and batches one notification per origin agent", async () => {
|
||||
const { companyId, agentId, issueIds } = await seedReviewItems(3);
|
||||
const now = new Date("2026-08-02T00:00:00.000Z");
|
||||
const notifications: Array<Record<string, unknown>> = [];
|
||||
const svc = decisionRetentionService(db, { notifyOriginAgent: async (batch) => notifications.push(batch) });
|
||||
await attentionService(db, { now: () => now.getTime() }).list(companyId, { limit: 100 });
|
||||
await svc.setKeep({
|
||||
companyId,
|
||||
sourceKind: "review",
|
||||
sourceId: issueIds[0]!,
|
||||
keep: true,
|
||||
authActor: boardActor(companyId),
|
||||
actor: mutationActor,
|
||||
});
|
||||
const refreshed = await attentionService(db, { now: () => now.getTime() }).list(companyId, { limit: 100 });
|
||||
expect(await svc.autoArchive({ companyId, items: refreshed.items, now })).toBe(2);
|
||||
expect(await svc.deliverNotifications()).toEqual({ notifiedAgents: 1, delivered: 2 });
|
||||
expect(notifications).toHaveLength(1);
|
||||
expect(notifications[0]).toMatchObject({ companyId, agentId, items: expect.arrayContaining([
|
||||
expect.objectContaining({ issueId: issueIds[1] }),
|
||||
expect.objectContaining({ issueId: issueIds[2] }),
|
||||
]) });
|
||||
expect((await svc.getState(companyId, "review", issueIds[0]!))?.archivedAt).toBeNull();
|
||||
});
|
||||
|
||||
it("fails the whole reviewed manifest when one expected version changes", async () => {
|
||||
const { companyId, issueIds } = await seedReviewItems(2);
|
||||
const now = Date.parse("2026-08-02T00:00:00.000Z");
|
||||
const svc = decisionRetentionService(db);
|
||||
const feed = await attentionService(db, { now: () => now }).list(companyId, { limit: 100 });
|
||||
const manifest = feed.items.map((item) => ({
|
||||
companyId,
|
||||
sourceKind: item.sourceKind,
|
||||
sourceId: item.subject.id,
|
||||
expectedVersion: item.retentionVersion,
|
||||
activityAt: item.activityAt,
|
||||
reason: "Reviewed as stale",
|
||||
}));
|
||||
await svc.setKeep({
|
||||
companyId,
|
||||
sourceKind: "review",
|
||||
sourceId: issueIds[0]!,
|
||||
keep: true,
|
||||
authActor: boardActor(companyId),
|
||||
actor: mutationActor,
|
||||
});
|
||||
await expect(svc.archiveReviewedManifest({
|
||||
companyId,
|
||||
manifest,
|
||||
originActor: boardActor(companyId),
|
||||
decidingActor: boardActor(companyId),
|
||||
decidedByUserId: "board-user",
|
||||
})).rejects.toThrow("archive_proposal_stale");
|
||||
expect((await db.select().from(decisionRetention)).every((row) => row.archivedAt === null)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
companyMemberships,
|
||||
createDb,
|
||||
decisionEffectExecutions,
|
||||
decisionRetention,
|
||||
decisions,
|
||||
decisionTargetIssues,
|
||||
heartbeatRuns,
|
||||
@@ -22,6 +23,8 @@ import {
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { attentionService } from "../services/attention.js";
|
||||
import { decisionService } from "../services/decisions.js";
|
||||
import { hashAttentionArchiveManifest } from "../services/decision-retention.js";
|
||||
import type { AttentionArchiveManifestEntry, AttentionArchiveTargetSnapshot } from "@paperclipai/shared";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
const describePg = support.supported ? describe : describe.skip;
|
||||
@@ -69,7 +72,7 @@ describePg("decisionService", () => {
|
||||
delete process.env.PAPERCLIP_DECISIONS_SWEEP_BATCH_SIZE;
|
||||
delete process.env.PAPERCLIP_DECISIONS_RECOVERY_GRACE_MS;
|
||||
delete process.env.PAPERCLIP_AGENT_JWT_SECRET;
|
||||
await db.delete(decisionEffectExecutions); await db.delete(decisionTargetIssues); await db.delete(decisions); await db.delete(activityLog);
|
||||
await db.delete(decisionEffectExecutions); await db.delete(decisionTargetIssues); await db.delete(decisions); await db.delete(decisionRetention); await db.delete(activityLog);
|
||||
await db.delete(issueComments); await db.delete(issueRelations); await db.delete(heartbeatRuns); await db.delete(issues); await db.delete(agents); await db.delete(companyMemberships); await db.delete(authUsers); await db.delete(companies);
|
||||
});
|
||||
afterAll(async () => tempDb?.cleanup());
|
||||
@@ -119,6 +122,64 @@ describePg("decisionService", () => {
|
||||
expect(await db.select().from(issueComments).where(eq(issueComments.issueId, targetIssueId))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("binds bulk archive acceptance to the exact signed, versioned manifest", async () => {
|
||||
const extraIssueId = randomUUID();
|
||||
const unreviewedIssueId = randomUUID();
|
||||
await db.insert(issues).values([
|
||||
{ id: extraIssueId, companyId, title: "Second aging item", status: "in_review", priority: "medium", createdByAgentId: agentId, assigneeUserId: decidedByUserId },
|
||||
{ id: unreviewedIssueId, companyId, title: "Not reviewed", status: "in_review", priority: "medium", createdByAgentId: agentId, assigneeUserId: decidedByUserId },
|
||||
]);
|
||||
const activityAt = new Date("2026-04-01T00:00:00.000Z");
|
||||
await db.insert(decisionRetention).values([targetIssueId, extraIssueId, unreviewedIssueId].map((sourceId) => ({
|
||||
companyId,
|
||||
sourceKind: "review",
|
||||
sourceId,
|
||||
sourceActivityAt: activityAt,
|
||||
})));
|
||||
const manifest: AttentionArchiveManifestEntry[] = [targetIssueId, extraIssueId].map((sourceId) => ({
|
||||
companyId,
|
||||
sourceKind: "review",
|
||||
sourceId,
|
||||
expectedVersion: 1,
|
||||
activityAt: activityAt.toISOString(),
|
||||
reason: `Archive ${sourceId}`,
|
||||
}));
|
||||
const snapshots = Object.fromEntries(manifest.map((entry) => [
|
||||
`attention:${entry.sourceKind}:${entry.sourceId}`,
|
||||
{
|
||||
status: "attention",
|
||||
assigneeAgentId: null,
|
||||
assigneeUserId: null,
|
||||
updatedAt: entry.activityAt,
|
||||
attentionArchive: entry,
|
||||
} satisfies AttentionArchiveTargetSnapshot,
|
||||
]));
|
||||
const created = await service().create({
|
||||
companyId,
|
||||
actor: agentActor(),
|
||||
agentId,
|
||||
runId,
|
||||
title: "Archive two?",
|
||||
body: "Reviewed exact set",
|
||||
options: [
|
||||
{ id: "archive", label: "Archive", style: "destructive", effects: [] },
|
||||
{ id: "keep", label: "Keep", effects: [] },
|
||||
],
|
||||
metadata: { kind: "attention_archive_proposal", manifestHash: hashAttentionArchiveManifest(manifest) },
|
||||
additionalTargetSnapshots: snapshots,
|
||||
});
|
||||
const result = await service().decide({
|
||||
id: created.id,
|
||||
optionId: "archive",
|
||||
decidedByUserId,
|
||||
userActor: boardActor(),
|
||||
});
|
||||
expect(result.executionStatus).toBe("succeeded");
|
||||
const states = await db.select().from(decisionRetention);
|
||||
expect(states.filter((row) => row.archivedAt).map((row) => row.sourceId).sort()).toEqual([extraIssueId, targetIssueId].sort());
|
||||
expect(states.find((row) => row.sourceId === unreviewedIssueId)?.archivedAt).toBeNull();
|
||||
});
|
||||
|
||||
it("skips strict stale targets and fails closed on intersection denial", async () => {
|
||||
const stale = await createCommentDecision("strict");
|
||||
await db.update(issues).set({ updatedAt: new Date(Date.now() + 1_000) }).where(eq(issues.id, targetIssueId));
|
||||
|
||||
@@ -29,7 +29,11 @@ const {
|
||||
} = vi.hoisted(() => {
|
||||
const createAppMock = vi.fn(async () => ((_: unknown, __: unknown) => {}) as never);
|
||||
const createBetterAuthInstanceMock = vi.fn(() => ({}));
|
||||
const createDbMock = vi.fn(() => ({}) as never);
|
||||
const createDbMock = vi.fn(() => ({
|
||||
select: vi.fn(() => ({
|
||||
from: vi.fn(() => ({ where: vi.fn(async () => []) })),
|
||||
})),
|
||||
}) as never);
|
||||
const detectPortMock = vi.fn(async (port: number) => port);
|
||||
const deriveAuthTrustedOriginsMock = vi.fn(() => []);
|
||||
const resolveHeartbeatSchedulingSuppressionMock = vi.fn(() => ({
|
||||
@@ -207,9 +211,16 @@ vi.mock("../services/index.js", () => ({
|
||||
agentMembershipsInserted: 0,
|
||||
humanGrantsInserted: 0,
|
||||
})),
|
||||
attentionService: vi.fn(() => ({
|
||||
list: vi.fn(async () => ({ items: [], nextCursor: null })),
|
||||
})),
|
||||
decisionService: vi.fn(() => ({
|
||||
sweepExpired: vi.fn(async () => ({ expired: 0 })),
|
||||
})),
|
||||
decisionRetentionService: vi.fn(() => ({
|
||||
autoArchive: vi.fn(async () => 0),
|
||||
deliverNotifications: vi.fn(async () => ({ notifiedAgents: 0, delivered: 0 })),
|
||||
})),
|
||||
feedbackService: feedbackServiceFactoryMock,
|
||||
bootstrapExecutionPolicyFromEnv: vi.fn(async () => null),
|
||||
applyManagedEnvironments: vi.fn(async () => null),
|
||||
|
||||
Reference in new issue
Block a user