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 > - Every master commit must pass Cloud readiness before Docker publishes it and staging deploys it > - Two server tests failed there on and off, so master stopped reaching staging > - Both failures came from test setup that leaked across suites, not from product behavior > - CI runs each shard against one shared PostgreSQL server, and each suite gets its own database on it > - This pull request removes both leaks at their cause and adds a guard for each > - The benefit is that Cloud readiness no longer fails on these two tests, and Docker publishing and staging deploys continue ## Linked Issues or Issue Description **What happened?** Cloud readiness failed on master in two server test shards. 1. `antigravity-swarm.db.test.ts` failed with `duplicate key value violates unique constraint "companies_issue_prefix_idx"`. 2. `git-workspace-expiration.test.ts` > "rolls back when new history appears after capture without changing files" returned `skipReason: "inspection_failed"` instead of `restore_point_contents_changed`. This failed on four attempts of one master commit. **Root cause** 1. The swarm suite and 20 other suites made company issue prefixes from four random hex characters (65,536 values). The swarm suite seeds about 65 companies in one database, so one run of that file had about a 3% chance of a collision. 2. `isolated-remote-workspace-source-lock.test.ts` and `native-workspace-finalizer.test.ts` ran `ALTER ROLE <current_user> SET idle_in_transaction_session_timeout = '1s'`. In CI all suites in a shard share one PostgreSQL server and one role. So every new session in every other suite also got a 1-second idle-in-transaction limit. The expiration test holds a transaction open while it runs Git commands. PostgreSQL closed that session, and the expiration recorded `CONNECTION_CLOSED` as `inspection_failed`. The lock suite never reset the setting. **Steps to reproduce** 1. Run the lock suite and then the expiration test on one shared test server (the same layout CI uses). 2. Before this change, 40 of 40 runs of the expiration test fail with `CONNECTION_CLOSED`. **Expected behavior** A suite's session settings apply only to its own database. Seeded companies never share an issue prefix. ## What Changed - Added `uniqueIssuePrefix(tag)`, a shared test helper that adds 48 random bits (12 uppercase hex characters) to a tag. - Changed all 24 company seeds that used four or fewer random characters (21 files) to use the helper. Updated one identifier assertion in `cases-routes.test.ts` for the longer prefix. - Changed the two suites from `ALTER ROLE ... SET` to `ALTER DATABASE <current_database()> SET`, so the 1-second limit applies only to their own disposable database. The finalizer suite still resets it after its test. - Added two guard tests: one proves the helper does not repeat across 70,000 prefixes, and one fails if any test file changes a setting for a whole role. ## Verification - Deterministic red for the Git expiration failure: one shared test server, lock suite first, then the expiration test 40 times. Before: 40 of 40 failed with `CONNECTION_CLOSED`. After: 40 of 40 passed, and 40 of 40 passed again with 12 CPU-burning processes running. - The same failure appeared in PR CI before the fix: with the full suite on one shared server, 17 runs of the looped expiration test failed with `CONNECTION_CLOSED`. - Deterministic red for the prefix generator: the old four-character generator gives 42,898 distinct prefixes from 70,000 calls. The new helper gives 70,000. - `antigravity-swarm.db.test.ts`: 30 of 30 runs passed with 12 CPU-burning processes running. - All 21 suites that changed seeds pass locally. The two changed lock suites pass (72 tests). ## Risks - Low risk. Only test files change. The product code is unchanged. - Longer test prefixes make test issue identifiers longer. One assertion that checked a four-character prefix is updated. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, GitHub CLI) and extended reasoning. ## 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>
638 lines
26 KiB
TypeScript
638 lines
26 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import express from "express";
|
|
import request from "supertest";
|
|
import { eq } from "drizzle-orm";
|
|
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
|
import {
|
|
activityLog,
|
|
agents,
|
|
companies,
|
|
createDb,
|
|
decisionTrainingExamples,
|
|
executionWorkspaces,
|
|
heartbeatRuns,
|
|
issueComments,
|
|
issues,
|
|
issueThreadInteractions,
|
|
projectWorkspaces,
|
|
projects,
|
|
toolActionRequests,
|
|
toolApplications,
|
|
toolConnections,
|
|
toolInvocations,
|
|
} from "@paperclipai/db";
|
|
import {
|
|
getEmbeddedPostgresTestSupport,
|
|
startEmbeddedPostgresTestDatabase,
|
|
} from "./helpers/embedded-postgres.js";
|
|
import { errorHandler } from "../middleware/index.js";
|
|
import { decisionTrainingRoutes } from "../routes/decision-training.js";
|
|
import { attentionService } from "../services/attention.js";
|
|
import { captureDecisionSnapshot, decisionTrainingService, withoutGoogleWorkspaceContent } from "../services/decision-training.js";
|
|
import { uniqueIssuePrefix } from "./helpers/issue-prefix.js";
|
|
|
|
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
|
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
|
|
|
if (!embeddedPostgresSupport.supported) {
|
|
console.warn(
|
|
`Skipping embedded Postgres decision training tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
|
|
);
|
|
}
|
|
|
|
describeEmbeddedPostgres("decision training", () => {
|
|
let db!: ReturnType<typeof createDb>;
|
|
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
|
|
|
beforeAll(async () => {
|
|
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-decision-training-");
|
|
db = createDb(tempDb.connectionString);
|
|
}, 30_000);
|
|
|
|
afterEach(async () => {
|
|
await db.delete(activityLog);
|
|
await db.delete(decisionTrainingExamples);
|
|
await db.delete(issueThreadInteractions);
|
|
await db.delete(issueComments);
|
|
await db.delete(executionWorkspaces);
|
|
await db.delete(heartbeatRuns);
|
|
await db.delete(issues);
|
|
await db.delete(projectWorkspaces);
|
|
await db.delete(projects);
|
|
await db.delete(agents);
|
|
await db.delete(companies);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await tempDb?.cleanup();
|
|
});
|
|
|
|
async function seedResolvedInteraction() {
|
|
const companyId = randomUUID();
|
|
const projectId = randomUUID();
|
|
const issueId = randomUUID();
|
|
const interactionId = randomUUID();
|
|
const cutoffAt = new Date("2026-07-16T12:00:00.000Z");
|
|
const beforeId = randomUUID();
|
|
const atCutoffId = randomUUID();
|
|
const afterId = randomUUID();
|
|
|
|
await db.insert(companies).values({ id: companyId, name: "Decision Co", issuePrefix: uniqueIssuePrefix("D") });
|
|
await db.insert(projects).values({ id: projectId, companyId, name: "Decisions" });
|
|
await db.insert(issues).values({
|
|
id: issueId,
|
|
companyId,
|
|
projectId,
|
|
identifier: "DEC-1",
|
|
title: "Choose a rollout strategy",
|
|
status: "in_review",
|
|
});
|
|
await db.insert(issueThreadInteractions).values({
|
|
id: interactionId,
|
|
companyId,
|
|
issueId,
|
|
kind: "request_confirmation",
|
|
status: "accepted",
|
|
payload: { question: "Ship it?" } as never,
|
|
result: { accepted: true } as never,
|
|
resolvedByUserId: "board-user",
|
|
resolvedAt: cutoffAt,
|
|
});
|
|
await db.insert(issueComments).values([
|
|
{ id: beforeId, companyId, issueId, body: "Before", createdAt: new Date("2026-07-16T11:59:59.000Z") },
|
|
{ id: atCutoffId, companyId, issueId, body: "At cutoff", createdAt: cutoffAt },
|
|
{ id: afterId, companyId, issueId, body: "Leaked later context", createdAt: new Date("2026-07-16T12:00:01.000Z") },
|
|
]);
|
|
return { companyId, projectId, issueId, interactionId, cutoffAt, beforeId, atCutoffId, afterId };
|
|
}
|
|
|
|
it("includes the cutoff boundary and excludes later comments", async () => {
|
|
const seeded = await seedResolvedInteraction();
|
|
const captured = await captureDecisionSnapshot(db, {
|
|
companyId: seeded.companyId,
|
|
sourceKind: "interaction",
|
|
sourceId: seeded.interactionId,
|
|
issueId: seeded.issueId,
|
|
}, new Date("2026-07-16T13:00:00.000Z"));
|
|
|
|
expect(captured.cutoffAt).toEqual(seeded.cutoffAt);
|
|
expect(captured.snapshot.cutoff).toEqual({
|
|
at: seeded.cutoffAt.toISOString(),
|
|
lastCommentId: seeded.atCutoffId,
|
|
commentCount: 2,
|
|
});
|
|
expect(captured.snapshot.comments.map((comment) => comment.id)).toEqual([seeded.beforeId, seeded.atCutoffId]);
|
|
expect(JSON.stringify(captured.snapshot)).not.toContain("Leaked later context");
|
|
expect(captured.snapshot.retention).toEqual({
|
|
policy: "scrub_deleted_comments_v1",
|
|
commentDeletion: "redact",
|
|
issueDeletion: "cascade",
|
|
});
|
|
});
|
|
|
|
it("scrubs captured comment content after source deletion", async () => {
|
|
const seeded = await seedResolvedInteraction();
|
|
const svc = decisionTrainingService(db);
|
|
const example = await svc.create({
|
|
companyId: seeded.companyId,
|
|
sourceKind: "interaction",
|
|
sourceId: seeded.interactionId,
|
|
issueId: seeded.issueId,
|
|
notes: "Keep the decision, not deleted comment content.",
|
|
createdByUserId: "board-user",
|
|
});
|
|
|
|
await svc.scrubDeletedComments({
|
|
companyId: seeded.companyId,
|
|
issueId: seeded.issueId,
|
|
commentIds: [seeded.beforeId],
|
|
deletedAt: new Date("2026-07-16T14:00:00.000Z"),
|
|
});
|
|
|
|
const updated = await svc.getById(example.id);
|
|
expect(updated?.retentionPolicy).toBe("scrub_deleted_comments_v1");
|
|
expect(updated?.snapshot.comments).toEqual(expect.arrayContaining([
|
|
expect.objectContaining({
|
|
id: seeded.beforeId,
|
|
body: "",
|
|
presentation: null,
|
|
metadata: null,
|
|
retentionRedaction: {
|
|
reason: "source_comment_deleted",
|
|
policy: "scrub_deleted_comments_v1",
|
|
},
|
|
}),
|
|
]));
|
|
expect(JSON.stringify(updated?.snapshot)).not.toContain("Before");
|
|
expect(updated?.snapshot.comments.find((comment) => comment.id === seeded.atCutoffId)?.body).toBe("At cutoff");
|
|
});
|
|
|
|
it("deletes training examples when their issue is deleted", async () => {
|
|
const seeded = await seedResolvedInteraction();
|
|
const svc = decisionTrainingService(db);
|
|
const example = await svc.create({
|
|
companyId: seeded.companyId,
|
|
sourceKind: "interaction",
|
|
sourceId: seeded.interactionId,
|
|
issueId: seeded.issueId,
|
|
notes: "Cascade with the issue.",
|
|
createdByUserId: "board-user",
|
|
});
|
|
|
|
await db.delete(issueComments).where(eq(issueComments.issueId, seeded.issueId));
|
|
await db.delete(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, seeded.issueId));
|
|
await db.delete(issues).where(eq(issues.id, seeded.issueId));
|
|
|
|
expect(await svc.getById(example.id)).toBeUndefined();
|
|
});
|
|
|
|
it("excludes runs updated after the decision cutoff", async () => {
|
|
const seeded = await seedResolvedInteraction();
|
|
const agentId = randomUUID();
|
|
const includedRunId = randomUUID();
|
|
const excludedRunId = randomUUID();
|
|
await db.insert(agents).values({
|
|
id: agentId,
|
|
companyId: seeded.companyId,
|
|
name: "Decision agent",
|
|
role: "engineer",
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {},
|
|
permissions: {},
|
|
});
|
|
await db.insert(heartbeatRuns).values([
|
|
{
|
|
id: includedRunId,
|
|
companyId: seeded.companyId,
|
|
agentId,
|
|
status: "succeeded",
|
|
startedAt: new Date("2026-07-16T11:00:00.000Z"),
|
|
finishedAt: new Date("2026-07-16T11:30:00.000Z"),
|
|
contextSnapshot: { issueId: seeded.issueId, evidence: "known before cutoff" },
|
|
createdAt: new Date("2026-07-16T11:00:00.000Z"),
|
|
updatedAt: new Date("2026-07-16T11:30:00.000Z"),
|
|
},
|
|
{
|
|
id: excludedRunId,
|
|
companyId: seeded.companyId,
|
|
agentId,
|
|
status: "running",
|
|
startedAt: new Date("2026-07-16T11:45:00.000Z"),
|
|
contextSnapshot: { issueId: seeded.issueId, evidence: "written after cutoff" },
|
|
createdAt: new Date("2026-07-16T11:45:00.000Z"),
|
|
updatedAt: new Date("2026-07-16T12:30:00.000Z"),
|
|
},
|
|
]);
|
|
|
|
const captured = await captureDecisionSnapshot(db, {
|
|
companyId: seeded.companyId,
|
|
sourceKind: "interaction",
|
|
sourceId: seeded.interactionId,
|
|
issueId: seeded.issueId,
|
|
}, new Date("2026-07-16T13:00:00.000Z"));
|
|
|
|
expect(captured.snapshot.runs.map((run) => run.id)).toEqual([includedRunId]);
|
|
expect(JSON.stringify(captured.snapshot)).not.toContain("written after cutoff");
|
|
});
|
|
|
|
it("leaves what agents read from Google Workspace out of the snapshot", async () => {
|
|
const seeded = await seedResolvedInteraction();
|
|
const secret = "Board notes read from Gmail";
|
|
const [agent] = await db.insert(agents).values({
|
|
companyId: seeded.companyId, name: "Reader", role: "engineer", status: "active", adapterType: "process", adapterConfig: {}, runtimeConfig: {},
|
|
}).returning();
|
|
const [googleRun, otherRun] = await db.insert(heartbeatRuns).values([
|
|
{
|
|
companyId: seeded.companyId, agentId: agent!.id, status: "succeeded", stdoutExcerpt: secret, resultJson: { summary: secret }, sessionIdAfter: "gmail-session",
|
|
startedAt: new Date("2026-07-16T11:00:00.000Z"), finishedAt: new Date("2026-07-16T11:10:00.000Z"),
|
|
contextSnapshot: { issueId: seeded.issueId }, createdAt: new Date("2026-07-16T11:00:00.000Z"), updatedAt: new Date("2026-07-16T11:10:00.000Z"),
|
|
},
|
|
{
|
|
companyId: seeded.companyId, agentId: agent!.id, status: "succeeded", resultJson: { summary: "Other work" },
|
|
startedAt: new Date("2026-07-16T11:20:00.000Z"), finishedAt: new Date("2026-07-16T11:30:00.000Z"),
|
|
contextSnapshot: { issueId: seeded.issueId, paperclipSessionHandoffMarkdown: secret }, createdAt: new Date("2026-07-16T11:20:00.000Z"), updatedAt: new Date("2026-07-16T11:30:00.000Z"),
|
|
},
|
|
]).returning();
|
|
const [resumedRun] = await db.insert(heartbeatRuns).values({
|
|
companyId: seeded.companyId, agentId: agent!.id, status: "succeeded", resultJson: { summary: `Quoting: ${secret}` },
|
|
sessionIdBefore: "gmail-session", sessionIdAfter: "gmail-session",
|
|
startedAt: new Date("2026-07-16T11:50:00.000Z"), finishedAt: new Date("2026-07-16T11:55:00.000Z"),
|
|
contextSnapshot: { issueId: seeded.issueId }, createdAt: new Date("2026-07-16T11:50:00.000Z"), updatedAt: new Date("2026-07-16T11:55:00.000Z"),
|
|
}).returning();
|
|
const [application] = await db.insert(toolApplications).values({ companyId: seeded.companyId, name: "Google Workspace", type: "mcp_http" }).returning();
|
|
const [connection] = await db.insert(toolConnections).values({
|
|
companyId: seeded.companyId, applicationId: application!.id, name: "Google Workspace", uid: randomUUID(), transport: "mcp_remote",
|
|
status: "active", config: { sourceTemplateKey: "google-workspace" },
|
|
}).returning();
|
|
const [invocation] = await db.insert(toolInvocations).values({
|
|
companyId: seeded.companyId, connectionId: connection!.id, runId: googleRun!.id, toolName: "get_message", status: "succeeded",
|
|
}).returning();
|
|
const [actionRequest] = await db.insert(toolActionRequests).values({
|
|
companyId: seeded.companyId, issueId: seeded.issueId, invocationId: invocation!.id, interactionId: seeded.interactionId,
|
|
status: "executed", canonicalArgumentsHash: "hash", canonicalArgumentsSummary: { summary: "", sizeBytes: 0, sha256: "hash", redactedFields: [] },
|
|
}).returning();
|
|
const [deliveredRun] = await db.insert(heartbeatRuns).values({
|
|
companyId: seeded.companyId, agentId: agent!.id, status: "succeeded", resultJson: { summary: secret }, sessionIdAfter: "approval-session",
|
|
startedAt: new Date("2026-07-16T11:40:00.000Z"), finishedAt: new Date("2026-07-16T11:45:00.000Z"),
|
|
contextSnapshot: { issueId: seeded.issueId, toolActionRequestIds: [actionRequest!.id], toolAction: { resultSummary: secret } },
|
|
createdAt: new Date("2026-07-16T11:40:00.000Z"), updatedAt: new Date("2026-07-16T11:45:00.000Z"),
|
|
}).returning();
|
|
const [resumedApprovalRun] = await db.insert(heartbeatRuns).values({
|
|
companyId: seeded.companyId, agentId: agent!.id, status: "succeeded", resultJson: { summary: `Recalling: ${secret}` },
|
|
sessionIdBefore: "approval-session", startedAt: new Date("2026-07-16T11:46:00.000Z"), finishedAt: new Date("2026-07-16T11:48:00.000Z"),
|
|
contextSnapshot: { issueId: seeded.issueId }, createdAt: new Date("2026-07-16T11:46:00.000Z"), updatedAt: new Date("2026-07-16T11:48:00.000Z"),
|
|
}).returning();
|
|
await db.update(issueThreadInteractions).set({
|
|
payload: { question: "Send?", toolAction: { previewMarkdown: secret } } as never,
|
|
result: { accepted: true, toolAction: { resultSummary: secret } } as never,
|
|
}).where(eq(issueThreadInteractions.id, seeded.interactionId));
|
|
|
|
const captured = await captureDecisionSnapshot(db, {
|
|
companyId: seeded.companyId,
|
|
sourceKind: "interaction",
|
|
sourceId: seeded.interactionId,
|
|
issueId: seeded.issueId,
|
|
}, new Date("2026-07-16T13:00:00.000Z"));
|
|
|
|
expect(JSON.stringify(captured.snapshot)).not.toContain(secret);
|
|
expect(captured.snapshot.runs.find((run) => run.id === googleRun!.id)).toMatchObject({ googleWorkspaceContentOmitted: true });
|
|
expect(captured.snapshot.runs.find((run) => run.id === otherRun!.id)).toMatchObject({ resultJson: { summary: "Other work" } });
|
|
expect(captured.snapshot.runs.find((run) => run.id === deliveredRun!.id)).toMatchObject({ googleWorkspaceContentOmitted: true });
|
|
expect(captured.snapshot.runs.find((run) => run.id === resumedRun!.id)).toMatchObject({ googleWorkspaceContentOmitted: true });
|
|
expect(captured.snapshot.runs.find((run) => run.id === resumedApprovalRun!.id)).toMatchObject({ googleWorkspaceContentOmitted: true });
|
|
expect(captured.snapshot.decision.payload).toMatchObject({ payload: { question: "Send?", googleWorkspaceContentOmitted: true } });
|
|
|
|
const savedBeforeThisChange = {
|
|
companyId: seeded.companyId, sourceKind: "interaction" as const, sourceId: seeded.interactionId,
|
|
snapshot: { ...captured.snapshot, runs: [{ id: googleRun!.id, resultJson: { summary: secret } }, { id: otherRun!.id, status: "succeeded" }],
|
|
decision: { ...captured.snapshot.decision, payload: { payload: { toolAction: { previewMarkdown: secret } } } } } as never,
|
|
};
|
|
const [exported] = await withoutGoogleWorkspaceContent(db, seeded.companyId, [savedBeforeThisChange]);
|
|
expect(JSON.stringify(exported)).not.toContain(secret);
|
|
expect((exported as unknown as { runs: unknown[] }).runs[1]).toEqual({ id: otherRun!.id, status: "succeeded" });
|
|
});
|
|
|
|
it("labels workspace-only commit evidence accurately", async () => {
|
|
const seeded = await seedResolvedInteraction();
|
|
await db.insert(projectWorkspaces).values({
|
|
companyId: seeded.companyId,
|
|
projectId: seeded.projectId,
|
|
name: "Primary workspace",
|
|
repoUrl: "https://github.com/paperclipai/paperclip.git",
|
|
metadata: { commitSha: "abcdef1234567890" },
|
|
isPrimary: false,
|
|
createdAt: new Date("2026-07-16T11:00:00.000Z"),
|
|
updatedAt: new Date("2026-07-16T11:30:00.000Z"),
|
|
});
|
|
await db.insert(projectWorkspaces).values({
|
|
companyId: seeded.companyId,
|
|
projectId: seeded.projectId,
|
|
name: "Post-cutoff workspace",
|
|
repoUrl: "https://github.com/paperclipai/paperclip.git",
|
|
metadata: { commitSha: "ffffffffffffffff" },
|
|
isPrimary: true,
|
|
createdAt: new Date("2026-07-16T11:00:00.000Z"),
|
|
updatedAt: new Date("2026-07-16T12:30:00.000Z"),
|
|
});
|
|
await db.insert(executionWorkspaces).values({
|
|
companyId: seeded.companyId,
|
|
projectId: seeded.projectId,
|
|
sourceIssueId: seeded.issueId,
|
|
mode: "isolated_workspace",
|
|
strategyType: "git_worktree",
|
|
name: "Post-cutoff execution workspace",
|
|
providerType: "git_worktree",
|
|
metadata: { commitSha: "eeeeeeeeeeeeeeee" },
|
|
openedAt: new Date("2026-07-16T11:00:00.000Z"),
|
|
lastUsedAt: new Date("2026-07-16T12:30:00.000Z"),
|
|
updatedAt: new Date("2026-07-16T12:30:00.000Z"),
|
|
});
|
|
|
|
const captured = await captureDecisionSnapshot(db, {
|
|
companyId: seeded.companyId,
|
|
sourceKind: "interaction",
|
|
sourceId: seeded.interactionId,
|
|
issueId: seeded.issueId,
|
|
}, new Date("2026-07-16T13:00:00.000Z"));
|
|
|
|
expect(captured.snapshot.code).toMatchObject({
|
|
commitSha: "abcdef1234567890",
|
|
resolution: "workspace",
|
|
});
|
|
});
|
|
|
|
it("enforces one example per decision and author", async () => {
|
|
const seeded = await seedResolvedInteraction();
|
|
const svc = decisionTrainingService(db);
|
|
const input = {
|
|
companyId: seeded.companyId,
|
|
sourceKind: "interaction" as const,
|
|
sourceId: seeded.interactionId,
|
|
issueId: seeded.issueId,
|
|
notes: "Ship behind a flag.",
|
|
createdByUserId: "board-user",
|
|
};
|
|
|
|
const created = await svc.create(input);
|
|
await expect(svc.create(input)).rejects.toMatchObject({ status: 409 });
|
|
const updated = await svc.updateNotes(created.id, "board-user", "Use a 10% canary first.");
|
|
expect(updated?.notesHistory).toEqual([
|
|
expect.objectContaining({ author: "board-user", body: "Ship behind a flag." }),
|
|
]);
|
|
const unchanged = await svc.updateNotes(created.id, "board-user", "Use a 10% canary first.");
|
|
expect(unchanged?.notesHistory).toEqual(updated?.notesHistory);
|
|
expect(updated?.snapshot).toEqual(created.snapshot);
|
|
});
|
|
|
|
it("enriches attention items with the current user's training example", async () => {
|
|
const seeded = await seedResolvedInteraction();
|
|
const example = await decisionTrainingService(db).create({
|
|
companyId: seeded.companyId,
|
|
sourceKind: "interaction",
|
|
sourceId: seeded.interactionId,
|
|
issueId: seeded.issueId,
|
|
notes: "Captured guidance.",
|
|
createdByUserId: "board-user",
|
|
});
|
|
await db
|
|
.update(issueThreadInteractions)
|
|
.set({ status: "pending", resolvedAt: null, updatedAt: new Date() })
|
|
.where(eq(issueThreadInteractions.id, seeded.interactionId));
|
|
|
|
const feed = await attentionService(db).list(seeded.companyId, { userId: "board-user" });
|
|
const item = feed.items.find((candidate) => candidate.subject.id === seeded.interactionId);
|
|
expect(item?.trainingExampleId).toBe(example.id);
|
|
});
|
|
|
|
it("does not log a notes update when the submitted notes are unchanged", async () => {
|
|
const seeded = await seedResolvedInteraction();
|
|
const example = await decisionTrainingService(db).create({
|
|
companyId: seeded.companyId,
|
|
sourceKind: "interaction",
|
|
sourceId: seeded.interactionId,
|
|
issueId: seeded.issueId,
|
|
notes: "Keep the current notes.",
|
|
createdByUserId: "board-user",
|
|
});
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use((req, _res, next) => {
|
|
req.actor = { type: "board", userId: "board-user", source: "local_implicit" };
|
|
next();
|
|
});
|
|
app.use("/api", decisionTrainingRoutes(db));
|
|
app.use(errorHandler);
|
|
|
|
await request(app)
|
|
.patch(`/api/decision-training/${example.id}`)
|
|
.send({ notes: "Keep the current notes." })
|
|
.expect(200);
|
|
|
|
const noOpLogs = await db
|
|
.select()
|
|
.from(activityLog)
|
|
.where(eq(activityLog.action, "decision_training.notes_updated"));
|
|
expect(noOpLogs).toHaveLength(0);
|
|
|
|
await request(app)
|
|
.patch(`/api/decision-training/${example.id}`)
|
|
.send({ notes: "Record the real change." })
|
|
.expect(200);
|
|
|
|
const changedLogs = await db
|
|
.select()
|
|
.from(activityLog)
|
|
.where(eq(activityLog.action, "decision_training.notes_updated"));
|
|
expect(changedLogs).toHaveLength(1);
|
|
});
|
|
|
|
it("returns not found for malformed example ids", async () => {
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use((req, _res, next) => {
|
|
req.actor = { type: "board", userId: "board-user", source: "local_implicit" };
|
|
next();
|
|
});
|
|
app.use("/api", decisionTrainingRoutes(db));
|
|
app.use(errorHandler);
|
|
|
|
await request(app).get("/api/decision-training/not-a-uuid").expect(404);
|
|
await request(app)
|
|
.patch("/api/decision-training/not-a-uuid")
|
|
.send({ notes: "Changed" })
|
|
.expect(404);
|
|
await request(app).delete("/api/decision-training/not-a-uuid").expect(404);
|
|
});
|
|
|
|
it("rejects updates and deletes from a different board user", async () => {
|
|
const seeded = await seedResolvedInteraction();
|
|
const example = await decisionTrainingService(db).create({
|
|
companyId: seeded.companyId,
|
|
sourceKind: "interaction",
|
|
sourceId: seeded.interactionId,
|
|
issueId: seeded.issueId,
|
|
notes: "Owner notes",
|
|
createdByUserId: "board-user",
|
|
});
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use((req, _res, next) => {
|
|
req.actor = { type: "board", userId: "other-board-user", source: "local_implicit" };
|
|
next();
|
|
});
|
|
app.use("/api", decisionTrainingRoutes(db));
|
|
app.use(errorHandler);
|
|
|
|
await request(app)
|
|
.patch(`/api/decision-training/${example.id}`)
|
|
.send({ notes: "Changed by someone else" })
|
|
.expect(403);
|
|
await request(app).delete(`/api/decision-training/${example.id}`).expect(403);
|
|
|
|
const unchanged = await decisionTrainingService(db).getById(example.id);
|
|
expect(unchanged?.notes).toBe("Owner notes");
|
|
});
|
|
|
|
it("rejects agent writes and snapshot mutation", async () => {
|
|
const seeded = await seedResolvedInteraction();
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use((req, _res, next) => {
|
|
req.actor = {
|
|
type: "agent",
|
|
agentId: randomUUID(),
|
|
companyId: seeded.companyId,
|
|
source: "agent_jwt",
|
|
};
|
|
next();
|
|
});
|
|
app.use("/api", decisionTrainingRoutes(db));
|
|
app.use(errorHandler);
|
|
|
|
await request(app)
|
|
.post(`/api/companies/${seeded.companyId}/decision-training`)
|
|
.send({ sourceKind: "interaction", sourceId: seeded.interactionId, issueId: seeded.issueId, notes: "No" })
|
|
.expect(403);
|
|
|
|
await request(app)
|
|
.patch(`/api/decision-training/${randomUUID()}`)
|
|
.send({ notes: "Changed", snapshot: { version: 2 } })
|
|
.expect(400);
|
|
});
|
|
|
|
it("rejects agent reads and exports", async () => {
|
|
const seeded = await seedResolvedInteraction();
|
|
const example = await decisionTrainingService(db).create({
|
|
companyId: seeded.companyId,
|
|
sourceKind: "interaction",
|
|
sourceId: seeded.interactionId,
|
|
issueId: seeded.issueId,
|
|
notes: "Sensitive guidance",
|
|
createdByUserId: "board-user",
|
|
});
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use((req, _res, next) => {
|
|
req.actor = {
|
|
type: "agent",
|
|
agentId: randomUUID(),
|
|
companyId: seeded.companyId,
|
|
source: "agent_jwt",
|
|
};
|
|
next();
|
|
});
|
|
app.use("/api", decisionTrainingRoutes(db));
|
|
app.use(errorHandler);
|
|
|
|
await request(app).get(`/api/companies/${seeded.companyId}/decision-training`).expect(403);
|
|
await request(app).get(`/api/decision-training/${example.id}`).expect(403);
|
|
await request(app).get(`/api/companies/${seeded.companyId}/decision-training/export.jsonl`).expect(403);
|
|
});
|
|
|
|
it("exports immutable state and labels as JSONL", async () => {
|
|
const seeded = await seedResolvedInteraction();
|
|
const example = await decisionTrainingService(db).create({
|
|
companyId: seeded.companyId,
|
|
sourceKind: "interaction",
|
|
sourceId: seeded.interactionId,
|
|
issueId: seeded.issueId,
|
|
notes: "Use a feature flag.",
|
|
createdByUserId: "board-user",
|
|
});
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use((req, _res, next) => {
|
|
req.actor = { type: "board", userId: "board-user", source: "local_implicit" };
|
|
next();
|
|
});
|
|
app.use("/api", decisionTrainingRoutes(db));
|
|
app.use(errorHandler);
|
|
|
|
const response = await request(app)
|
|
.get(`/api/companies/${seeded.companyId}/decision-training/export.jsonl`)
|
|
.expect(200);
|
|
const line = JSON.parse(response.text.trim());
|
|
expect(line).toEqual({
|
|
retentionPolicy: "scrub_deleted_comments_v1",
|
|
state: example.snapshot,
|
|
label: { outcome: "accepted", notes: "Use a feature flag." },
|
|
});
|
|
expect(response.text).not.toContain("Leaked later context");
|
|
|
|
const exportLogs = await db
|
|
.select()
|
|
.from(activityLog)
|
|
.where(eq(activityLog.action, "decision_training.exported"));
|
|
expect(exportLogs).toHaveLength(1);
|
|
expect(exportLogs[0]).toMatchObject({
|
|
companyId: seeded.companyId,
|
|
actorType: "user",
|
|
actorId: "board-user",
|
|
entityType: "decision_training_export",
|
|
entityId: seeded.companyId,
|
|
details: { exampleCount: 1, exampleIds: [example.id] },
|
|
});
|
|
});
|
|
|
|
it("logs individual example reads", async () => {
|
|
const seeded = await seedResolvedInteraction();
|
|
const example = await decisionTrainingService(db).create({
|
|
companyId: seeded.companyId,
|
|
sourceKind: "interaction",
|
|
sourceId: seeded.interactionId,
|
|
issueId: seeded.issueId,
|
|
notes: "Read audit",
|
|
createdByUserId: "board-user",
|
|
});
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use((req, _res, next) => {
|
|
req.actor = { type: "board", userId: "board-user", source: "local_implicit" };
|
|
next();
|
|
});
|
|
app.use("/api", decisionTrainingRoutes(db));
|
|
app.use(errorHandler);
|
|
|
|
await request(app).get(`/api/decision-training/${example.id}`).expect(200);
|
|
|
|
const readLogs = await db
|
|
.select()
|
|
.from(activityLog)
|
|
.where(eq(activityLog.action, "decision_training.read"));
|
|
expect(readLogs).toHaveLength(1);
|
|
expect(readLogs[0]).toMatchObject({
|
|
companyId: seeded.companyId,
|
|
actorType: "user",
|
|
actorId: "board-user",
|
|
entityType: "decision_training_example",
|
|
entityId: example.id,
|
|
details: {
|
|
sourceKind: "interaction",
|
|
sourceId: seeded.interactionId,
|
|
issueId: seeded.issueId,
|
|
},
|
|
});
|
|
});
|
|
});
|