Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
732f262
fix(api): include a default justification on SoA
chasprowebdev May 25, 2026
13f468a
fix(app): show default justification at all times on SoA
chasprowebdev May 25, 2026
2939178
fix(app): able to edit the justification
chasprowebdev May 25, 2026
17d899f
Merge branch 'main' into chas/soa-justification
chasprowebdev May 25, 2026
6682be1
fix(app): return a generic default when no family match on SoA
chasprowebdev May 25, 2026
4253d45
Merge branch 'chas/soa-justification' of https://github.com/trycompai…
chasprowebdev May 25, 2026
090e7bc
Merge branch 'main' into chas/soa-justification
tofikwest May 26, 2026
09da0ef
Merge branch 'main' of https://github.com/trycompai/comp into chas/so…
chasprowebdev Jun 1, 2026
35eb9e7
Merge branch 'main' into chas/soa-justification
chasprowebdev Jun 1, 2026
b9fd71b
Merge branch 'main' into chas/soa-justification
chasprowebdev Jun 1, 2026
2c33ecc
Merge branch 'main' of https://github.com/trycompai/comp into chas/so…
chasprowebdev Jun 2, 2026
67b4ab9
chore: merge release v3.66.2 back to main [skip ci]
github-actions[bot] Jun 2, 2026
3bec256
Merge branch 'main' of https://github.com/trycompai/comp into chas/so…
chasprowebdev Jun 2, 2026
43fa889
fix(app): fix empty justification issue on SoA
chasprowebdev Jun 2, 2026
a5621cb
fix(app): keep SoA justification dialog open when save fails
chasprowebdev Jun 2, 2026
7f564df
fix(api): guarantee non-null SoA justification on YES defaults
chasprowebdev Jun 2, 2026
9d01005
Merge pull request #2921 from trycompai/chas/soa-justification
tofikwest Jun 2, 2026
4e7d57d
fix(people): stop tracking background checks for auditor-only members…
Marfuen Jun 2, 2026
51c3b3d
feat(background-checks): admin cancel/delete/retry (CS-475) (#2993)
Marfuen Jun 2, 2026
3d6e609
feat(background-checks): hourly reconciliation for stuck checks (CS-4…
Marfuen Jun 2, 2026
c381397
feat(admin): add Finding Templates management to admin panel
tofikwest Jun 2, 2026
d7e2caf
Merge branch 'main' into tofik/finding-templates-admin
tofikwest Jun 2, 2026
612489f
Merge pull request #2997 from trycompai/tofik/finding-templates-admin
tofikwest Jun 2, 2026
dcd4b4d
fix(background-checks): move admin actions into the status card foote…
Marfuen Jun 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,10 @@ export class BackgroundCheckCustomService {
throw new NotFoundException('Member not found.');
}

const resolvedName = employeeName?.trim() || member.user.name || member.user.email;
const resolvedEmail = employeeEmail?.trim().toLowerCase() || member.user.email;
const resolvedName =
employeeName?.trim() || member.user.name || member.user.email;
const resolvedEmail =
employeeEmail?.trim().toLowerCase() || member.user.email;

// Create/update the record without marking it completed yet
const record = await db.backgroundCheckRequest.upsert({
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { BackgroundCheckIdentityClient } from './background-check-identity.client';

describe('BackgroundCheckIdentityClient idempotency key', () => {
const originalEnv = { ...process.env };
const originalFetch = global.fetch;

beforeEach(() => {
process.env = {
...originalEnv,
BACKGROUND_CHECK_API_KEY: 'bc_test',
BACKGROUND_CHECK_API_BASE_URL: 'https://identity.test',
};
});

afterEach(() => {
process.env = originalEnv;
global.fetch = originalFetch;
});

function mockFetchOk() {
const fetchMock = jest.fn().mockResolvedValue({
ok: true,
text: async () => JSON.stringify({ id: 'check_1', status: 'invited' }),
});
global.fetch = fetchMock as unknown as typeof fetch;
return fetchMock;
}

function keyFrom(fetchMock: jest.Mock): string {
const init = fetchMock.mock.calls[0][1] as {
headers: Record<string, string>;
};
return init.headers['Idempotency-Key'];
}

const params = {
organizationId: 'org_1',
memberId: 'mem_1',
employeeName: 'Ada',
employeeEmail: 'ada@example.com',
requesterEmail: 'admin@example.com',
};

it('forwards the provided idempotency key as the Idempotency-Key header', async () => {
const fetchMock = mockFetchOk();
await new BackgroundCheckIdentityClient().createBackgroundCheck({
...params,
idempotencyKey: 'comp-background-check:bcr_1',
});
expect(keyFrom(fetchMock)).toBe('comp-background-check:bcr_1');
});

it('forwards a per-attempt retry idempotency key unchanged', async () => {
const fetchMock = mockFetchOk();
await new BackgroundCheckIdentityClient().createBackgroundCheck({
...params,
idempotencyKey: 'comp-background-check:bcr_1:2',
});
expect(keyFrom(fetchMock)).toBe('comp-background-check:bcr_1:2');
});
});
79 changes: 46 additions & 33 deletions apps/api/src/background-checks/background-check-identity.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,51 +14,61 @@ export class BackgroundCheckIdentityClient {
employeeName: string;
employeeEmail: string;
requesterEmail: string;
idempotencyKey: string;
}): Promise<IdentityCreateResponse> {
const apiKey = process.env.BACKGROUND_CHECK_API_KEY;
if (!apiKey) {
throw new BadRequestException('Background check service is not configured. Contact support.');
throw new BadRequestException(
'Background check service is not configured. Contact support.',
);
}

const baseUrl = this.baseUrl();
const callbackUrl = this.callbackUrl();

const response = await this.fetchIdentity(`${baseUrl}/v1/background-checks`, {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'Idempotency-Key': `comp-background-check:${params.memberId}`,
},
body: JSON.stringify({
candidate: {
name: params.employeeName,
email: params.employeeEmail,
},
requester: {
email: params.requesterEmail,
},
employmentHistory: [],
references: [],
metadata: {
source: 'comp',
compOrganizationId: params.organizationId,
compMemberId: params.memberId,
const response = await this.fetchIdentity(
`${baseUrl}/v1/background-checks`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'Idempotency-Key': params.idempotencyKey,
},
callbackUrl,
}),
});
body: JSON.stringify({
candidate: {
name: params.employeeName,
email: params.employeeEmail,
},
requester: {
email: params.requesterEmail,
},
employmentHistory: [],
references: [],
metadata: {
source: 'comp',
compOrganizationId: params.organizationId,
compMemberId: params.memberId,
},
callbackUrl,
}),
},
);

const json = await this.readJson(response);
if (!response.ok) {
this.logger.error('Identity background check request failed', json);
throw new BadRequestException('Identity background check request failed.');
throw new BadRequestException(
'Identity background check request failed.',
);
}

return identityCreateResponseSchema.parse(json);
}

async getBackgroundCheck(identityBackgroundCheckId: string): Promise<unknown> {
async getBackgroundCheck(
identityBackgroundCheckId: string,
): Promise<unknown> {
const apiKey = process.env.BACKGROUND_CHECK_API_KEY;
if (!apiKey) return null;

Expand All @@ -76,19 +86,22 @@ export class BackgroundCheckIdentityClient {

private baseUrl(): string {
const baseUrl =
process.env.BACKGROUND_CHECK_API_BASE_URL ?? 'https://glad-sturgeon-729.convex.site';
process.env.BACKGROUND_CHECK_API_BASE_URL ??
'https://glad-sturgeon-729.convex.site';
return baseUrl.replace(/\/+$/, '');
}

private callbackUrl(): string {
const endpoint = process.env.BACKGROUND_WH_ENDPOINT?.trim();
return (endpoint || 'https://api.trycomp.ai/v1/background-checks/webhook').replace(
/\/+$/,
'',
);
return (
endpoint || 'https://api.trycomp.ai/v1/background-checks/webhook'
).replace(/\/+$/, '');
}

private async fetchIdentity(url: string, init: RequestInit): Promise<Response> {
private async fetchIdentity(
url: string,
init: RequestInit,
): Promise<Response> {
try {
return await fetch(url, {
...init,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ export async function fetchCompletedReportSnapshot({
}

try {
const snapshot = await identityClient.getBackgroundCheck(identityBackgroundCheckId);
const snapshot = await identityClient.getBackgroundCheck(
identityBackgroundCheckId,
);
return toInputJsonValue(snapshot);
} catch {
return null;
Expand Down
145 changes: 145 additions & 0 deletions apps/api/src/background-checks/background-check-retry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { BackgroundCheckStatus, db, Prisma } from '@db';
import type { BackgroundCheckIdentityClient } from './background-check-identity.client';

type GetForMemberFn = (params: {
organizationId: string;
memberId: string;
}) => Promise<{
id: string;
rerunCount: number;
employeeName: string;
employeeEmail: string;
status: BackgroundCheckStatus;
} | null>;

export function assertTransitionAllowed(
action: 'cancel' | 'retry',
status: BackgroundCheckStatus,
): void {
const allowed: Record<'cancel' | 'retry', BackgroundCheckStatus[]> = {
cancel: [
BackgroundCheckStatus.invited,
BackgroundCheckStatus.in_progress,
BackgroundCheckStatus.in_review,
],
retry: [BackgroundCheckStatus.failed, BackgroundCheckStatus.cancelled],
};
if (!allowed[action].includes(status)) {
throw new BadRequestException(
`Cannot ${action} a background check in '${status}' status.`,
);
}
}

export async function cancelForMember({
organizationId,
memberId,
getForMember,
}: {
organizationId: string;
memberId: string;
getForMember: GetForMemberFn;
}) {
const existing = await getForMember({ organizationId, memberId });
if (!existing) {
throw new NotFoundException('Background check not found.');
}
assertTransitionAllowed('cancel', existing.status);

return db.backgroundCheckRequest.update({
where: { organizationId_memberId: { organizationId, memberId } },
data: {
status: BackgroundCheckStatus.cancelled,
lastSyncedAt: new Date(),
},
});
}

export async function deleteForMember({
organizationId,
memberId,
getForMember,
}: {
organizationId: string;
memberId: string;
getForMember: GetForMemberFn;
}): Promise<{ ok: true }> {
const existing = await getForMember({ organizationId, memberId });
if (!existing) {
throw new NotFoundException('Background check not found.');
}
// Hard delete; webhookEvents cascade via the FK. Frees the
// @@unique([organizationId, memberId]) constraint for a fresh request.
await db.backgroundCheckRequest.delete({
where: { organizationId_memberId: { organizationId, memberId } },
});
return { ok: true };
}

export async function retryForMember({
organizationId,
memberId,
requesterEmail,
identityClient,
getForMember,
}: {
organizationId: string;
memberId: string;
requesterEmail: string;
identityClient: BackgroundCheckIdentityClient;
getForMember: GetForMemberFn;
}) {
const existing = await getForMember({ organizationId, memberId });
if (!existing) {
throw new NotFoundException('Background check not found.');
}
assertTransitionAllowed('retry', existing.status);

const attempt = existing.rerunCount + 1;
const where = { organizationId_memberId: { organizationId, memberId } };

// Free retry: no charge. Create a fresh Identity check first (varied
// idempotency key) so a late webhook from the prior check cannot match
// the row after we swap in the new id.
let identityResult;
try {
identityResult = await identityClient.createBackgroundCheck({
organizationId,
memberId,
employeeName: existing.employeeName,
employeeEmail: existing.employeeEmail,
requesterEmail,
// Per-record, per-attempt key so each retry creates a fresh vendor
// check rather than colliding with a prior attempt's idempotency key.
idempotencyKey: `comp-background-check:${existing.id}:${attempt}`,
});
} catch (error) {

@cubic-dev-ai cubic-dev-ai Bot Jun 2, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The retry error handler performs a stale status write that can clobber a successful concurrent retry.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/api/src/background-checks/background-check-retry.ts, line 117:

<comment>The retry error handler performs a stale status write that can clobber a successful concurrent retry.</comment>

<file context>
@@ -0,0 +1,145 @@
+      // check rather than colliding with a prior attempt's idempotency key.
+      idempotencyKey: `comp-background-check:${existing.id}:${attempt}`,
+    });
+  } catch (error) {
+    // Restore the prior status (retry is only allowed from 'failed' or
+    // 'cancelled'). Forcing 'failed' here would strip a cancelled check of the
</file context>
Fix with cubic

// Restore the prior status (retry is only allowed from 'failed' or
// 'cancelled'). Forcing 'failed' here would strip a cancelled check of the
// webhook terminal-guard and let a late vendor webhook resurrect it.
await db.backgroundCheckRequest.update({
where,
data: { status: existing.status, lastSyncedAt: new Date() },
});
throw error;
}

return db.backgroundCheckRequest.update({
where,
data: {
identityBackgroundCheckId: identityResult.id,
candidateUrl: identityResult.candidateUrl ?? null,
status: identityResult.status,
rerunCount: attempt,
identityStatus: null,
employmentStatus: null,
referenceStatus: null,
rightToWorkStatus: null,
adjudicationStatus: null,
reportSnapshot: Prisma.JsonNull,
reportSyncedAt: null,
lastSyncedAt: new Date(),
},
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ export function verifyBackgroundCheckWebhookSignature({
}

const timestamp = Number(timestampHeader);
if (!Number.isFinite(timestamp) || Math.abs(Date.now() - timestamp) > WEBHOOK_MAX_SKEW_MS) {
if (
!Number.isFinite(timestamp) ||
Math.abs(Date.now() - timestamp) > WEBHOOK_MAX_SKEW_MS
) {
throw new UnauthorizedException('Webhook timestamp is invalid.');
}

Expand Down
Loading
Loading