diff --git a/docs/de/platform/admin/governance/data-subject-requests.md b/docs/de/platform/admin/governance/data-subject-requests.md
index f6e9a69300..aa6cfee5df 100644
--- a/docs/de/platform/admin/governance/data-subject-requests.md
+++ b/docs/de/platform/admin/governance/data-subject-requests.md
@@ -20,6 +20,8 @@ Als Admin oder Inhaber bearbeitest du unter **Einstellungen > Richtlinien > Anfr
Die Löschung entfernt betroffene Daten endgültig; sie verschiebt sie nicht in den Papierkorb. Der Beleg erfasst Kategorien und Anzahlen, darunter Chats, Dokumente und Uploads, Einstellungen, Feedback, Benachrichtigungen, Nutzung und das Bereinigen von Personenkennungen im Audit-Protokoll.
+Aufgaben, die die Person als **Reviewer** nennen, verlieren diese Zuweisung. Eine Prüfanfrage, die noch auf sie wartet, geht wie bei **Reviewer entfernen** an den Ersteller der Aufgabe oder des Projekts, und diese Person wird benachrichtigt. Bei einer archivierten Aufgabe geht die Prüfanfrage ohne Benachrichtigung weiter. Prüfentscheidungen, die die Person bereits getroffen hat, bleiben ohne ihren Namen erhalten.
+
## Vorher die Richtlinie prüfen
| Einstellung | Wirkung |
diff --git a/docs/en/platform/admin/governance/data-subject-requests.md b/docs/en/platform/admin/governance/data-subject-requests.md
index 63f3e4d184..18a195bd78 100644
--- a/docs/en/platform/admin/governance/data-subject-requests.md
+++ b/docs/en/platform/admin/governance/data-subject-requests.md
@@ -20,6 +20,8 @@ Use **Settings > Governance > Data subject requests** as an Admin or Owner to pr
Erasure permanently removes covered data; it is not a move to Trash. The receipt records the affected categories and counts, including chats, documents and uploads, preferences, feedback, notifications, usage, and audit-identifier scrubbing.
+Tasks that name the person as **Reviewer** lose that designation. A task review still waiting on them moves to the task creator or project creator, as **Clear reviewer** does, and that person is notified. On an archived task the review moves without a notification. Review decisions the person already made stay on record without their name.
+
## Check the policy before filing
| Setting | Effect |
diff --git a/docs/fr/platform/admin/governance/data-subject-requests.md b/docs/fr/platform/admin/governance/data-subject-requests.md
index 6ac2d16273..f7ead59d06 100644
--- a/docs/fr/platform/admin/governance/data-subject-requests.md
+++ b/docs/fr/platform/admin/governance/data-subject-requests.md
@@ -20,6 +20,8 @@ En tant qu’admin ou propriétaire, utilise **Paramètres > Gouvernance > Perso
L’effacement supprime définitivement les données couvertes ; il ne les déplace pas vers la corbeille. Le reçu indique les catégories et les nombres concernés : chats, documents et imports, préférences, retours, notifications, usage et nettoyage des identifiants personnels dans l’audit.
+Les tâches qui désignent la personne comme **Relecteur** perdent cette désignation. Une demande de revue qui l’attend encore passe, comme avec **Retirer le relecteur**, à la personne qui a créé la tâche ou le projet, et celle-ci en est notifiée. Pour une tâche archivée, la demande passe sans notification. Les décisions de revue que la personne a déjà prises restent enregistrées sans son nom.
+
## Vérifier la règle avant le dépôt
| Réglage | Effet |
diff --git a/services/platform/app/features/tasks/components/reviewer-picker.test.tsx b/services/platform/app/features/tasks/components/reviewer-picker.test.tsx
index f6b1d9e391..03fa3786eb 100644
--- a/services/platform/app/features/tasks/components/reviewer-picker.test.tsx
+++ b/services/platform/app/features/tasks/components/reviewer-picker.test.tsx
@@ -38,9 +38,13 @@ const members: AssignableActor[] = [
{ type: 'user', id: 'user-4', name: 'Dan', email: 'dan@example.com' },
];
+/** Whether the project's audience has loaded (see `useAssignableActors`). */
+let scopeReady = true;
+
vi.mock('../hooks/use-actor-directory', () => ({
useAssignableActors: () => ({
assignableMembers: members,
+ scopeReady,
currentUserId: 'user-2',
resolveActor: (_type: string, id: string) => ({
type: 'user',
@@ -54,6 +58,7 @@ vi.mock('../hooks/use-actor-directory', () => ({
describe('ReviewerPicker', () => {
beforeEach(() => {
vi.clearAllMocks();
+ scopeReady = true;
});
it('lists only members holding an editor-level role, current user first', async () => {
@@ -74,6 +79,30 @@ describe('ReviewerPicker', () => {
expect(screen.getByText('tasks.reviewer.editorsOnly')).toBeInTheDocument();
});
+ it('lists nobody until the project audience has loaded', async () => {
+ // Until then the members are org-wide, editors outside a team-restricted
+ // project included — the server would refuse any of them.
+ scopeReady = false;
+ const { user } = render(
+ ,
+ );
+
+ await user.click(
+ screen.getByRole('button', { name: 'tasks.fields.reviewer' }),
+ );
+
+ expect(screen.queryByText('Alex')).not.toBeInTheDocument();
+ expect(screen.queryByText('Bea')).not.toBeInTheDocument();
+ expect(screen.getByText('common.actions.loading')).toBeInTheDocument();
+ expect(
+ screen.queryByText('common.search.noResults'),
+ ).not.toBeInTheDocument();
+ });
+
it('designates on select and clears via the footer action', async () => {
const onChange = vi.fn();
const first = render(
diff --git a/services/platform/app/features/tasks/components/reviewer-picker.tsx b/services/platform/app/features/tasks/components/reviewer-picker.tsx
index a23c86b3c6..d4e020275c 100644
--- a/services/platform/app/features/tasks/components/reviewer-picker.tsx
+++ b/services/platform/app/features/tasks/components/reviewer-picker.tsx
@@ -27,7 +27,10 @@ import { AssigneeAvatar } from './assignee-avatar';
* machinery (transfer confirm, live-run cancel, agents/automations sections)
* applies here. Candidates are the project's members holding an editor-level
* org role — the same `EDITOR_ROLES` set the server enforces (Members can see
- * review cards but cannot respond).
+ * review cards but cannot respond). Until the project's audience has loaded
+ * it lists nobody: the org-wide fallback the assignee picker lives with
+ * would offer editors outside a team-restricted project, whom the server
+ * refuses.
*
* When `disabled` (no edit permission) it renders the bare avatar with no menu.
*/
@@ -52,7 +55,7 @@ export function ReviewerPicker({
}) {
const { t } = useT('tasks');
const { t: tCommon } = useT('common');
- const { assignableMembers, currentUserId, resolveActor } =
+ const { assignableMembers, currentUserId, resolveActor, scopeReady } =
useAssignableActors(organizationId, projectId);
const [open, setOpen] = useState(false);
@@ -61,6 +64,7 @@ export function ReviewerPicker({
const label = resolved?.name ?? t('reviewer.none');
const options = useMemo(() => {
+ if (!scopeReady) return [];
const eligible = assignableMembers.filter(
(member) => member.role !== undefined && EDITOR_ROLES.has(member.role),
);
@@ -79,7 +83,7 @@ export function ReviewerPicker({
) : undefined,
}));
- }, [assignableMembers, currentUserId, t]);
+ }, [assignableMembers, currentUserId, scopeReady, t]);
const reviewerIsCurrentUser =
reviewerUserId !== undefined &&
@@ -140,7 +144,11 @@ export function ReviewerPicker({
modal
trigger={trigger}
searchPlaceholder={t('reviewer.search')}
- emptyText={tCommon('search.noResults')}
+ emptyText={
+ scopeReady
+ ? tCommon('search.noResults')
+ : tCommon('actions.loading')
+ }
aria-label={t('fields.reviewer')}
optionAction={(opt) => (
({
}),
}));
+/** What `listAccessibleUserIds` answers — undefined while it loads. */
+let accessScope: { orgWide: boolean; userIds: string[] } | undefined;
+
vi.mock('@/app/hooks/use-backend-query', () => ({
- useBackendQuery: () => ({ data: undefined }),
+ useBackendQuery: (name: string, args: unknown) => ({
+ data:
+ name === 'projects/queries:listAccessibleUserIds' && args !== 'skip'
+ ? accessScope
+ : undefined,
+ }),
}));
vi.mock('@/app/hooks/use-current-member-context', () => ({
@@ -143,3 +151,37 @@ describe('useActorDirectory — members + project-agent instances', () => {
expect(result.current.resolveAssigneeId('unknown-id')).toBe('unknown-id');
});
});
+
+/**
+ * The candidate lists are narrowed to the project's audience, and say when
+ * that narrowing has happened: until it has, the members are org-wide, so a
+ * picker that must offer only who the server takes (the reviewer's) waits.
+ */
+describe('useAssignableActors — the project audience', () => {
+ beforeEach(() => {
+ accessScope = undefined;
+ });
+
+ it('drops members outside a team-restricted project', () => {
+ accessScope = { orgWide: false, userIds: ['user-1'] };
+ const { result } = renderHook(() => useAssignableActors('org-1', 'proj-1'));
+ expect(result.current.scopeReady).toBe(true);
+ expect(result.current.assignableMembers.map((m) => m.id)).toEqual([
+ 'user-1',
+ ]);
+ });
+
+ it('is not ready while the audience loads, and falls back to the whole org', () => {
+ const { result } = renderHook(() => useAssignableActors('org-1', 'proj-1'));
+ expect(result.current.scopeReady).toBe(false);
+ expect(result.current.assignableMembers.map((m) => m.id)).toEqual([
+ 'user-1',
+ 'user-2',
+ ]);
+ });
+
+ it('is ready at once without a project — the org is the audience', () => {
+ const { result } = renderHook(() => useAssignableActors('org-1'));
+ expect(result.current.scopeReady).toBe(true);
+ });
+});
diff --git a/services/platform/app/features/tasks/hooks/use-actor-directory.ts b/services/platform/app/features/tasks/hooks/use-actor-directory.ts
index 7369d94d41..6367dec90d 100644
--- a/services/platform/app/features/tasks/hooks/use-actor-directory.ts
+++ b/services/platform/app/features/tasks/hooks/use-actor-directory.ts
@@ -303,6 +303,9 @@ export function useActorDirectory(organizationId: string, projectId?: string) {
* With no `projectId` members degrade to org-wide and agents to none — an
* agent exists only inside its project. While the access query is in flight,
* members fall back to org-wide; the backend guard is the real gate.
+ * `scopeReady` says whether that narrowing has happened, for a picker that
+ * must offer only who the server will take (the reviewer picker lists
+ * nobody until it is true).
*/
export function useAssignableActors(
organizationId: string,
@@ -325,6 +328,7 @@ export function useAssignableActors(
// Instances are project-curated by construction — the directory already
// scoped them to this project.
const assignableAgents = directory.agents;
+ const scopeReady = !projectId || scope.data !== undefined;
- return { ...directory, assignableMembers, assignableAgents };
+ return { ...directory, assignableMembers, assignableAgents, scopeReady };
}
diff --git a/services/platform/app/features/tasks/lib/reviewer-refusal.test.ts b/services/platform/app/features/tasks/lib/reviewer-refusal.test.ts
new file mode 100644
index 0000000000..10e109dc3f
--- /dev/null
+++ b/services/platform/app/features/tasks/lib/reviewer-refusal.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+
+import { AppError } from '@/lib/shared/errors/app-error';
+
+import { reviewerRefusalMessage } from './reviewer-refusal';
+
+const t = (key: string) => `tasks.${key}`;
+
+describe('reviewerRefusalMessage', () => {
+ it('explains a designee who cannot edit the project with the picker hint', () => {
+ expect(
+ reviewerRefusalMessage(
+ new AppError({ code: 'TASK_REVIEWER_NO_EDIT_ACCESS' }),
+ t,
+ ),
+ ).toBe('tasks.reviewer.editorsOnly');
+ });
+
+ it('explains a designee who is no longer a member the same way', () => {
+ expect(
+ reviewerRefusalMessage(
+ new AppError({ code: 'TASK_REVIEWER_INVALID' }),
+ t,
+ ),
+ ).toBe('tasks.reviewer.editorsOnly');
+ });
+
+ it('leaves every other failure to the caller', () => {
+ expect(
+ reviewerRefusalMessage(new AppError({ code: 'TASK_NOT_FOUND' }), t),
+ ).toBeUndefined();
+ expect(reviewerRefusalMessage(new Error('offline'), t)).toBeUndefined();
+ });
+});
diff --git a/services/platform/app/features/tasks/lib/reviewer-refusal.ts b/services/platform/app/features/tasks/lib/reviewer-refusal.ts
new file mode 100644
index 0000000000..416e5e67cb
--- /dev/null
+++ b/services/platform/app/features/tasks/lib/reviewer-refusal.ts
@@ -0,0 +1,21 @@
+import { backendErrorCode } from '@/lib/utils/backend-error';
+
+/**
+ * Localized copy for a refused **Reviewer** designation: the server takes
+ * only a live member who can edit the project — the rule the review gate
+ * resolves by — and the picker offers only those, so a refusal means the
+ * list went stale (someone lost access while it was open). Says what the
+ * picker's own hint says instead of the generic error toast.
+ */
+export function reviewerRefusalMessage(
+ error: unknown,
+ t: (key: string) => string,
+): string | undefined {
+ switch (backendErrorCode(error)) {
+ case 'TASK_REVIEWER_INVALID':
+ case 'TASK_REVIEWER_NO_EDIT_ACCESS':
+ return t('reviewer.editorsOnly');
+ default:
+ return undefined;
+ }
+}
diff --git a/services/platform/backend/domains/collab/service.test.ts b/services/platform/backend/domains/collab/service.test.ts
index d9b3865d34..366a4bd824 100644
--- a/services/platform/backend/domains/collab/service.test.ts
+++ b/services/platform/backend/domains/collab/service.test.ts
@@ -7,12 +7,14 @@ import { addJobInTx } from '../../jobs/enqueue.ts';
import { emitHintInTx } from '../../realtime/outbox.ts';
import type { CollabNotificationInput } from './service.ts';
import {
+ dismissReviewerAssignedNotifications,
dismissReviewRequestNotifications,
dismissTriggerPausedNotifications,
markAllNotificationsRead,
notifyTaskComment,
notifyTaskMentions,
notifyTaskReviewerAssigned,
+ notifyTaskReviewRequested,
notifyTriggerPaused,
writeCoalescedNotification,
} from './service.ts';
@@ -361,6 +363,87 @@ describe('the reviewer-designation heads-up (task_reviewer_assigned)', () => {
expect(calls).toEqual([]);
expect(vi.mocked(emitHintInTx)).not.toHaveBeenCalled();
});
+
+ it('a moved designation marks only the former designee’s unread heads-up on this task read, and hints them', async () => {
+ // Before the fix a change of reviewer ahead of In review left "You're
+ // the reviewer" ringing for the person it was taken from.
+ const { db, calls } = recordingDb((text) =>
+ text.startsWith('UPDATE app.user_notifications') ? [{ id: 'n-1' }] : [],
+ );
+ await expect(
+ dismissReviewerAssignedNotifications(db, {
+ organizationId: 'org-1',
+ taskId: 'task-1',
+ userId: 'u-recipient',
+ }),
+ ).resolves.toBe(1);
+ const update = calls.find((call) =>
+ call.text.startsWith('UPDATE app.user_notifications'),
+ );
+ expect(update?.text).toContain('read = true');
+ expect(update?.text).toContain("type = 'task_reviewer_assigned'");
+ expect(update?.text).toContain('read = false');
+ expect(update?.values).toEqual(
+ expect.arrayContaining(['org-1', 'u-recipient', 'task-1']),
+ );
+ expect(vi.mocked(emitHintInTx)).toHaveBeenCalledTimes(1);
+ expect(vi.mocked(emitHintInTx)).toHaveBeenCalledWith(db, {
+ orgId: 'org-1',
+ userId: 'u-recipient',
+ entity: NOTIFICATION_HINT_ENTITY,
+ entityId: null,
+ });
+ });
+
+ it('a moved designation with no unread heads-up hints nobody', async () => {
+ const { db } = recordingDb(() => []);
+ await expect(
+ dismissReviewerAssignedNotifications(db, {
+ organizationId: 'org-1',
+ taskId: 'task-1',
+ userId: 'u-recipient',
+ }),
+ ).resolves.toBe(0);
+ expect(vi.mocked(emitHintInTx)).not.toHaveBeenCalled();
+ });
+
+ it('a review handed over by no person (an erasure) asks impersonally, as the system', async () => {
+ const { db, calls } = recordingDb((text) =>
+ text.startsWith('INSERT INTO app.user_notifications')
+ ? [{ id: 'n-request' }]
+ : [],
+ );
+ await notifyTaskReviewRequested(db, {
+ organizationId: 'org-1',
+ task: designation.task,
+ reviewerUserId: 'u-recipient',
+ approvalId: 'approval-1',
+ submitter: { kind: 'system' },
+ });
+ // No actor to name: nobody's display name is read.
+ expect(calls.some((call) => call.text.includes('FROM "user"'))).toBe(false);
+ const insert = calls.find((call) =>
+ call.text.startsWith('INSERT INTO app.user_notifications'),
+ );
+ expect(insert?.values).toEqual(
+ expect.arrayContaining([
+ 'u-recipient',
+ 'task_review_requested',
+ 'taskReviewRequested',
+ 'taskReviewRequestedBodyHuman',
+ 'task_review',
+ 'approval-1',
+ 'system',
+ null,
+ ]),
+ );
+ expect(insert?.values).toContainEqual({
+ taskId: 'task-1',
+ projectId: 'proj-1',
+ taskTitle: 'Ship the brief',
+ approvalId: 'approval-1',
+ });
+ });
});
describe('the mention bell, per surface', () => {
diff --git a/services/platform/backend/domains/collab/service.ts b/services/platform/backend/domains/collab/service.ts
index e10341e64d..5beb08c61f 100644
--- a/services/platform/backend/domains/collab/service.ts
+++ b/services/platform/backend/domains/collab/service.ts
@@ -574,9 +574,12 @@ async function resolveUserDisplayName(
return row?.name ?? row?.email ?? null;
}
+/** Who asks for the review. `system` is a hand-over no person made (an
+ * erasure moving a review off its subject): the request reads impersonally. */
export type TaskReviewSubmitter =
| { kind: 'agent'; name?: string }
- | { kind: 'user'; userId: string };
+ | { kind: 'user'; userId: string }
+ | { kind: 'system' };
/** Actionable review request to the designated reviewer (pref gate skipped —
* the review group is locked on). */
@@ -629,10 +632,12 @@ export async function notifyTaskReviewRequested(
taskId: args.task.id,
...(args.submitter.kind === 'user'
? { actorType: 'user' as const, actorId: args.submitter.userId }
- : {
- actorType: 'agent' as const,
- ...(agentName !== undefined ? { actorId: agentName } : {}),
- }),
+ : args.submitter.kind === 'system'
+ ? { actorType: 'system' as const }
+ : {
+ actorType: 'agent' as const,
+ ...(agentName !== undefined ? { actorId: agentName } : {}),
+ }),
});
}
@@ -702,6 +707,33 @@ export async function dismissReviewRequestNotifications(
return rows.length;
}
+/**
+ * Mark a former designee's unread "You're the reviewer" heads-up on this
+ * task read — the designation moved off them before the review opened, so
+ * the bell must stop telling them they are on the hook. Only the heads-up:
+ * a request the open review sent them is `dismissReviewRequestNotifications`'
+ * (per approval), and a read row is history and stays as it is.
+ */
+export async function dismissReviewerAssignedNotifications(
+ db: Db,
+ args: { organizationId: string; taskId: string; userId: string },
+): Promise {
+ const rows = await db<{ id: string }[]>`
+ UPDATE app.user_notifications SET read = true, read_at_ms = ${Date.now()}
+ WHERE org_id = ${args.organizationId} AND user_id = ${args.userId}
+ AND type = 'task_reviewer_assigned' AND read = false
+ AND task_id = ${args.taskId}
+ RETURNING id
+ `;
+ if (rows.length > 0) {
+ await emitBellHint(db, {
+ organizationId: args.organizationId,
+ userId: args.userId,
+ });
+ }
+ return rows.length;
+}
+
/**
* Mark the owner's unread cloud-sync failure rows for one config read — the
* run that recovered did what the row asked for, so the bell stops ringing
diff --git a/services/platform/backend/domains/erasure/review-handover.integration.ts b/services/platform/backend/domains/erasure/review-handover.integration.ts
new file mode 100644
index 0000000000..8e0dcb9871
--- /dev/null
+++ b/services/platform/backend/domains/erasure/review-handover.integration.ts
@@ -0,0 +1,187 @@
+/** Real Postgres interleavings: erasure must neither undo a newer reviewer
+ * designation nor ask someone to review an approval already completed. */
+import { randomUUID } from 'node:crypto';
+
+import { transactSerializable } from '@tale/shared/db/serializable';
+import type { Sql, TransactionSql } from 'postgres';
+
+import { updateTask, updateTaskStatus } from '../tasks/service.ts';
+import { processErasure } from './service.ts';
+
+function signal() {
+ let release = () => {};
+ const promise = new Promise((resolve) => {
+ release = resolve;
+ });
+ return { promise, release };
+}
+
+/** Keep every read/write real. Only the first routing write pauses, after
+ * the task and pending review were read but before the competing commit.
+ * A serialization retry must run freely against its fresh snapshot. */
+function pauseFirstHandover(sql: Sql, pause: () => Promise): Sql {
+ let paused = false;
+ const wrap = (tx: TransactionSql): TransactionSql =>
+ new Proxy(tx, {
+ apply(target, thisArg, args: unknown[]) {
+ const strings = args[0];
+ if (
+ !paused &&
+ Array.isArray(strings) &&
+ /UPDATE app\.approvals SET\s+metadata = coalesce/.test(
+ strings.join(''),
+ )
+ ) {
+ paused = true;
+ return pause().then(() => Reflect.apply(target, thisArg, args));
+ }
+ return Reflect.apply(target, thisArg, args);
+ },
+ });
+ type Callback = (tx: TransactionSql) => Promise;
+ return new Proxy(sql, {
+ get(target, property, receiver) {
+ if (property !== 'begin') return Reflect.get(target, property, receiver);
+ return (options: string | Callback, callback?: Callback) => {
+ if (typeof options === 'function') {
+ return target.begin((tx) => options(wrap(tx)));
+ }
+ if (!callback) throw new Error('Missing transaction callback');
+ return target.begin(options, (tx) => callback(wrap(tx)));
+ };
+ },
+ });
+}
+
+export async function checkErasureReviewHandoverRaces(
+ sql: Sql,
+ ctx: { userId: string },
+ record: (name: string, ok: boolean, detail: string) => void,
+): Promise {
+ for (const rival of ['designation', 'decision'] as const) {
+ const orgId = randomUUID();
+ const projectId = randomUUID();
+ const taskId = randomUUID();
+ const approvalId = randomUUID();
+ const requestId = randomUUID();
+ const subject = `erasure-race-subject-${orgId}`;
+ const reviewer = `erasure-race-reviewer-${orgId}`;
+ const now = Date.now();
+ const auth = {
+ organizationId: orgId,
+ userId: ctx.userId,
+ role: 'owner',
+ teamIds: [] as string[],
+ };
+ await sql`
+ INSERT INTO "organization" ("id", "name", "slug", "createdAt")
+ VALUES (${orgId}, 'Erasure handover race', ${`itest-erasure-race-${orgId}`}, now())
+ `;
+ for (const id of [subject, reviewer]) {
+ await sql`
+ INSERT INTO "user" ("id", "name", "email", "emailVerified", "createdAt", "updatedAt")
+ VALUES (${id}, 'Erasure race member', ${`${id}@example.com`}, true, now(), now())
+ `;
+ }
+ for (const id of [ctx.userId, subject, reviewer]) {
+ await sql`
+ INSERT INTO "member" ("id", "organizationId", "userId", "role", "createdAt")
+ VALUES (${randomUUID()}, ${orgId}, ${id}, 'owner', now())
+ `;
+ }
+ await sql`
+ INSERT INTO app.projects (id, org_id, name, created_by, created_at_ms, updated_at_ms)
+ VALUES (${projectId}, ${orgId}, 'Handover race', ${ctx.userId}, ${now}, ${now})
+ `;
+ // The pending recipient need not be the explicit designation (a creator
+ // can be selected by the fallback chain). With no matching designation
+ // to clear, erasure holds no task-row write lock before its routing read.
+ await sql`
+ INSERT INTO app.tasks (id, org_id, project_id, title, status, rank,
+ created_by, created_by_type, created_at_ms, updated_at_ms)
+ VALUES (${taskId}, ${orgId}, ${projectId}, 'Waiting for review', 'in_review',
+ 'a0', ${ctx.userId}, 'user', ${now}, ${now})
+ `;
+ await sql`
+ INSERT INTO app.approvals (id, org_id, resource_type, resource_id, status,
+ metadata, created_at_ms)
+ VALUES (${approvalId}, ${orgId}, 'task_review', ${taskId}, 'pending',
+ ${sql.json({ requestedFor: subject, taskId, projectId, round: 0 })}, ${now})
+ `;
+ // Directly file an isolated receipt: only this invocation runs it, so a
+ // job worker cannot consume it before the barrier is installed.
+ await sql`
+ INSERT INTO app.gdpr_erasure_requests (id, org_id, target_user_id, reason,
+ reason_code, requested_by, requested_at_ms, sla_deadline_at_ms, status)
+ VALUES (${requestId}, ${orgId}, ${subject}, 'Concurrency regression',
+ 'consent_withdrawn', ${ctx.userId}, ${now}, ${now + 86_400_000}, 'pending')
+ `;
+
+ const reached = signal();
+ const resume = signal();
+ const pausedSql = pauseFirstHandover(sql, async () => {
+ reached.release();
+ await resume.promise;
+ });
+ const erasure = processErasure(pausedSql, requestId);
+ let timeout: ReturnType | undefined;
+ try {
+ await Promise.race([
+ reached.promise,
+ erasure.then(() => {
+ throw new Error('Erasure finished without reaching the handover');
+ }),
+ new Promise((_resolve, reject) => {
+ timeout = setTimeout(
+ () => reject(new Error('Erasure handover barrier timed out')),
+ 10_000,
+ );
+ }),
+ ]);
+ // These are the real competing domain writes, committed while the
+ // erasure still carries its earlier task/approval snapshot.
+ await transactSerializable(sql, async (tx) => {
+ await tx`SET LOCAL statement_timeout = '10s'`;
+ if (rival === 'designation') {
+ await updateTask(tx, auth, { taskId, reviewerUserId: reviewer });
+ } else {
+ await updateTaskStatus(tx, auth, taskId, 'done');
+ }
+ });
+ } finally {
+ if (timeout !== undefined) clearTimeout(timeout);
+ resume.release();
+ await erasure;
+ }
+
+ const [task] = await sql<{ reviewer: string | null; status: string }[]>`
+ SELECT reviewer_user_id AS reviewer, status FROM app.tasks
+ WHERE id = ${taskId} AND org_id = ${orgId}
+ `;
+ const [approval] = await sql<
+ { recipient: string | null; status: string }[]
+ >`
+ SELECT metadata->>'requestedFor' AS recipient, status FROM app.approvals
+ WHERE id = ${approvalId} AND org_id = ${orgId}
+ `;
+ const [staleBells] = await sql<{ count: number }[]>`
+ SELECT count(*)::int AS count FROM app.user_notifications
+ WHERE org_id = ${orgId} AND resource_id = ${approvalId}
+ AND type = 'task_review_requested' AND user_id = ${ctx.userId}
+ `;
+ const [receipt] = await sql<{ status: string }[]>`
+ SELECT status FROM app.gdpr_erasure_requests WHERE id = ${requestId}
+ `;
+ const routingPreserved =
+ rival === 'designation'
+ ? task?.reviewer === reviewer &&
+ approval?.recipient === reviewer &&
+ approval.status === 'pending'
+ : task?.status === 'done' && approval?.status === 'completed';
+ record(
+ `erasure handover preserves a concurrently committed ${rival}`,
+ routingPreserved && staleBells?.count === 0 && receipt?.status === 'done',
+ `task=${task?.status}/${task?.reviewer === reviewer ? 'new-reviewer' : String(task?.reviewer)}, review=${approval?.status}/${approval?.recipient === reviewer ? 'new-reviewer' : approval?.recipient === ctx.userId ? 'creator' : String(approval?.recipient)}, stale requests=${staleBells?.count} (want 0), receipt=${receipt?.status} (want done)`,
+ );
+ }
+}
diff --git a/services/platform/backend/domains/erasure/service.lifecycle.test.ts b/services/platform/backend/domains/erasure/service.lifecycle.test.ts
index 3dd18bb5c6..5e06eabd42 100644
--- a/services/platform/backend/domains/erasure/service.lifecycle.test.ts
+++ b/services/platform/backend/domains/erasure/service.lifecycle.test.ts
@@ -8,7 +8,8 @@
* check; these pin the transitions that used to be silent or unguarded —
* the Retry of a receipt blocked at filing (policy re-applied, CAS re-arm),
* the execution-time hold block (audited), the limiter outage (not a
- * denial), and the project-agent-runs pass.
+ * denial), the project-agent-runs pass, and the review pass handing a
+ * waiting review on instead of stamping it with the pseudonym.
*/
import type { Sql } from 'postgres';
@@ -24,6 +25,9 @@ import { emitHintInTx } from '../../realtime/outbox.ts';
import { createAuditLog } from '../audit_logs/service.ts';
import { loadActiveHolds } from '../legal_holds/service.ts';
import { writeNotificationForOrgs } from '../notifications/service.ts';
+import { TaskError } from '../tasks/errors.ts';
+import { retargetPendingTaskReview } from '../tasks/reviews.ts';
+import { loadTaskOrThrow, type TaskRow } from '../tasks/service.ts';
import {
ErasureError,
getErasureRequest,
@@ -63,6 +67,8 @@ vi.mock('../retention/service.ts', () => ({
purgeThreadLineage: vi.fn(() => Promise.resolve(0)),
purgeDocument: vi.fn(),
}));
+vi.mock('../tasks/reviews.ts', () => ({ retargetPendingTaskReview: vi.fn() }));
+vi.mock('../tasks/service.ts', () => ({ loadTaskOrThrow: vi.fn() }));
interface Statement {
text: string;
@@ -90,7 +96,16 @@ function fakeSql(
statements.push({ text, values });
return Promise.resolve(answer(text, values) ?? []);
};
- tag.begin = (callback: (tx: typeof tag) => unknown): unknown => callback(tag);
+ tag.begin = (
+ optionsOrCallback: string | ((tx: typeof tag) => unknown),
+ callback?: (tx: typeof tag) => unknown,
+ ): unknown => {
+ if (typeof optionsOrCallback === 'string') {
+ statements.push({ text: `BEGIN ${optionsOrCallback}`, values: [] });
+ return callback?.(tag);
+ }
+ return optionsOrCallback(tag);
+ };
tag.json = (value: unknown): unknown => value;
return { sql: tag as unknown as Sql, statements };
}
@@ -441,6 +456,301 @@ describe('processErasure', () => {
});
});
+/**
+ * A review still waiting on the subject is routing, not history: stamping
+ * it with the pseudonym left it waiting on nobody — on no board and in no
+ * bell. It moves on through the chain a cleared designation takes, the
+ * subject excluded, and only what still names the subject afterwards is
+ * pseudonymized.
+ */
+describe('processErasure — the review pass', () => {
+ it('hands a waiting review on through the cleared chain, then pseudonymizes what still names the subject', async () => {
+ vi.mocked(loadActiveHolds).mockResolvedValue(noHolds);
+ const task = {
+ id: 'task-1',
+ reviewerUserId: null,
+ archivedAt: null,
+ } as unknown as TaskRow;
+ const fake = fakeSql((text, values) => {
+ if (
+ text.startsWith(
+ "UPDATE app.gdpr_erasure_requests SET status = 'running'",
+ )
+ )
+ return [
+ {
+ organizationId: 'org_1',
+ targetUserId: 'subject',
+ status: 'running',
+ },
+ ];
+ if (text.startsWith('SELECT id FROM app.tasks'))
+ return [{ id: 'task-1' }];
+ if (text.startsWith('UPDATE app.tasks SET reviewer_user_id = NULL'))
+ return values[0] === 'task-1' ? [{ id: 'task-1' }] : [];
+ if (text.startsWith('SELECT id FROM app.approvals'))
+ return [{ id: 'review-open' }];
+ if (text.startsWith('SELECT id, resource_id AS "taskId"'))
+ return [
+ { id: 'review-open', taskId: 'task-1' },
+ { id: 'review-orphan', taskId: 'task-gone' },
+ ];
+ if (text.startsWith('SELECT id, approved_by AS "approvedBy"'))
+ return [
+ // The orphan has no task to move to, so it keeps the old stamp.
+ {
+ id: 'review-orphan',
+ approvedBy: null,
+ metadata: { requestedFor: 'subject', round: 0 },
+ },
+ {
+ id: 'review-decided',
+ approvedBy: 'subject',
+ metadata: {
+ requestedFor: 'subject',
+ response: { decision: 'approve', respondedBy: 'subject' },
+ },
+ },
+ ];
+ if (text.startsWith('SELECT EXISTS')) return [{ elsewhere: false }];
+ return undefined;
+ });
+ let statementsAtLoad = -1;
+ vi.mocked(loadTaskOrThrow).mockImplementation((_tx, taskId) => {
+ if (taskId !== 'task-1') {
+ return Promise.reject(
+ new TaskError('TASK_NOT_FOUND', 'Task not found', 404),
+ );
+ }
+ statementsAtLoad = fake.statements.length;
+ return Promise.resolve(task);
+ });
+
+ await processErasure(fake.sql, 'req-1');
+
+ // The designation is cleared BEFORE the chain runs, so the chain starts
+ // past the subject's designation — and the subject is excluded from the
+ // creator slots too (they are still a member until removed).
+ const clearedAt = fake.statements.findIndex((s) =>
+ s.text.startsWith('UPDATE app.tasks SET reviewer_user_id = NULL'),
+ );
+ expect(clearedAt).toBeGreaterThanOrEqual(0);
+ expect(statementsAtLoad).toBeGreaterThan(clearedAt);
+ expect(loadTaskOrThrow).toHaveBeenCalledWith(
+ expect.anything(),
+ 'task-1',
+ 'org_1',
+ );
+ expect(retargetPendingTaskReview).toHaveBeenCalledTimes(1);
+ const transactionAt = fake.statements.findIndex(
+ (s) => s.text === 'BEGIN isolation level serializable',
+ );
+ expect(transactionAt).toBeGreaterThanOrEqual(0);
+ expect(clearedAt).toBeGreaterThan(transactionAt);
+ expect(emitHintInTx).toHaveBeenCalledWith(expect.anything(), {
+ orgId: 'org_1',
+ entity: 'task',
+ entityId: 'task-1',
+ });
+ expect(retargetPendingTaskReview).toHaveBeenCalledWith(expect.anything(), {
+ task,
+ excludeUserId: 'subject',
+ silent: false,
+ });
+ // Only rows that still name the subject after the hand-over get the
+ // pseudonym; the handed-over review is not rewritten to it.
+ const pseudonymized = fake.statements
+ .filter((s) => s.text.startsWith('UPDATE app.approvals SET approved_by'))
+ .map((s) => s.values);
+ expect(pseudonymized).toEqual([
+ [null, { requestedFor: 'erased-user', round: 0 }, 'review-orphan'],
+ [
+ 'erased-user',
+ {
+ requestedFor: 'erased-user',
+ response: { decision: 'approve', respondedBy: 'erased-user' },
+ },
+ 'review-decided',
+ ],
+ ]);
+ const settle = fake.statements.find(
+ (s) =>
+ s.text.startsWith('UPDATE app.gdpr_erasure_requests SET status = ?') &&
+ s.text.includes('counts = ?'),
+ );
+ expect(settle?.values[0]).toBe('done');
+ // One handed over, two pseudonymized, one designation cleared.
+ expect(settle?.values[2]).toMatchObject({ reviewDecisions: 4 });
+ });
+
+ it('leaves a review that was reassigned after discovery with its new reviewer', async () => {
+ vi.mocked(loadActiveHolds).mockResolvedValue(noHolds);
+ const fake = fakeSql((text) => {
+ if (
+ text.startsWith(
+ "UPDATE app.gdpr_erasure_requests SET status = 'running'",
+ )
+ ) {
+ return [
+ {
+ organizationId: 'org_1',
+ targetUserId: 'subject',
+ status: 'running',
+ },
+ ];
+ }
+ if (text.startsWith('SELECT id, resource_id AS "taskId"')) {
+ return [{ id: 'review-open', taskId: 'task-1' }];
+ }
+ if (text.startsWith('SELECT EXISTS')) return [{ elsewhere: false }];
+ // No designation or pending review still points to the subject in
+ // the transaction: the concurrent edit already handed it over.
+ return undefined;
+ });
+ vi.mocked(loadTaskOrThrow).mockResolvedValue({
+ id: 'task-1',
+ reviewerUserId: 'new-reviewer',
+ } as unknown as TaskRow);
+
+ await processErasure(fake.sql, 'req-1');
+
+ expect(retargetPendingTaskReview).not.toHaveBeenCalled();
+ expect(emitHintInTx).not.toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ entity: 'task' }),
+ );
+ const settle = fake.statements.find(
+ (s) =>
+ s.text.startsWith('UPDATE app.gdpr_erasure_requests SET status = ?') &&
+ s.text.includes('counts = ?'),
+ );
+ expect(settle?.values[2]).toMatchObject({ reviewDecisions: 0 });
+ });
+});
+
+/**
+ * The two ways a hand-over can go other than plainly: an archived task,
+ * whose card nobody sees, and a hand-over that throws — which must hold
+ * back neither the designation's clear nor the pseudonym.
+ */
+describe('processErasure — the review pass, off the plain path', () => {
+ /** `task-1` is designated to the subject and its review waits on them. */
+ function reviewPassSql() {
+ return fakeSql((text, values) => {
+ if (
+ text.startsWith(
+ "UPDATE app.gdpr_erasure_requests SET status = 'running'",
+ )
+ )
+ return [
+ {
+ organizationId: 'org_1',
+ targetUserId: 'subject',
+ status: 'running',
+ },
+ ];
+ if (text.startsWith('SELECT id FROM app.tasks'))
+ return [{ id: 'task-1' }];
+ if (text.startsWith('UPDATE app.tasks SET reviewer_user_id = NULL'))
+ return values[0] === 'task-1' ? [{ id: 'task-1' }] : [];
+ if (text.startsWith('SELECT id FROM app.approvals'))
+ return [{ id: 'review-open' }];
+ if (text.startsWith('SELECT id, resource_id AS "taskId"'))
+ return [{ id: 'review-open', taskId: 'task-1' }];
+ if (text.startsWith('SELECT id, approved_by AS "approvedBy"'))
+ return [
+ {
+ id: 'review-open',
+ approvedBy: null,
+ metadata: { requestedFor: 'subject', round: 0 },
+ },
+ {
+ id: 'review-decided',
+ approvedBy: 'subject',
+ metadata: {
+ requestedFor: 'subject',
+ response: { decision: 'approve', respondedBy: 'subject' },
+ },
+ },
+ ];
+ if (text.startsWith('SELECT EXISTS')) return [{ elsewhere: false }];
+ return undefined;
+ });
+ }
+
+ function settled(fake: ReturnType): unknown[] | undefined {
+ return fake.statements.find(
+ (s) =>
+ s.text.startsWith('UPDATE app.gdpr_erasure_requests SET status = ?') &&
+ s.text.includes('counts = ?'),
+ )?.values;
+ }
+
+ it('moves the routing of an archived task without asking anyone', async () => {
+ vi.mocked(loadActiveHolds).mockResolvedValue(noHolds);
+ const task = {
+ id: 'task-1',
+ reviewerUserId: null,
+ archivedAt: 1_700_000_000_000,
+ } as unknown as TaskRow;
+ vi.mocked(loadTaskOrThrow).mockResolvedValue(task);
+
+ await processErasure(reviewPassSql().sql, 'req-1');
+
+ expect(retargetPendingTaskReview).toHaveBeenCalledWith(expect.anything(), {
+ task,
+ excludeUserId: 'subject',
+ silent: true,
+ });
+ });
+
+ it('still clears the designation and pseudonymizes everything when a hand-over fails', async () => {
+ vi.mocked(loadActiveHolds).mockResolvedValue(noHolds);
+ vi.mocked(loadTaskOrThrow).mockResolvedValue({
+ id: 'task-1',
+ reviewerUserId: null,
+ archivedAt: null,
+ } as unknown as TaskRow);
+ vi.mocked(retargetPendingTaskReview).mockRejectedValue(
+ new Error('email queue down'),
+ );
+ const error = vi
+ .spyOn(console, 'error')
+ .mockImplementation(() => undefined);
+ const fake = reviewPassSql();
+
+ await processErasure(fake.sql, 'req-1');
+
+ expect(error).toHaveBeenCalledWith(
+ '[erasure] handing on the review of task task-1 failed:',
+ expect.any(Error),
+ );
+ // The serializable attempt rolled back; the designation goes in a
+ // transaction of its own, and the board still hears about it.
+ const clears = fake.statements.filter((s) =>
+ s.text.startsWith('UPDATE app.tasks SET reviewer_user_id = NULL'),
+ );
+ expect(clears).toHaveLength(2);
+ expect(emitHintInTx).toHaveBeenCalledWith(expect.anything(), {
+ orgId: 'org_1',
+ entity: 'task',
+ entityId: 'task-1',
+ });
+ // The waiting row falls to the pseudonym as before hand-overs existed,
+ // and the decision loses the subject's id: nothing is held back and the
+ // pass is not reported as failed.
+ const pseudonymized = fake.statements
+ .filter((s) => s.text.startsWith('UPDATE app.approvals SET approved_by'))
+ .map((s) => s.values[2]);
+ expect(pseudonymized).toEqual(['review-open', 'review-decided']);
+ const settle = settled(fake);
+ expect(settle?.[0]).toBe('done');
+ // Two pseudonymized, one designation cleared, none handed over.
+ expect(settle?.[2]).toMatchObject({ reviewDecisions: 3 });
+ error.mockRestore();
+ });
+});
+
describe('requestErasure — the hold gate at filing', () => {
it('files a durable blocked receipt that records the org-wide hold', async () => {
vi.mocked(checkOrganizationRateLimit).mockResolvedValue(undefined as never);
diff --git a/services/platform/backend/domains/erasure/service.ts b/services/platform/backend/domains/erasure/service.ts
index ac4e9e4f75..f9223da2dd 100644
--- a/services/platform/backend/domains/erasure/service.ts
+++ b/services/platform/backend/domains/erasure/service.ts
@@ -1,3 +1,4 @@
+import { transactSerializable } from '@tale/shared/db/serializable';
import type { Sql, TransactionSql } from 'postgres';
import { isRecord } from '../../../lib/utils/type-utils.ts';
@@ -24,6 +25,9 @@ import { createAuditLog } from '../audit_logs/service.ts';
import { applyMaturedDsarPolicyChange } from '../governance/settings-tail.ts';
import { type ActiveHolds, loadActiveHolds } from '../legal_holds/service.ts';
import { writeNotificationForOrgs } from '../notifications/service.ts';
+import { TaskError } from '../tasks/errors.ts';
+import { retargetPendingTaskReview } from '../tasks/reviews.ts';
+import { loadTaskOrThrow, type TaskRow } from '../tasks/service.ts';
import { hintVideoJobs } from '../video_links/hints.ts';
/**
@@ -1159,10 +1163,115 @@ export async function processErasure(
// Review decisions are pseudonymized rather than deleted: the decision is
// the audit record of a governance gate, so the row stays and the identity
- // goes. `tasks.reviewer_user_id` is different — it is live routing, not
- // history, so it is cleared. Leaving it pointed at an erased user sends
- // the next review to nobody.
+ // goes. Routing is different — it is live, not history. `tasks.
+ // reviewer_user_id` is cleared: leaving it pointed at an erased user sends
+ // the next review to nobody. A review still WAITING on the subject moves
+ // on through the chain a cleared designation takes (human task creator →
+ // project creator), never back to the subject; stamped with the pseudonym
+ // instead, it waited on nobody — on no board and in no bell. Only then is
+ // what still names the subject pseudonymized: the decisions, the
+ // workflow-era rows every review door leaves alone, and a waiting row
+ // whose task is gone, that was decided in the meantime, or whose hand-over
+ // failed — routing never holds back the erasure of history.
await pass('reviewDecisions', async () => {
+ const clearDesignation = (tx: TransactionSql, taskId: string) =>
+ tx<{ id: string }[]>`
+ UPDATE app.tasks SET reviewer_user_id = NULL
+ WHERE id = ${taskId} AND org_id = ${organizationId}
+ AND reviewer_user_id = ${targetUserId}
+ RETURNING id
+ `;
+ const designated = await sql<{ id: string }[]>`
+ SELECT id FROM app.tasks
+ WHERE org_id = ${organizationId}
+ AND reviewer_user_id = ${targetUserId}
+ `;
+ const waiting = await sql<{ id: string; taskId: string }[]>`
+ SELECT id, resource_id AS "taskId" FROM app.approvals
+ WHERE org_id = ${organizationId} AND resource_type = 'task_review'
+ AND status = 'pending' AND wf_execution_id IS NULL
+ AND metadata->>'requestedFor' = ${targetUserId}
+ `;
+ let cleared = 0;
+ let handedOver = 0;
+ const taskIds = new Set([
+ ...designated.map((row) => row.id),
+ ...waiting.map((row) => row.taskId),
+ ]);
+ for (const taskId of taskIds) {
+ // The designation, review and hint move together. A concurrent task
+ // edit retries this read instead of letting a stale reviewer overwrite
+ // the designation that edit just selected.
+ let moved: { cleared: number; handedOver: number };
+ try {
+ moved = await transactSerializable(sql, async (tx) => {
+ const removed = await clearDesignation(tx, taskId);
+ let task: TaskRow;
+ try {
+ task = await loadTaskOrThrow(tx, taskId, organizationId);
+ } catch (error) {
+ // A row whose task is gone has nowhere to move: the pseudonym
+ // below covers it.
+ if (error instanceof TaskError && error.code === 'TASK_NOT_FOUND') {
+ return { cleared: removed.length, handedOver: 0 };
+ }
+ throw error;
+ }
+ // Discovery was outside this transaction: someone may already have
+ // decided or reassigned the review. Only a request still addressed
+ // to the subject needs a handover.
+ const pending = await tx<{ id: string }[]>`
+ SELECT id FROM app.approvals
+ WHERE org_id = ${organizationId} AND resource_type = 'task_review'
+ AND resource_id = ${taskId} AND status = 'pending'
+ AND wf_execution_id IS NULL
+ AND metadata->>'requestedFor' = ${targetUserId}
+ `;
+ if (pending.length > 0) {
+ // An archived task keeps its open review (archiving closes no
+ // gate), so the routing still moves — a restore must not bring
+ // back a review waiting on nobody — but nobody is asked about a
+ // card hidden from the board.
+ await retargetPendingTaskReview(tx, {
+ task,
+ excludeUserId: targetUserId,
+ silent: task.archivedAt !== null,
+ });
+ }
+ if (removed.length > 0 || pending.length > 0) {
+ await emitHintInTx(tx, {
+ orgId: organizationId,
+ entity: 'task',
+ entityId: taskId,
+ });
+ }
+ return { cleared: removed.length, handedOver: pending.length };
+ });
+ } catch (error) {
+ // Everything in that transaction rolled back. The designation still
+ // goes — it is the subject's id on live routing — and the waiting
+ // row falls to the pseudonym below, as before hand-overs existed: a
+ // failed hand-over must not keep the subject's id on this or any
+ // later task, nor on the decisions after it.
+ console.error(
+ `[erasure] handing on the review of task ${taskId} failed:`,
+ error,
+ );
+ moved = await sql.begin(async (tx) => {
+ const removed = await clearDesignation(tx, taskId);
+ if (removed.length > 0) {
+ await emitHintInTx(tx, {
+ orgId: organizationId,
+ entity: 'task',
+ entityId: taskId,
+ });
+ }
+ return { cleared: removed.length, handedOver: 0 };
+ });
+ }
+ cleared += moved.cleared;
+ handedOver += moved.handedOver;
+ }
const decisions = await sql<
{ id: string; approvedBy: string | null; metadata: unknown }[]
>`
@@ -1193,13 +1302,7 @@ export async function processErasure(
`;
changed++;
}
- const cleared = await sql<{ id: string }[]>`
- UPDATE app.tasks SET reviewer_user_id = NULL
- WHERE org_id = ${organizationId}
- AND reviewer_user_id = ${targetUserId}
- RETURNING id
- `;
- return changed + cleared.length;
+ return handedOver + changed + cleared;
});
// Global auth state: the lockout trail is keyed by email and the two-factor
diff --git a/services/platform/backend/domains/tasks/reviews.retarget.test.ts b/services/platform/backend/domains/tasks/reviews.retarget.test.ts
index 002370ec26..076332afbc 100644
--- a/services/platform/backend/domains/tasks/reviews.retarget.test.ts
+++ b/services/platform/backend/domains/tasks/reviews.retarget.test.ts
@@ -1,13 +1,20 @@
import type { TransactionSql } from 'postgres';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { findOrganizationMember } from '../../auth/membership.ts';
+import {
+ findOrganizationMember,
+ getUserTeamIds,
+} from '../../auth/membership.ts';
import {
autoSubscribe,
dismissReviewRequestNotifications,
notifyTaskReviewRequested,
} from '../collab/service.ts';
-import { type ApprovalRow, retargetPendingTaskReview } from './reviews.ts';
+import {
+ type ApprovalRow,
+ retargetPendingTaskReview,
+ reviewerEligibility,
+} from './reviews.ts';
import type { TaskRow } from './service.ts';
vi.mock('../../auth/membership.ts', () => ({
@@ -152,6 +159,7 @@ beforeEach(() => {
: { id: `m-${userId}`, organizationId, userId, role },
);
});
+ vi.mocked(getUserTeamIds).mockReset().mockResolvedValue([]);
vi.mocked(autoSubscribe).mockReset();
vi.mocked(dismissReviewRequestNotifications).mockReset();
vi.mocked(notifyTaskReviewRequested).mockReset();
@@ -318,3 +326,132 @@ describe('retargetPendingTaskReview', () => {
expect(notifyTaskReviewRequested).not.toHaveBeenCalled();
});
});
+
+/**
+ * An erasure moves a review off its subject through the same chain, never
+ * back to the subject: they stay a member until someone removes them, so
+ * the chain would otherwise hand the review straight back through a creator
+ * slot. No person made the change, so the request reads impersonally.
+ */
+describe('retargetPendingTaskReview — moving a review off an erased subject', () => {
+ it('skips the subject in the creator slot and asks the project creator, as the system', async () => {
+ const { tx, statements } = fakeTx(
+ [approval({ metadata: { taskId: 't-1', requestedFor: 'u-carol' } })],
+ { createdBy: 'u-lead', teamIds: [] },
+ );
+
+ const waitsOn = await retargetPendingTaskReview(tx, {
+ // The erasure cleared the subject's designation first.
+ task: taskRow({ reviewerUserId: null, createdBy: 'u-carol' }),
+ excludeUserId: 'u-carol',
+ });
+
+ expect(waitsOn).toBe('u-lead');
+ expect(approvalWrites(statements)).toEqual([
+ [{ json: { requestedFor: 'u-lead' } }, 'apv-1'],
+ ]);
+ expect(findOrganizationMember).not.toHaveBeenCalledWith(
+ tx,
+ 'org-1',
+ 'u-carol',
+ );
+ expect(autoSubscribe).toHaveBeenCalledWith(
+ tx,
+ expect.objectContaining({ subscriberId: 'u-lead', reason: 'reviewer' }),
+ );
+ expect(notifyTaskReviewRequested).toHaveBeenCalledWith(tx, {
+ organizationId: 'org-1',
+ task: { id: 't-1', projectId: 'p-1', title: 'Ship the launch notes' },
+ reviewerUserId: 'u-lead',
+ approvalId: 'apv-1',
+ submitter: { kind: 'system' },
+ });
+ });
+
+ it('moves the routing and the follow but asks nobody when silent', async () => {
+ const { tx, statements } = fakeTx(
+ [approval({ metadata: { taskId: 't-1', requestedFor: 'u-carol' } })],
+ { createdBy: 'u-lead', teamIds: [] },
+ );
+
+ const waitsOn = await retargetPendingTaskReview(tx, {
+ task: taskRow({
+ reviewerUserId: null,
+ createdBy: 'u-carol',
+ archivedAt: 5,
+ }),
+ excludeUserId: 'u-carol',
+ silent: true,
+ });
+
+ expect(waitsOn).toBe('u-lead');
+ expect(approvalWrites(statements)).toEqual([
+ [{ json: { requestedFor: 'u-lead' } }, 'apv-1'],
+ ]);
+ // The subject's request bell still goes and the new reviewer follows
+ // the task (a restore brings the card back waiting on them), but no
+ // request rings for a card hidden from the board.
+ expect(dismissReviewRequestNotifications).toHaveBeenCalledTimes(1);
+ expect(autoSubscribe).toHaveBeenCalledWith(
+ tx,
+ expect.objectContaining({ subscriberId: 'u-lead', reason: 'reviewer' }),
+ );
+ expect(notifyTaskReviewRequested).not.toHaveBeenCalled();
+ });
+
+ it('empties the request when the subject is every link of the chain', async () => {
+ const { tx, statements } = fakeTx(
+ [approval({ metadata: { taskId: 't-1', requestedFor: 'u-carol' } })],
+ { createdBy: 'u-carol', teamIds: [] },
+ );
+
+ const waitsOn = await retargetPendingTaskReview(tx, {
+ task: taskRow({ reviewerUserId: null, createdBy: 'u-carol' }),
+ excludeUserId: 'u-carol',
+ });
+
+ expect(waitsOn).toBeUndefined();
+ expect(approvalWrites(statements)).toEqual([
+ [{ json: { requestedFor: null } }, 'apv-1'],
+ ]);
+ expect(notifyTaskReviewRequested).not.toHaveBeenCalled();
+ });
+});
+
+/**
+ * The one rule a reviewer is held to — the gate resolves by it and a
+ * designation is refused by it, so a designee is never stored only to be
+ * routed past at mint.
+ */
+describe('reviewerEligibility', () => {
+ const { tx } = fakeTx([]);
+ const ask = (userId: string, projectTeamIds: string[] = []) =>
+ reviewerEligibility(tx, {
+ organizationId: 'org-1',
+ projectTeamIds,
+ userId,
+ });
+
+ it('takes an editor of an org-wide project', async () => {
+ await expect(ask('u-bob')).resolves.toBe('eligible');
+ });
+
+ it('refuses a member whose role cannot edit', async () => {
+ await expect(ask('u-viewer')).resolves.toBe('cannot_edit');
+ });
+
+ it('refuses an editor outside the teams of a team-restricted project', async () => {
+ vi.mocked(getUserTeamIds).mockImplementation((_sql, _org, userId) =>
+ Promise.resolve(userId === 'u-alice' ? ['team-a'] : ['team-b']),
+ );
+ await expect(ask('u-bob', ['team-a'])).resolves.toBe('cannot_edit');
+ await expect(ask('u-alice', ['team-a'])).resolves.toBe('eligible');
+ // An admin edits every project, team or not.
+ await expect(ask('u-lead', ['team-a'])).resolves.toBe('eligible');
+ });
+
+ it('calls a disabled account or a non-member no member at all', async () => {
+ await expect(ask('u-gone')).resolves.toBe('not_member');
+ await expect(ask('u-stranger')).resolves.toBe('not_member');
+ });
+});
diff --git a/services/platform/backend/domains/tasks/reviews.ts b/services/platform/backend/domains/tasks/reviews.ts
index 91be0d71fd..0165b048f4 100644
--- a/services/platform/backend/domains/tasks/reviews.ts
+++ b/services/platform/backend/domains/tasks/reviews.ts
@@ -86,15 +86,51 @@ async function listTaskReviewApprovals(
`;
}
+/** Why a person can or cannot take a task's review. */
+export type ReviewerEligibility = 'eligible' | 'not_member' | 'cannot_edit';
+
+/**
+ * Whether a person can take a review in a project: a live member of the
+ * organization who holds project canEdit. The ONE rule — the gate resolves
+ * its reviewer by it, and a designation is held to it, so a designee the
+ * gate would route past is refused up front instead of silently skipped.
+ */
+export async function reviewerEligibility(
+ tx: TransactionSql | Sql,
+ args: {
+ organizationId: string;
+ /** The project's audience (`PROJECT_TEAM_IDS_SQL`); empty = org-wide. */
+ projectTeamIds: readonly string[];
+ userId: string;
+ },
+): Promise {
+ const member = await findOrganizationMember(
+ tx,
+ args.organizationId,
+ args.userId,
+ );
+ if (member === null || member.role === 'disabled') return 'not_member';
+ const teamIds = await getUserTeamIds(tx, args.organizationId, args.userId);
+ const access = checkProjectAccess(
+ { teamIds: args.projectTeamIds },
+ teamIds,
+ member.role,
+ );
+ return access.canEdit ? 'eligible' : 'cannot_edit';
+}
+
/**
* Who should review a task parked at `in_review` — revalidated at every
* call so a designee who lost project access falls through the chain:
* explicit `reviewerUserId` → human task creator → project creator; the
- * first candidate who still holds project canEdit wins.
+ * first candidate who still holds project canEdit wins. `excluding` is
+ * skipped wherever it appears in the chain (an erased subject stays a
+ * member until someone removes them, and may be either creator).
*/
async function resolveReviewer(
tx: TransactionSql | Sql,
task: TaskRow,
+ excluding?: string,
): Promise {
const projects = await tx<{ createdBy: string; teamIds: string[] | null }[]>`
SELECT created_by AS "createdBy", ${tx.unsafe(PROJECT_TEAM_IDS_SQL)} AS "teamIds"
@@ -107,22 +143,16 @@ async function resolveReviewer(
project?.createdBy,
];
const seen = new Set();
+ if (excluding !== undefined) seen.add(excluding);
for (const candidate of candidates) {
if (candidate === undefined || seen.has(candidate)) continue;
seen.add(candidate);
- const member = await findOrganizationMember(
- tx,
- task.organizationId,
- candidate,
- );
- if (member === null || member.role === 'disabled') continue;
- const teamIds = await getUserTeamIds(tx, task.organizationId, candidate);
- const access = checkProjectAccess(
- { teamIds: project?.teamIds ?? [] },
- teamIds,
- member.role,
- );
- if (access.canEdit) return candidate;
+ const eligibility = await reviewerEligibility(tx, {
+ organizationId: task.organizationId,
+ projectTeamIds: project?.teamIds ?? [],
+ userId: candidate,
+ });
+ if (eligibility === 'eligible') return candidate;
}
return undefined;
}
@@ -246,19 +276,32 @@ export async function requestTaskReview(
* Workflow-era rows are left alone, as on the status leave. Returns whom
* the open review now waits on; undefined when none is open or nobody
* resolves.
+ *
+ * An erasure moves a review off its subject the same way: no person made
+ * that change, so `actorUserId` is absent and the request reads
+ * impersonally, and `excludeUserId` keeps the chain from landing on the
+ * subject again through a creator slot. `silent` moves the routing (and
+ * the follow) without asking anyone — for a task hidden from the board,
+ * where an actionable request would point at a card nobody can act on
+ * until it is restored.
*/
export async function retargetPendingTaskReview(
tx: TransactionSql,
- args: { task: TaskRow; actorUserId: string },
+ args: {
+ task: TaskRow;
+ actorUserId?: string;
+ excludeUserId?: string;
+ silent?: boolean;
+ },
): Promise {
- const { task, actorUserId } = args;
+ const { task, actorUserId, excludeUserId, silent = false } = args;
const pending = (await listTaskReviewApprovals(tx, task.id)).filter(
(approval) =>
approval.status === 'pending' && approval.wfExecutionId === null,
);
if (pending.length === 0) return undefined;
- const reviewer = await resolveReviewer(tx, task);
+ const reviewer = await resolveReviewer(tx, task, excludeUserId);
for (const approval of pending) {
if ((approval.metadata?.requestedFor ?? null) === (reviewer ?? null)) {
continue;
@@ -281,12 +324,16 @@ export async function retargetPendingTaskReview(
subscriberId: reviewer,
reason: 'reviewer',
});
+ if (silent) continue;
await notifyTaskReviewRequested(tx, {
organizationId: task.organizationId,
task: { id: task.id, projectId: task.projectId, title: task.title },
reviewerUserId: reviewer,
approvalId: approval.id,
- submitter: { kind: 'user', userId: actorUserId },
+ submitter:
+ actorUserId === undefined
+ ? { kind: 'system' }
+ : { kind: 'user', userId: actorUserId },
});
}
return reviewer;
diff --git a/services/platform/backend/domains/tasks/service.activity.test.ts b/services/platform/backend/domains/tasks/service.activity.test.ts
index b381bbb145..3bbb4bb4e7 100644
--- a/services/platform/backend/domains/tasks/service.activity.test.ts
+++ b/services/platform/backend/domains/tasks/service.activity.test.ts
@@ -8,6 +8,7 @@ import { type TaskRow, updateTask } from './service.ts';
vi.mock('../collab/service.ts', () => ({
autoSubscribe: vi.fn(),
+ dismissReviewerAssignedNotifications: vi.fn(),
notifyTaskAssigned: vi.fn(),
notifyTaskReviewerAssigned: vi.fn(),
notifyTaskStatusChanged: vi.fn(),
@@ -19,19 +20,12 @@ vi.mock('../../jobs/enqueue.ts', () => ({ addJobInTx: vi.fn() }));
vi.mock('../files/upload-intents.ts', () => ({
firstForeignUpload: vi.fn().mockResolvedValue(null),
}));
-vi.mock('../../auth/membership.ts', () => ({
- findOrganizationMember: vi.fn().mockResolvedValue({
- userId: 'u-bob',
- role: 'member',
- email: 'bob@example.com',
- disabled: false,
- }),
-}));
vi.mock('./reviews.ts', () => ({
closePendingTaskReviewOnStatusLeave: vi.fn(),
collectPendingReviewsForProjects: vi.fn(() => Promise.resolve([])),
requestTaskReview: vi.fn(),
retargetPendingTaskReview: vi.fn(),
+ reviewerEligibility: vi.fn(() => Promise.resolve('eligible')),
}));
vi.mock('./agent-runs.ts', () => ({
cancelAgentRunInTx: vi.fn(),
diff --git a/services/platform/backend/domains/tasks/service.reviewer.test.ts b/services/platform/backend/domains/tasks/service.reviewer.test.ts
index 4bc3b0bde5..87e8bcb59c 100644
--- a/services/platform/backend/domains/tasks/service.reviewer.test.ts
+++ b/services/platform/backend/domains/tasks/service.reviewer.test.ts
@@ -3,14 +3,16 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
autoSubscribe,
+ dismissReviewerAssignedNotifications,
notifyTaskReviewerAssigned,
} from '../collab/service.ts';
import { loadProjectOrThrow, type ProjectRow } from '../projects/service.ts';
-import { retargetPendingTaskReview } from './reviews.ts';
+import { retargetPendingTaskReview, reviewerEligibility } from './reviews.ts';
import { type TaskRow, updateTask } from './service.ts';
vi.mock('../collab/service.ts', () => ({
autoSubscribe: vi.fn(),
+ dismissReviewerAssignedNotifications: vi.fn(),
notifyTaskAssigned: vi.fn(),
notifyTaskReviewerAssigned: vi.fn(),
notifyTaskStatusChanged: vi.fn(),
@@ -19,21 +21,12 @@ vi.mock('../events/emit.ts', () => ({ emitEvent: vi.fn() }));
vi.mock('../audit_logs/service.ts', () => ({ createAuditLog: vi.fn() }));
vi.mock('../../realtime/outbox.ts', () => ({ emitHintInTx: vi.fn() }));
vi.mock('../../jobs/enqueue.ts', () => ({ addJobInTx: vi.fn() }));
-vi.mock('../../auth/membership.ts', () => ({
- findOrganizationMember: vi.fn((_sql, organizationId, userId) =>
- Promise.resolve({
- id: `m-${userId}`,
- organizationId,
- userId,
- role: 'editor',
- }),
- ),
-}));
vi.mock('./reviews.ts', () => ({
closePendingTaskReviewOnStatusLeave: vi.fn(),
collectPendingReviewsForProjects: vi.fn(() => Promise.resolve([])),
requestTaskReview: vi.fn(),
retargetPendingTaskReview: vi.fn(),
+ reviewerEligibility: vi.fn(),
}));
vi.mock('./agent-runs.ts', () => ({
cancelAgentRunInTx: vi.fn(),
@@ -130,9 +123,14 @@ function taskRow(overrides: Partial = {}): TaskRow {
};
}
+/** Every statement the fake answered, so a refusal can be shown to have
+ * written nothing. */
+let statements: string[] = [];
+
function fakeTx(fixture: TaskRow): TransactionSql {
const tag = (strings: TemplateStringsArray): Promise => {
const text = strings.join('?').replaceAll(/\s+/g, ' ').trim();
+ statements.push(text);
return Promise.resolve(
text.startsWith('SELECT ? FROM app.tasks WHERE id = ?') ? [fixture] : [],
);
@@ -146,9 +144,12 @@ function fakeTx(fixture: TaskRow): TransactionSql {
}
beforeEach(() => {
+ statements = [];
vi.mocked(loadProjectOrThrow).mockReset().mockResolvedValue(project);
vi.mocked(retargetPendingTaskReview).mockReset().mockResolvedValue(undefined);
+ vi.mocked(reviewerEligibility).mockReset().mockResolvedValue('eligible');
vi.mocked(autoSubscribe).mockReset();
+ vi.mocked(dismissReviewerAssignedNotifications).mockReset();
vi.mocked(notifyTaskReviewerAssigned).mockReset();
});
@@ -192,20 +193,6 @@ describe('updateTask — the open review follows the reviewer', () => {
);
});
- it('still sends the heads-up when the open review resolves past the designee', async () => {
- // The designee lost project edit access: the request falls through the
- // chain to someone else, so theirs is the only bell they get.
- vi.mocked(retargetPendingTaskReview).mockResolvedValue('u-owner');
- const tx = fakeTx(taskRow());
-
- await updateTask(tx, auth, { taskId: 't-1', reviewerUserId: 'u-bob' });
-
- expect(notifyTaskReviewerAssigned).toHaveBeenCalledWith(
- tx,
- expect.objectContaining({ reviewerUserId: 'u-bob' }),
- );
- });
-
it('hands a cleared review back to the gate to resolve, belling no designee', async () => {
vi.mocked(retargetPendingTaskReview).mockResolvedValue('u-owner');
const tx = fakeTx(taskRow());
@@ -230,3 +217,108 @@ describe('updateTask — the open review follows the reviewer', () => {
expect(notifyTaskReviewerAssigned).not.toHaveBeenCalled();
});
});
+
+/**
+ * A designee is held to the rule the gate resolves by. Before this, only
+ * org membership was checked: a designee who could not edit the project was
+ * stored, belled with "You're the reviewer", and then routed past at mint —
+ * the review landing, silently, on a creator.
+ */
+describe('updateTask — who can be designated', () => {
+ it('refuses a designee who cannot edit the project, writing nothing', async () => {
+ vi.mocked(reviewerEligibility).mockResolvedValue('cannot_edit');
+ const tx = fakeTx(taskRow({ status: 'todo' }));
+
+ await expect(
+ updateTask(tx, auth, { taskId: 't-1', reviewerUserId: 'u-viewer' }),
+ ).rejects.toMatchObject({
+ name: 'TaskError',
+ code: 'TASK_REVIEWER_NO_EDIT_ACCESS',
+ status: 400,
+ });
+
+ // Judged against the project's own audience.
+ expect(reviewerEligibility).toHaveBeenCalledWith(tx, {
+ organizationId: 'org-1',
+ projectTeamIds: [],
+ userId: 'u-viewer',
+ });
+ expect(statements.some((text) => text.startsWith('UPDATE app.tasks'))).toBe(
+ false,
+ );
+ expect(retargetPendingTaskReview).not.toHaveBeenCalled();
+ expect(dismissReviewerAssignedNotifications).not.toHaveBeenCalled();
+ expect(autoSubscribe).not.toHaveBeenCalled();
+ expect(notifyTaskReviewerAssigned).not.toHaveBeenCalled();
+ });
+
+ it('refuses a designee who is no longer a live member', async () => {
+ vi.mocked(reviewerEligibility).mockResolvedValue('not_member');
+ const tx = fakeTx(taskRow({ status: 'todo' }));
+
+ await expect(
+ updateTask(tx, auth, { taskId: 't-1', reviewerUserId: 'u-gone' }),
+ ).rejects.toMatchObject({ code: 'TASK_REVIEWER_INVALID', status: 400 });
+ expect(statements.some((text) => text.startsWith('UPDATE app.tasks'))).toBe(
+ false,
+ );
+ });
+
+ it('judges only a new designee — a clear or a re-select asks nothing', async () => {
+ const tx = fakeTx(taskRow());
+
+ await updateTask(tx, auth, { taskId: 't-1', reviewerUserId: null });
+ await updateTask(tx, auth, { taskId: 't-1', reviewerUserId: 'u-alice' });
+
+ expect(reviewerEligibility).not.toHaveBeenCalled();
+ });
+});
+
+/**
+ * The "You're the reviewer" heads-up is for whoever holds the designation.
+ * Before this, a change ahead of In review left the previous designee's
+ * unread heads-up ringing.
+ */
+describe('updateTask — the previous designee is let off the hook', () => {
+ it('dismisses the previous designee’s heads-up when the designation moves', async () => {
+ const tx = fakeTx(taskRow({ status: 'todo' }));
+
+ await updateTask(tx, auth, { taskId: 't-1', reviewerUserId: 'u-bob' });
+
+ expect(dismissReviewerAssignedNotifications).toHaveBeenCalledWith(tx, {
+ organizationId: 'org-1',
+ taskId: 't-1',
+ userId: 'u-alice',
+ });
+ // The new designee still gets theirs.
+ expect(notifyTaskReviewerAssigned).toHaveBeenCalledWith(
+ tx,
+ expect.objectContaining({ reviewerUserId: 'u-bob' }),
+ );
+ });
+
+ it('dismisses it when the reviewer is cleared', async () => {
+ const tx = fakeTx(taskRow({ status: 'todo' }));
+
+ await updateTask(tx, auth, { taskId: 't-1', reviewerUserId: null });
+
+ expect(dismissReviewerAssignedNotifications).toHaveBeenCalledWith(tx, {
+ organizationId: 'org-1',
+ taskId: 't-1',
+ userId: 'u-alice',
+ });
+ });
+
+ it('dismisses nothing for a first designation or an unchanged one', async () => {
+ await updateTask(fakeTx(taskRow({ reviewerUserId: null })), auth, {
+ taskId: 't-1',
+ reviewerUserId: 'u-bob',
+ });
+ await updateTask(fakeTx(taskRow()), auth, {
+ taskId: 't-1',
+ reviewerUserId: 'u-alice',
+ });
+
+ expect(dismissReviewerAssignedNotifications).not.toHaveBeenCalled();
+ });
+});
diff --git a/services/platform/backend/domains/tasks/service.ts b/services/platform/backend/domains/tasks/service.ts
index 93f435235b..0ae555d7cf 100644
--- a/services/platform/backend/domains/tasks/service.ts
+++ b/services/platform/backend/domains/tasks/service.ts
@@ -6,7 +6,6 @@ import {
defaultTaskLabelColor,
PREDEFINED_TASK_LABELS,
} from '../../../lib/shared/task-label-colors.ts';
-import { findOrganizationMember } from '../../auth/membership.ts';
import {
checkProjectAccess,
EDITOR_ROLES,
@@ -35,6 +34,7 @@ import { createAuditLog } from '../audit_logs/service.ts';
import { resolveSurfaceMentions } from '../collab/mention-directory.ts';
import {
autoSubscribe,
+ dismissReviewerAssignedNotifications,
notifyTaskAssigned,
notifyTaskMentions,
notifyTaskReviewerAssigned,
@@ -56,6 +56,7 @@ import {
collectPendingReviewsForProjects,
requestTaskReview,
retargetPendingTaskReview,
+ reviewerEligibility,
type TaskReviewTrigger,
} from './reviews.ts';
import { mentionAutomationEnabled } from './run-start.ts';
@@ -1415,9 +1416,13 @@ export async function updateTask(
}
}
// A NEW designee (not a clear, not a re-select) is about to be subscribed
- // and belled: only a live member of THIS org can be on the hook — the
- // picker offers members only, so a miss is a stale or hand-built request,
- // and a disabled account cannot review.
+ // and belled, so they must be someone the gate would actually hand the
+ // review to — the one rule `reviewerEligibility` holds the gate to. A
+ // designee without project edit access used to be stored and then routed
+ // past at mint, the review silently landing on a creator. The picker
+ // offers eligible members only, so a miss is a stale or hand-built
+ // request; re-selecting a designee who has since lost access is no
+ // designation and passes, and the gate routes past them as before.
const designatedReviewer =
args.reviewerUserId !== undefined &&
reviewerUserId !== null &&
@@ -1425,17 +1430,23 @@ export async function updateTask(
? reviewerUserId
: null;
if (designatedReviewer !== null) {
- const member = await findOrganizationMember(
- tx,
- auth.organizationId,
- designatedReviewer,
- );
- if (member === null || member.role === 'disabled') {
+ const eligibility = await reviewerEligibility(tx, {
+ organizationId: auth.organizationId,
+ projectTeamIds: project.teamIds,
+ userId: designatedReviewer,
+ });
+ if (eligibility === 'not_member') {
throw new TaskError(
'TASK_REVIEWER_INVALID',
'The reviewer must be an active member of this organization',
);
}
+ if (eligibility === 'cannot_edit') {
+ throw new TaskError(
+ 'TASK_REVIEWER_NO_EDIT_ACCESS',
+ 'The reviewer must be able to edit this project',
+ );
+ }
}
if (Object.keys(newState).length === 0) {
@@ -1521,6 +1532,16 @@ export async function updateTask(
actorUserId: auth.userId,
})
: undefined;
+ // The previous designee is off the hook: an unread "You're the reviewer"
+ // heads-up would keep telling them otherwise. Their request bell, when the
+ // review was open, went with the retarget above.
+ if (task.reviewerUserId !== null && reviewerUserId !== task.reviewerUserId) {
+ await dismissReviewerAssignedNotifications(tx, {
+ organizationId: auth.organizationId,
+ taskId: task.id,
+ userId: task.reviewerUserId,
+ });
+ }
if (designatedReviewer !== null) {
// The designee owns the gate from now on: they follow the task (its
// progress, not just the request moment) and get the heads-up bell —
diff --git a/services/platform/backend/integration-check.ts b/services/platform/backend/integration-check.ts
index cc96de045b..ac8c5eafdf 100644
--- a/services/platform/backend/integration-check.ts
+++ b/services/platform/backend/integration-check.ts
@@ -68,6 +68,7 @@ import { appendMessageRow } from './domains/chat/store.ts';
import { checkTaskRunConnectorCaller } from './domains/connectors/bridge-caller.integration.ts';
import { setMailTransportForTesting } from './domains/connectors/service.ts';
import { checkConversationApi } from './domains/conversations/api-sync.integration.ts';
+import { checkErasureReviewHandoverRaces } from './domains/erasure/review-handover.integration.ts';
import { checkEmailedAttachments } from './domains/knowledge/attachment-mail.integration.ts';
import { checkInboundEmailBodies } from './domains/knowledge/message-index.integration.ts';
import { checkKnowledgeEntryIndexing } from './domains/knowledge_entries/indexing.integration.ts';
@@ -21640,20 +21641,29 @@ async function checkTasksCollabIntegrity(
// ---- designating a reviewer tells them -----------------------------------
// The designee is subscribed (reason 'reviewer') and gets the heads-up
// bell on the wire entity the app keys the bell on; designating yourself
- // rings nothing, and a non-member cannot be put on the hook at all.
+ // rings nothing, a non-member cannot be put on the hook at all, and
+ // neither can a member who cannot edit the project — the gate would only
+ // route past them.
const reviewer = 'integrity-reviewer-1';
- await sql`
- INSERT INTO "user" ("id", "name", "email", "emailVerified", "createdAt",
- "updatedAt")
- VALUES (${reviewer}, 'Integrity Reviewer', ${`${reviewer}@example.com`},
- true, ${new Date()}, ${new Date()})
- ON CONFLICT ("id") DO NOTHING
- `;
- await sql`
- INSERT INTO "member" ("id", "organizationId", "userId", "role", "createdAt")
- VALUES (${`m-${reviewer}`}, ${orgId}, ${reviewer}, 'member', ${new Date()})
- ON CONFLICT ("id") DO NOTHING
- `;
+ const readOnlyMember = 'integrity-reviewer-readonly';
+ for (const [id, role] of [
+ [reviewer, 'editor'],
+ [readOnlyMember, 'member'],
+ ] as const) {
+ await sql`
+ INSERT INTO "user" ("id", "name", "email", "emailVerified", "createdAt",
+ "updatedAt")
+ VALUES (${id}, ${id}, ${`${id}@example.com`}, true, ${new Date()},
+ ${new Date()})
+ ON CONFLICT ("id") DO NOTHING
+ `;
+ await sql`
+ INSERT INTO "member" ("id", "organizationId", "userId", "role",
+ "createdAt")
+ VALUES (${`m-${orgId}-${id}`}, ${orgId}, ${id}, ${role}, ${new Date()})
+ ON CONFLICT ("id") DO NOTHING
+ `;
+ }
const reviewedTask = await newTask('Needs a reviewer');
const designated = await post(
`/api/app/tasks/${reviewedTask}?orgId=${orgId}`,
@@ -21692,8 +21702,24 @@ async function checkTasksCollabIntegrity(
.object({ error: z.string() })
.loose()
.safeParse(await bogus.json());
+ const readOnly = await post(`/api/app/tasks/${reviewedTask}?orgId=${orgId}`, {
+ reviewerUserId: readOnlyMember,
+ });
+ const readOnlyBody = z
+ .object({ error: z.string() })
+ .loose()
+ .safeParse(await readOnly.json());
+ const stillDesignated = await sql<{ reviewerUserId: string | null }[]>`
+ SELECT reviewer_user_id AS "reviewerUserId" FROM app.tasks
+ WHERE id = ${reviewedTask}
+ `;
+ const readOnlyBell = await sql<{ count: string }[]>`
+ SELECT count(*)::text AS count FROM app.user_notifications
+ WHERE org_id = ${orgId} AND user_id = ${readOnlyMember}
+ AND task_id = ${reviewedTask}
+ `;
record(
- 'tasks/collab: designating a reviewer subscribes and bells them (never yourself, never a non-member)',
+ 'tasks/collab: designating a reviewer subscribes and bells them (never yourself, never a non-member, never someone who cannot edit)',
designated.ok &&
reviewerBell[0]?.count === '1' &&
reviewerFollows[0]?.count === '1' &&
@@ -21701,8 +21727,13 @@ async function checkTasksCollabIntegrity(
selfBell[0]?.count === '0' &&
bogus.status === 400 &&
bogusBody.success &&
- bogusBody.data.error === 'TASK_REVIEWER_INVALID',
- `designate → ${designated.status}, bell=${reviewerBell[0]?.count} (want 1), follows=${reviewerFollows[0]?.count} (want 1), hint=${reviewerHint[0]?.count} (want ≥1); self bell=${selfBell[0]?.count} (want 0); non-member → ${bogus.status}/${bogusBody.success ? bogusBody.data.error : 'ERR'} (want 400/TASK_REVIEWER_INVALID)`,
+ bogusBody.data.error === 'TASK_REVIEWER_INVALID' &&
+ readOnly.status === 400 &&
+ readOnlyBody.success &&
+ readOnlyBody.data.error === 'TASK_REVIEWER_NO_EDIT_ACCESS' &&
+ stillDesignated[0]?.reviewerUserId === reviewer &&
+ readOnlyBell[0]?.count === '0',
+ `designate → ${designated.status}, bell=${reviewerBell[0]?.count} (want 1), follows=${reviewerFollows[0]?.count} (want 1), hint=${reviewerHint[0]?.count} (want ≥1); self bell=${selfBell[0]?.count} (want 0); non-member → ${bogus.status}/${bogusBody.success ? bogusBody.data.error : 'ERR'} (want 400/TASK_REVIEWER_INVALID); read-only member → ${readOnly.status}/${readOnlyBody.success ? readOnlyBody.data.error : 'ERR'} (want 400/TASK_REVIEWER_NO_EDIT_ACCESS), designation=${stillDesignated[0]?.reviewerUserId === reviewer ? 'kept' : String(stillDesignated[0]?.reviewerUserId)} (want kept), their bells=${readOnlyBell[0]?.count} (want 0)`,
);
// ---- a reviewer changed mid-review takes the open review along ----------
@@ -21864,6 +21895,47 @@ async function checkTasksCollabIntegrity(
bellsCreator.length === 0,
`clear → ${clearedOver.status}, gate=${clearedGate.length} same=${clearedGate[0]?.id === handedApproval} for creator=${clearedGate[0]?.metadata?.requestedFor === userId} (want 1/true/true); chip=${viewCleared.chip === userId ? 'creator' : String(viewCleared.chip)} (want creator), waiting on B=${viewCleared.waitsOn(reviewerB)} (want false); bells B=${bellText(bellsBCleared)} (want all read), creator=${bellText(bellsCreator)} (want none: they cleared it themselves)`,
);
+ // ---- a reviewer changed BEFORE review lets the previous designee off ----
+ // No review is open yet, so there is no request to move — but A's unread
+ // "You're the reviewer" heads-up kept telling A they were on the hook.
+ const earlyTask = await newTask('Reviewer changed before review');
+ const headsUps = (user: string): Promise<{ read: boolean }[]> => sql<
+ { read: boolean }[]
+ >`
+ SELECT read FROM app.user_notifications
+ WHERE org_id = ${orgId} AND user_id = ${user} AND task_id = ${earlyTask}
+ AND type = 'task_reviewer_assigned'
+ `;
+ await post(`/api/app/tasks/${earlyTask}?orgId=${orgId}`, {
+ reviewerUserId: reviewerA,
+ });
+ const earlyA = await headsUps(reviewerA);
+ const movedEarly = await post(`/api/app/tasks/${earlyTask}?orgId=${orgId}`, {
+ reviewerUserId: reviewerB,
+ });
+ const movedA = await headsUps(reviewerA);
+ const movedB = await headsUps(reviewerB);
+ const earlyCleared = await post(
+ `/api/app/tasks/${earlyTask}?orgId=${orgId}`,
+ { reviewerUserId: null },
+ );
+ const clearedB = await headsUps(reviewerB);
+ const readText = (rows: { read: boolean }[]): string =>
+ rows.map((row) => (row.read ? 'read' : 'unread')).join(',') || 'none';
+ record(
+ "tasks/collab: changing the reviewer before review dismisses the previous designee's heads-up",
+ earlyA.length === 1 &&
+ earlyA.every((row) => !row.read) &&
+ movedEarly.ok &&
+ movedA.length === 1 &&
+ movedA.every((row) => row.read) &&
+ movedB.length === 1 &&
+ movedB.every((row) => !row.read) &&
+ earlyCleared.ok &&
+ clearedB.length === 1 &&
+ clearedB.every((row) => row.read),
+ `A designated: ${readText(earlyA)} (want unread); → B ${movedEarly.status}: A=${readText(movedA)} (want read), B=${readText(movedB)} (want unread); clear ${earlyCleared.status}: B=${readText(clearedB)} (want read)`,
+ );
// ---- a mention directory that cannot be listed fails the surface -------
// Against the real schema: the same resolution with the agent-instance
// leg failing rejects (MENTION_DIRECTORY_UNAVAILABLE, 503) instead of
@@ -43929,6 +44001,46 @@ async function checkErasure(
${sql.json({ requestedFor: subject, response: { respondedBy: subject } })},
${now})
`;
+ // A review still WAITING on the subject is routing, not history: it must
+ // move on to the task creator (here the owner) rather than wait on the
+ // pseudonym, where no board and no bell would ever find it.
+ const waitingProject = z
+ .object({ projectId: z.string() })
+ .loose()
+ .safeParse(
+ await (
+ await post(`/api/app/projects?orgId=${orgId}`, {
+ name: 'Erasure review hand-over',
+ })
+ ).json(),
+ );
+ const waitingTask = z
+ .object({ taskId: z.string() })
+ .loose()
+ .safeParse(
+ await (
+ await post(`/api/app/tasks?orgId=${orgId}`, {
+ projectId: waitingProject.success
+ ? waitingProject.data.projectId
+ : '',
+ title: 'Waiting on the subject',
+ status: 'in_review',
+ })
+ ).json(),
+ );
+ const waitingTaskId = waitingTask.success ? waitingTask.data.taskId : '';
+ // The subject held the designation and the open review when the erasure
+ // was filed (written directly: a read-only member can no longer be named).
+ await sql`
+ UPDATE app.tasks SET reviewer_user_id = ${subject}
+ WHERE id = ${waitingTaskId}
+ `;
+ await sql`
+ UPDATE app.approvals SET
+ metadata = metadata || ${sql.json({ requestedFor: subject })}
+ WHERE resource_type = 'task_review' AND resource_id = ${waitingTaskId}
+ AND status = 'pending'
+ `;
await sql`
INSERT INTO app.login_attempts (email, consecutive_failures,
last_failure_at)
@@ -43954,6 +44066,12 @@ async function checkErasure(
) VALUES (${orgId}, ${subject}, 'folder', ${`gd-${subject}`}, 'Reports',
'documents', 'active', ${now}, ${now})
`;
+ // Nothing above hints the task (the designation and the review were
+ // written directly), so a `task` hint past this cursor is the erasure's:
+ // the board, **Needs my review** and the Reviewer field refresh on it.
+ const outboxBefore = await sql<{ max: string | null }[]>`
+ SELECT max(id)::text AS max FROM app_realtime.outbox
+ `;
const filed = z
.object({ requestId: z.string(), threadsTargeted: z.number() })
.loose()
@@ -44027,6 +44145,41 @@ async function checkErasure(
const receiptCounts = await sql<{ counts: Record | null }[]>`
SELECT counts FROM app.gdpr_erasure_requests WHERE id = ${requestId}
`;
+ const waitingAfter = await sql<
+ { id: string; status: string; requestedFor: string | null }[]
+ >`
+ SELECT id, status, metadata->>'requestedFor' AS "requestedFor"
+ FROM app.approvals
+ WHERE resource_type = 'task_review' AND resource_id = ${waitingTaskId}
+ `;
+ const waitingDesignation = await sql<{ reviewerUserId: string | null }[]>`
+ SELECT reviewer_user_id AS "reviewerUserId" FROM app.tasks
+ WHERE id = ${waitingTaskId}
+ `;
+ const handedBell = await sql<{ read: boolean; actorType: string }[]>`
+ SELECT read, actor_type AS "actorType" FROM app.user_notifications
+ WHERE org_id = ${orgId} AND user_id = ${userId}
+ AND type = 'task_review_requested'
+ AND resource_id = ${waitingAfter[0]?.id ?? ''}
+ `;
+ const boardHints = await sql<{ count: string }[]>`
+ SELECT count(*)::text AS count FROM app_realtime.outbox
+ WHERE org_id = ${orgId} AND entity = 'task'
+ AND entity_id = ${waitingTaskId}
+ AND id > ${outboxBefore[0]?.max ?? '0'}::bigint
+ `;
+ record(
+ 'erasure: a review still waiting on the subject moves on to the task creator, not to the pseudonym',
+ waitingTask.success &&
+ waitingAfter.length === 1 &&
+ waitingAfter[0]?.status === 'pending' &&
+ waitingAfter[0]?.requestedFor === userId &&
+ waitingDesignation[0]?.reviewerUserId === null &&
+ handedBell.length === 1 &&
+ handedBell.every((bell) => !bell.read && bell.actorType === 'system') &&
+ Number(boardHints[0]?.count ?? '0') > 0,
+ `task=${waitingTask.success ? 'ok' : 'ERR'}; reviews=${waitingAfter.length} ${waitingAfter[0]?.status}/${waitingAfter[0]?.requestedFor === userId ? 'creator' : String(waitingAfter[0]?.requestedFor)} (want 1 pending/creator); designation=${String(waitingDesignation[0]?.reviewerUserId)} (want null); creator bell=${handedBell.map((bell) => `${bell.read ? 'read' : 'unread'}:${bell.actorType}`).join(',') || 'none'} (want unread:system); task hints=${boardHints[0]?.count} (want >0)`,
+ );
record(
'erasure: the uploads pass deletes the blob behind the ledger row',
receiptStatus === 'done' &&
@@ -54671,6 +54824,10 @@ async function main(): Promise {
'checkErasure',
() => checkErasure(sql, baseUrl, authCtx, `itest-${orgSuffix}`),
],
+ [
+ 'checkErasureReviewHandoverRaces',
+ () => checkErasureReviewHandoverRaces(sql, authCtx, record),
+ ],
// Reliability batch probes (self-contained; each seeds and cleans its
// own rows).
[
diff --git a/services/platform/backend/rest/error-codes.test.ts b/services/platform/backend/rest/error-codes.test.ts
index 4f9c881ff9..1087eec041 100644
--- a/services/platform/backend/rest/error-codes.test.ts
+++ b/services/platform/backend/rest/error-codes.test.ts
@@ -237,6 +237,7 @@ const APP_ONLY_CODES: ReadonlySet = new Set([
'TASK_PARENT_ARCHIVED',
'TASK_PARENT_PROJECT_MISMATCH',
'TASK_REVIEWER_INVALID',
+ 'TASK_REVIEWER_NO_EDIT_ACCESS',
'TASK_SCHEDULE_INVALID',
// Tasks: the door's schemas trim and cap the title, description, labels
// and comment body at the domain's own constants and canonicalize the
diff --git a/services/platform/tests/manual/readme.md b/services/platform/tests/manual/readme.md
index 47a130ab64..38ad923958 100644
--- a/services/platform/tests/manual/readme.md
+++ b/services/platform/tests/manual/readme.md
@@ -29,7 +29,7 @@ tale-project standard ([`AGENTS.md`](../../../../AGENTS.md) "Manual tests"), and
## The suites
-861 boxes across 21 suites. Every suite declares the ID prefix its
+876 boxes across 21 suites. Every suite declares the ID prefix its
boxes carry, in its header blockquote; a box ID is unique across this whole
directory and greppable as one token.
@@ -38,21 +38,21 @@ directory and greppable as one token.
| [accessibility](suites/accessibility.md) | `A11Y-` | cross-cutting WCAG 2.1 AA sweep | 26 |
| [approvals](suites/approvals.md) | `APV-` | human-in-the-loop: run approval/ask cards, task review gate, DSAR dual-approval | 20 |
| [auth](suites/auth.md) | `AUTH-` | login, SSO, 2FA, passkeys, password policy, first-run setup, RBAC | 48 |
-| [automations](suites/automations.md) | `AUTO-` | draft→deploy→version automations: list, builder, upload, trigger, runs, bindings | 71 |
-| [chat](suites/chat.md) | `CHAT-` | messages, attachments, tools + approvals, arena, share, reasoning, the chat header and rows | 84 |
+| [automations](suites/automations.md) | `AUTO-` | draft→deploy→version automations: list, builder, upload, trigger, runs, bindings | 72 |
+| [chat](suites/chat.md) | `CHAT-` | messages, attachments, tools + approvals, arena, share, reasoning, the chat header and rows | 86 |
| [connectors](suites/connectors.md) | `CONN-` | credential table + catalog picker; mailbox (IMAP/SMTP), OAuth, MCP endpoint | 30 |
-| [conversations](suites/conversations.md) | `CONV-` | the shared Inbox: statuses, priority, search, mailbox sync | 53 |
+| [conversations](suites/conversations.md) | `CONV-` | the shared Inbox: statuses, priority, search, mailbox sync | 55 |
| [data-residency](suites/data-residency.md) | `DATA-` | BYO knowledge database + object storage, embedding settings | 24 |
| [governance](suites/governance.md) | `GOV-` | content models, guardrails, policies, legal hold, DSAR, logs, trash | 54 |
| [knowledge](suites/knowledge.md) | `KNOW-` | documents, knowledge entries, products, contacts, websites | 52 |
| [metrics](suites/metrics.md) | `MET-` | org metrics tabs: usage, feedback, chat health, harness turns, automations, projects | 19 |
| [navigation](suites/navigation.md) | `NAV-` | side-nav rail + the Home panel, section panels, breadcrumbs, command palette, changelog, page-loads | 63 |
-| [notifications](suites/notifications.md) | `NOTIF-` | the notification bell + panel | 29 |
+| [notifications](suites/notifications.md) | `NOTIF-` | the notification bell + panel | 30 |
| [origins](suites/origins.md) | `ORIGIN-` | one deployment on several origins: sessions, file links, sign-in doors, an external TLS terminator | 12 |
| [performance](suites/performance.md) | `PERF-` | cold load, chat TTFT, thread switch, pagination | 18 |
-| [projects](suites/projects.md) | `PROJ-` | projects, agents, tasks (attachments, comments), files, secrets, threads, Home's projects section | 49 |
-| [responsive](suites/responsive.md) | `RESP-` | mobile viewport, bottom tab bar, the phone's Home list, mobile save bar, the narrow page column, short viewports | 28 |
-| [settings](suites/settings.md) | `SET-` | account, personalization, usage, org, teams, branding, connectors, API, providers | 93 |
+| [projects](suites/projects.md) | `PROJ-` | projects, agents, tasks (attachments, comments), files, secrets, threads, Home's projects section | 52 |
+| [responsive](suites/responsive.md) | `RESP-` | mobile viewport, bottom tab bar, the phone's Home list, mobile save bar, the narrow page column, short viewports | 32 |
+| [settings](suites/settings.md) | `SET-` | account, personalization, usage, org, teams, branding, connectors, API, providers | 95 |
| [skills](suites/skills.md) | `SKILL-` | skill library: table + facets, create/upload bundles, visibility, equip on agents | 20 |
| [tasks](suites/tasks.md) | `TASK-` | project task board/list: DnD lanes, task sheet, the task page, agent runs, outputs, review | 55 |
| [video-links](suites/video-links.md) | `VID-` | YouTube/video link ingestion (backend pipeline) | 13 |
diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md
index 558f9e0db0..e6f9c51c82 100644
--- a/services/platform/tests/manual/reference/automation.md
+++ b/services/platform/tests/manual/reference/automation.md
@@ -342,6 +342,9 @@ Legend: ✅ fully automated · 🔶 partially automated · ⛔ manual-only (no s
| [projects](../suites/projects.md) | `PROJ-F17`, `PROJ-F18`, `PROJ-F20`, `PROJ-F21` | ⛔ manual-only | — |
| [projects](../suites/projects.md) | `PROJ-B3` | ⛔ manual-only | — |
| [projects](../suites/projects.md) | `PROJ-F32` (the backend half): a reviewer changed while the task waits In review moves the open review in the same transaction — its `requestedFor` (the board chip and **Needs my review**), the request bell to the new reviewer with no heads-up on top, the previous reviewer's bell dismissed — and a clear hands it back to the task creator | 🔶 backend + real Postgres | `backend/domains/tasks/reviews.retarget.test.ts`, `backend/domains/tasks/service.reviewer.test.ts`, `backend/integration-check.ts` (`checkTasksCollabIntegrity`); the two live boards and bells stay manual |
+| [projects](../suites/projects.md) | `PROJ-F33` (the backend half): a reviewer changed or cleared before the task reaches In review marks the previous designee's unread **You're the reviewer** heads-up on that task read and hints their bell, while the new designee still gets theirs | 🔶 backend + real Postgres | `backend/domains/tasks/service.reviewer.test.ts`, `backend/domains/collab/service.test.ts`, `backend/integration-check.ts` (`checkTasksCollabIntegrity`); the two live bells stay manual |
+| [projects](../suites/projects.md) | `PROJ-F34` (the backend half): an erasure hands a review still waiting on its subject on through the chain a cleared designation takes (human task creator → project creator, the subject skipped in every slot), rings the new reviewer impersonally as the system (nobody on an archived task), clears the designation and hints the task in the same serializable transaction (barrier-driven real Postgres races preserve a concurrently committed reassignment and emit no stale request for a concurrently completed review; a hand-over that throws still clears and hints), and pseudonymizes only what still names the subject — decisions, workflow-era rows, a row whose task is gone or whose hand-over failed | 🔶 backend + real Postgres | `backend/domains/erasure/service.lifecycle.test.ts`, `backend/domains/tasks/reviews.retarget.test.ts`, `backend/domains/collab/service.test.ts`, `backend/integration-check.ts` (`checkErasure`), `backend/domains/erasure/review-handover.integration.ts` (`checkErasureReviewHandoverRaces`); the board chip and the bell after a real receipt stay manual |
+| [projects](../suites/projects.md) | `PROJ-B9` (the backend half): a designee who cannot edit the project — a read-only role, or outside a team-restricted project's teams — is refused with 400 `TASK_REVIEWER_NO_EDIT_ACCESS` before anything is written, by the same `reviewerEligibility` rule the review gate resolves by; the refusal's copy is the picker's hint (`tasks.reviewer.editorsOnly`, `reviewerRefusalMessage`); the picker lists editors only, narrowed to the project's audience, and nobody until that audience has loaded | 🔶 backend + helper + component + real Postgres | `backend/domains/tasks/service.reviewer.test.ts`, `backend/domains/tasks/reviews.retarget.test.ts`, `app/features/tasks/lib/reviewer-refusal.test.ts`, `app/features/tasks/components/reviewer-picker.test.tsx`, `app/features/tasks/hooks/use-actor-directory.test.ts`, `backend/integration-check.ts` (`checkTasksCollabIntegrity`); the task dialog's toast on a stale pick and the picker's live candidate list stay manual |
| [projects](../suites/projects.md) | `PROJ-F27` (the component half): the Chats tab names an untitled chat **Untitled chat** and never by its id, lists your chats with the share switch and the shared ones with their author's name (a user-id fragment when none resolves), and shares through the owner-gated chat mutation | 🔶 component | `app/features/projects/components/project-threads-tab.test.tsx`; the whole-row click, the pencil and the ages stay manual |
| [projects](../suites/projects.md) | `PROJ-A7` (the component half): the Sharing section's Audience picker, its no-teams hint and the read-only **Effective audience** each sit in a settings field row labelled by its visible label, with no `