Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat: duplicate task detection (#3635)
Eric Hayesadf2252771af
diff --git a/js/app/packages/app/component/next-soup/soup-view/views/tasks/TaskListEntity.tsx b/js/app/packages/app/component/next-soup/soup-view/views/tasks/TaskListEntity.tsxindex 4e956e4611..40e3572a9a 100644--- a/js/app/packages/app/component/next-soup/soup-view/views/tasks/TaskListEntity.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/views/tasks/TaskListEntity.tsx@@ -111,6 +111,7 @@ export function TaskListEntity(props: TaskListEntityProps) {const layoutProps = (): LayoutProps => ({entity: props.entity,checked: props.checked,+ hideCheckbox: props.hideCheckbox,onChecked: props.onChecked,unread: unread(),isShared: isShared(),diff --git a/js/app/packages/app/component/next-soup/soup-view/views/tasks/task-grid-layout.tsx b/js/app/packages/app/component/next-soup/soup-view/views/tasks/task-grid-layout.tsxindex 0ee2fb473a..17e6996b0b 100644--- a/js/app/packages/app/component/next-soup/soup-view/views/tasks/task-grid-layout.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/views/tasks/task-grid-layout.tsx@@ -31,7 +31,9 @@ import { ListPropertyValue } from './list-property-value';import {TASK_GRID_COLUMNS,TASK_GRID_TEMPLATE_AREAS_WIDE,+ TASK_GRID_TEMPLATE_AREAS_WIDE_NO_INDICATOR,TASK_GRID_TEMPLATE_COLUMNS_WIDE,+ TASK_GRID_TEMPLATE_COLUMNS_WIDE_NO_INDICATOR,type TaskGridColumn,} from './task-grid-template';@@ -117,28 +119,34 @@ export function TaskGridLayout(props: LayoutProps) {'gap-2 grid grid-rows-[1fr]')}style={{- 'grid-template-columns': TASK_GRID_TEMPLATE_COLUMNS_WIDE,- 'grid-template-areas': TASK_GRID_TEMPLATE_AREAS_WIDE,+ 'grid-template-columns': props.hideCheckbox+ ? TASK_GRID_TEMPLATE_COLUMNS_WIDE_NO_INDICATOR+ : TASK_GRID_TEMPLATE_COLUMNS_WIDE,+ 'grid-template-areas': props.hideCheckbox+ ? TASK_GRID_TEMPLATE_AREAS_WIDE_NO_INDICATOR+ : TASK_GRID_TEMPLATE_AREAS_WIDE,}}>- <Entity.Slot placement="indicator" class="relative size-full group">- <div class="absolute inset-0 grid place-items-center group-hover:opacity-0">- <UnreadIndicator active={props.unread} />- </div>- <div- class={cn(- 'absolute inset-0 grid place-items-center opacity-0 group-hover:opacity-100',- {- 'opacity-100': props.checked,- }- )}- >- <MultiSelectCheckbox- checked={props.checked}- onChecked={props.onChecked}- />- </div>- </Entity.Slot>+ <Show when={!props.hideCheckbox}>+ <Entity.Slot placement="indicator" class="relative size-full group">+ <div class="absolute inset-0 grid place-items-center group-hover:opacity-0">+ <UnreadIndicator active={props.unread} />+ </div>+ <div+ class={cn(+ 'absolute inset-0 grid place-items-center opacity-0 group-hover:opacity-100',+ {+ 'opacity-100': props.checked,+ }+ )}+ >+ <MultiSelectCheckbox+ checked={props.checked}+ onChecked={props.onChecked}+ />+ </div>+ </Entity.Slot>+ </Show><Entity.Slotplacement="content"diff --git a/js/app/packages/app/component/next-soup/soup-view/views/tasks/task-grid-template.ts b/js/app/packages/app/component/next-soup/soup-view/views/tasks/task-grid-template.tsindex 3f2e70b310..85917645cb 100644--- a/js/app/packages/app/component/next-soup/soup-view/views/tasks/task-grid-template.ts+++ b/js/app/packages/app/component/next-soup/soup-view/views/tasks/task-grid-template.ts@@ -50,6 +50,11 @@ export const TASK_GRID_TEMPLATE_COLUMNS_WIDE = `1rem minmax(0, 100%) ${TASK_GRID(c) => c.width).join(' ')} ${CREATED_BY_COLUMN_WIDTH} var(--task-col-timestamp, 5rem)`;+/** Wide template without the leading indicator (checkbox) column. */+export const TASK_GRID_TEMPLATE_COLUMNS_WIDE_NO_INDICATOR = `minmax(0, 100%) ${TASK_GRID_COLUMNS.map(+ (c) => c.width+).join(' ')} ${CREATED_BY_COLUMN_WIDTH} var(--task-col-timestamp, 5rem)`;+/** @deprecated Use TASK_GRID_TEMPLATE_COLUMNS_NARROW or TASK_GRID_TEMPLATE_COLUMNS_WIDE */const _TASK_GRID_TEMPLATE_COLUMNS = TASK_GRID_TEMPLATE_COLUMNS_NARROW;@@ -63,5 +68,10 @@ export const TASK_GRID_TEMPLATE_AREAS_WIDE = `"indicator content ${TASK_GRID_COL(c) => c.id).join(' ')} createdBy timestamp"`;+/** Wide template areas without the leading indicator (checkbox) column. */+export const TASK_GRID_TEMPLATE_AREAS_WIDE_NO_INDICATOR = `"content ${TASK_GRID_COLUMNS.map(+ (c) => c.id+).join(' ')} createdBy timestamp"`;+/** @deprecated Use TASK_GRID_TEMPLATE_AREAS_NARROW or TASK_GRID_TEMPLATE_AREAS_WIDE */const _TASK_GRID_TEMPLATE_AREAS = TASK_GRID_TEMPLATE_AREAS_NARROW;diff --git a/js/app/packages/block-md/component/ComposeTask.tsx b/js/app/packages/block-md/component/ComposeTask.tsxindex 2bef90701a..ebf00e5454 100644--- a/js/app/packages/block-md/component/ComposeTask.tsx+++ b/js/app/packages/block-md/component/ComposeTask.tsx@@ -34,6 +34,7 @@ import { useUpsertToHistoryMutation } from '@queries/history/history';import { refetchSoupEntity } from '@queries/soup/cache';import { propertiesServiceClient } from '@service-properties/client';import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';+import type { TaskSimilarityResult } from '@service-storage/client';import { debounce } from '@solid-primitives/scheduled';import { useQuery } from '@tanstack/solid-query';import { Button, Hotkey, Scroll, ToggleSwitch } from '@ui';@@ -55,6 +56,7 @@ import {updateDraftTimestamp,} from '../util/taskComposerStorage';import { InlinePropertyValue } from './InlinePropertyValue';+import { SimilarTasksSection } from './TaskDuplicatesPill';// Show these props in the composer (Linear-style left-to-right order).const COMPOSER_PROPERTIES = [@@ -222,6 +224,7 @@ export function ComposeTask(props: ComposeTaskProps) {content: draft.content,editorState: draft.editorState,propertyValues: draft.propertyValues,+ similarTasks: draft.similarTasks ?? [],isDraftLoaded: true,};}@@ -231,6 +234,7 @@ export function ComposeTask(props: ComposeTaskProps) {content: props.initialContent ?? '',editorState: undefined,propertyValues: getDefaultPropertyValues(),+ similarTasks: [] as TaskSimilarityResult[],isDraftLoaded: false,};};@@ -250,6 +254,9 @@ export function ComposeTask(props: ComposeTaskProps) {const [createMore, setCreateMore] = createSignal(false);const [errorMessage, setErrorMessage] = createSignal<string>('');const [isCreating, setIsCreating] = createSignal(false);+ const [similarTasks, setSimilarTasks] = createSignal<TaskSimilarityResult[]>(+ initialState.similarTasks+ );let attachInputRef: HTMLInputElement | undefined;const handleAttachFiles = async (event: Event) => {@@ -283,6 +290,7 @@ export function ComposeTask(props: ComposeTaskProps) {// so without this the draft only saved when title/content changed.JSON.stringify(propertyValues);const currentProperties = structuredClone(unwrap(propertyValues));+ const currentSimilarTasks = similarTasks();if (hasInitializedFromDraft) {hasInitializedFromDraft = false;@@ -294,6 +302,7 @@ export function ComposeTask(props: ComposeTaskProps) {content: currentContent,editorState: bodyEditor()?.getEditorState().toJSON(),propertyValues: currentProperties,+ similarTasks: currentSimilarTasks,});});@@ -575,6 +584,17 @@ export function ComposeTask(props: ComposeTaskProps) {props.onClose?.();};+ const handleOpenSimilarTask = (taskId: string) => {+ // Closing snapshots the draft (incl. these results); open the existing task+ // in a new split so the composer's work isn't lost.+ splitPanel.handle.close();+ props.onClose?.();+ openWithSplit(+ { type: 'task', id: taskId },+ { referredFrom: null, preferNewSplit: true }+ );+ };+const handleClearDraft = () => {clearTaskComposerDraft();setTitle('');@@ -846,6 +866,14 @@ export function ComposeTask(props: ComposeTaskProps) {</Button></div></div>++ <SimilarTasksSection+ title={title}+ content={content}+ initialResults={initialState.similarTasks}+ onResults={setSimilarTasks}+ onOpenTask={handleOpenSimilarTask}+ /></div>);}diff --git a/js/app/packages/block-md/component/Notebook.tsx b/js/app/packages/block-md/component/Notebook.tsxindex 1ff89ecabd..d9e977272f 100644--- a/js/app/packages/block-md/component/Notebook.tsx+++ b/js/app/packages/block-md/component/Notebook.tsx@@ -35,6 +35,7 @@ import { InlineTaskProperties } from './InlineTaskProperties';import { InstructionsEditor } from './InstructionsEditor';import { MarkdownEditor } from './MarkdownEditor';import { TaskDiscussion } from './TaskDiscussion';+import { TaskDuplicateMatchPill } from './TaskDuplicateMatches';import { TitleEditor } from './TitleEditor';import { registerMarkdownCommands } from './useMarkdownCommands';@@ -267,6 +268,7 @@ export function Notebook() {<div class="mb-6 flex flex-row flex-wrap items-center gap-2 text-sm empty:hidden"><InlineTaskProperties /><InlineTaskGithubPullRequests />+ <TaskDuplicateMatchPill /></div><ParamsProvider><MarkdownEditor />diff --git a/js/app/packages/block-md/component/TaskDuplicateMatches.tsx b/js/app/packages/block-md/component/TaskDuplicateMatches.tsxnew file mode 100644index 0000000000..03e1c6f520--- /dev/null+++ b/js/app/packages/block-md/component/TaskDuplicateMatches.tsx@@ -0,0 +1,201 @@+import { SidePanel } from '@app/component/side-panel';+import { useBlockId } from '@core/block';+import { DocumentMention } from '@core/component/LexicalMarkdown/component/decorator/DocumentMention';+import { toast } from '@core/component/Toast/Toast';+import CaretDownIcon from '@phosphor/caret-down.svg';+import WarningIcon from '@phosphor/warning.svg';+import {+ useDismissTaskDuplicatesMutation,+ useTaskDuplicatesQuery,+} from '@queries/storage/task-duplicates';+import type { TaskDuplicate } from '@service-storage/client';+import { Button, cn, Dropdown } from '@ui';+import { createMemo, createSignal, For, Show, Suspense } from 'solid-js';++export function TaskDuplicateMatchPill() {+ const matches = useTaskDuplicateMatches();+ const [open, setOpen] = createSignal(false);++ return (+ <Suspense>+ <Show when={matches.count() > 0}>+ <Dropdown open={open()} onOpenChange={setOpen} placement="bottom-start">+ <Dropdown.Trigger+ depth={2}+ class={cn(+ 'h-auto min-w-0 gap-1.5 rounded-full border-failure/40 px-2 py-1 leading-tight',+ 'bg-failure/10 text-failure-ink shadow-none',+ 'hover:bg-failure/15 focus-visible:bg-failure/15 focus-visible:ring-failure/60',+ open() && 'bg-failure/15'+ )}+ title="Possible duplicate tasks"+ >+ <WarningIcon class="size-3 shrink-0" />+ <span class="truncate">Duplicate Detected</span>+ <CaretDownIcon class="size-3 shrink-0 text-current/70" />+ </Dropdown.Trigger>+ <Dropdown.Content class="max-w-[calc(100vw-24px)]">+ <TaskDuplicateMatchPopover matches={matches} />+ </Dropdown.Content>+ </Dropdown>+ </Show>+ </Suspense>+ );+}++export function TaskDuplicateMatchesSidePanelSection() {+ const matches = useTaskDuplicateMatches();++ return (+ <Suspense>+ <Show when={matches.count() > 0}>+ <SidePanel.Section+ id="duplicates"+ title="Matches"+ defaultOpen+ order={30}+ >+ <TaskDuplicateMatchesSidePanel matches={matches} />+ </SidePanel.Section>+ </Show>+ </Suspense>+ );+}++type TaskDuplicateMatchesState = ReturnType<typeof useTaskDuplicateMatches>;++function useTaskDuplicateMatches() {+ const blockId = useBlockId();+ const matchesQuery = useTaskDuplicatesQuery(() => blockId);+ const dismissMutation = useDismissTaskDuplicatesMutation(() => blockId);++ const matches = createMemo(() => matchesQuery.data ?? []);+ const count = () => matches().length;++ const dismiss = async (matchesToDismiss: TaskDuplicate[]) => {+ if (matchesToDismiss.length === 0) return;+ const plural = matchesToDismiss.length > 1;++ try {+ await dismissMutation.mutateAsync({+ matchIds: matchesToDismiss.map((match) => match.id),+ otherDocumentIds: matchesToDismiss.map((match) => match.taskId),+ });+ toast.success(plural ? 'Duplicates dismissed.' : 'Duplicate dismissed.');+ } catch {+ toast.failure(+ plural+ ? 'Could not dismiss duplicates.'+ : 'Could not dismiss duplicate.'+ );+ }+ };++ return {+ count,+ dismiss,+ matches,+ };+}++function TaskDuplicateMatchPopover(props: {+ matches: TaskDuplicateMatchesState;+}) {+ return (+ <>+ <Dropdown.Group class="max-h-[320px] overflow-auto">+ <div class="flex w-max max-w-[calc(100vw-48px)] flex-col gap-0.5">+ <For each={props.matches.matches()}>+ {(match) => (+ <TaskDuplicateRow+ match={match}+ onDismiss={() => props.matches.dismiss([match])}+ />+ )}+ </For>+ </div>+ </Dropdown.Group>+ <Dropdown.Group>+ <DismissAllButton+ onDismissAll={() => props.matches.dismiss(props.matches.matches())}+ />+ </Dropdown.Group>+ </>+ );+}++function TaskDuplicateMatchesSidePanel(props: {+ matches: TaskDuplicateMatchesState;+}) {+ return (+ <div class="flex flex-col gap-1 py-2">+ <For each={props.matches.matches()}>+ {(match) => (+ <TaskDuplicateRow+ match={match}+ onDismiss={() => props.matches.dismiss([match])}+ />+ )}+ </For>+ <DismissAllButton+ onDismissAll={() => props.matches.dismiss(props.matches.matches())}+ />+ </div>+ );+}++function TaskDuplicateMention(props: { match: TaskDuplicate }) {+ return (+ <span class="min-w-0 flex-1 truncate text-xs">+ <DocumentMention+ key={props.match.id}+ documentId={props.match.taskId}+ documentName={props.match.taskName || 'Untitled task'}+ blockName="task"+ theme={{}}+ />+ </span>+ );+}++function DismissDuplicateButton(props: { onDismiss: () => void }) {+ return (+ <Button+ depth={2}+ variant="base"+ size="sm"+ class="h-6 shrink-0 px-2 text-xs"+ onClick={props.onDismiss}+ >+ Dismiss+ </Button>+ );+}++function DismissAllButton(props: { onDismissAll: () => void }) {+ return (+ <Button+ depth={2}+ variant="base"+ size="sm"+ class="mt-1 w-fit text-xs"+ onClick={props.onDismissAll}+ >+ Dismiss all+ </Button>+ );+}++function TaskDuplicateRow(props: {+ match: TaskDuplicate;+ onDismiss: () => void;+}) {+ return (+ <div class={cn('rounded-lg px-2 py-1.5', 'hover:bg-surface-hover')}>+ <div class="flex min-w-0 items-center gap-1.5">+ <TaskDuplicateMention match={props.match} />+ <DismissDuplicateButton onDismiss={props.onDismiss} />+ </div>+ </div>+ );+}diff --git a/js/app/packages/block-md/component/TaskDuplicatesPill.tsx b/js/app/packages/block-md/component/TaskDuplicatesPill.tsxnew file mode 100644index 0000000000..276b1cfb92--- /dev/null+++ b/js/app/packages/block-md/component/TaskDuplicatesPill.tsx@@ -0,0 +1,166 @@+import { TaskListEntity } from '@app/component/next-soup/soup-view/views/tasks/TaskListEntity';+import { ListLayoutProvider } from '@entity';+import CaretRightIcon from '@phosphor/caret-right.svg';+import CopyIcon from '@phosphor/copy.svg';+import { useSoupItemsQuery } from '@queries/soup/items';+import { useTaskSimilaritySearchQuery } from '@queries/storage/task-duplicates';+import type { TaskSimilarityResult } from '@service-storage/client';+import { debounce } from '@solid-primitives/scheduled';+import { cn } from '@ui';+import {+ type Accessor,+ createEffect,+ createSignal,+ For,+ Show,+ Suspense,+} from 'solid-js';++const DEBOUNCE_MS = 500;++type DebouncedInput = { title: string; markdown: string };++/**+ * Inner component: lives inside the local `<Suspense>` so every read of query+ * data (similarity + soup) is contained here and a pending fetch suspends only+ * this subtree instead of bubbling up and remounting the composer.+ */+function SimilarTasksInner(props: {+ debounced: Accessor<DebouncedInput>;+ initialResults: TaskSimilarityResult[];+ onResults: (results: TaskSimilarityResult[]) => void;+ onOpenTask: (taskId: string) => void;+}) {+ const [expanded, setExpanded] = createSignal(true);+ const [listRef, setListRef] = createSignal<HTMLElement>();++ // The composer's draft (and its saved results) was loaded for this input.+ const initialInput = props.debounced();++ const similarity = useTaskSimilaritySearchQuery(+ () => ({+ title: props.debounced().title,+ markdown: props.debounced().markdown,+ // Mirror the composer's create call, which does not share with a team.+ shareWithTeam: false,+ }),+ () => {+ const input = props.debounced();+ const isInitialInput =+ input.title === initialInput.title &&+ input.markdown === initialInput.markdown;+ return isInitialInput && props.initialResults.length > 0+ ? props.initialResults+ : undefined;+ }+ );++ // Persist the latest results with the composer draft.+ createEffect(() => {+ const data = similarity.data;+ if (data) props.onResults(data);+ });++ // Live results once loaded, otherwise the results saved with the draft.+ const results = (): TaskSimilarityResult[] =>+ similarity.data ?? props.initialResults;+ const ids = () => results().map((result) => result.taskId);++ // Hydrate full soup entities (status, owner, assignees, …) for the matches so+ // they render identically to the soup task list.+ const soup = useSoupItemsQuery(+ () => ({+ params: { limit: 25 },+ body: {+ document_filters: { document_ids: ids(), sub_types: ['task'] },+ },+ }),+ () => ({ enabled: ids().length > 0, staleTime: 30 * 1000 })+ );++ // Keep the similarity ranking order.+ const entities = () => {+ const order = new Map(ids().map((id, index) => [id, index] as const));+ return [...(soup.data ?? [])]+ .filter((entity) => order.has(entity.id))+ .sort((a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0));+ };++ return (+ <Show when={entities().length > 0}>+ <div class="shrink-0 flex flex-col gap-0.5">+ <button+ type="button"+ class="flex items-center gap-1.5 px-1.5 py-1 text-xs font-medium text-ink-muted hover:text-ink"+ onClick={() => setExpanded((value) => !value)}+ >+ <CaretRightIcon+ class={cn(+ 'size-3 shrink-0 transition-transform duration-90',+ expanded() && 'rotate-90'+ )}+ />+ <CopyIcon class="size-3.5 shrink-0" />+ <span>Possible duplicates</span>+ </button>+ <Show when={expanded()}>+ <ListLayoutProvider ref={listRef}>+ <div+ ref={setListRef}+ class="flex max-h-48 flex-col overflow-y-auto scrollbar-hidden"+ >+ <For each={entities()}>+ {(entity) => (+ <TaskListEntity+ entity={entity}+ hideCheckbox+ onClick={() => props.onOpenTask(entity.id)}+ />+ )}+ </For>+ </div>+ </ListLayoutProvider>+ </Show>+ </div>+ </Show>+ );+}++/**+ * Live "Possible duplicates" section for the task composer. As the user types,+ * it debounces the draft title/body and runs an ephemeral similarity search+ * against existing tasks (no vectors or matches are persisted), rendering hits+ * as soup-style task rows under a collapsible header.+ */+export function SimilarTasksSection(props: {+ title: Accessor<string>;+ content: Accessor<string>;+ initialResults: TaskSimilarityResult[];+ onResults: (results: TaskSimilarityResult[]) => void;+ onOpenTask: (taskId: string) => void;+}) {+ const [debounced, setDebounced] = createSignal<DebouncedInput>({+ title: props.title(),+ markdown: props.content(),+ });++ const updateDebounced = debounce(+ (next: DebouncedInput) => setDebounced(next),+ DEBOUNCE_MS+ );++ createEffect(() => {+ updateDebounced({ title: props.title(), markdown: props.content() });+ });++ return (+ <Suspense>+ <SimilarTasksInner+ debounced={debounced}+ initialResults={props.initialResults}+ onResults={props.onResults}+ onOpenTask={props.onOpenTask}+ />+ </Suspense>+ );+}diff --git a/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx b/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsxindex a019aeba26..bfe3147329 100644--- a/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx+++ b/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx@@ -58,6 +58,7 @@ import {Switch,} from 'solid-js';import { mdStore } from '../../signal/markdownBlockData';+import { TaskDuplicateMatchesSidePanelSection } from '../TaskDuplicateMatches';interface MarkdownSidePanelSectionsProps {canEdit: boolean;@@ -102,7 +103,10 @@ export function MarkdownSidePanelSections(<StatsSectionContent /></SidePanel.Section></Show>- <GithubSectionConditional documentId={blockId} isTask={isTask()} />+ <Show when={isTask()}>+ <TaskDuplicateMatchesSidePanelSection />+ </Show>+ <GithubSectionConditional documentId={blockId} isTask={isTask} /><NotificationsSectionConditional entity={entity()} /><ReferencesSectionConditional documentId={blockId} /></>@@ -928,7 +932,7 @@ function ReferencesSectionConditional(props: { documentId: string }) {function GithubSectionConditional(props: {documentId: string;- isTask: boolean;+ isTask: () => boolean;}) {const query = useDocumentGithubPullRequestsQuery(props.documentId,@@ -936,7 +940,7 @@ function GithubSectionConditional(props: {);const pullRequests = createMemo((): GithubPullRequest[] => {- if (!props.isTask || query.isLoading || query.isError) return [];+ if (!props.isTask() || query.isLoading || query.isError) return [];return query.data?.pullRequests ?? [];});const count = createMemo(() => pullRequests().length);diff --git a/js/app/packages/block-md/util/taskComposerStorage.ts b/js/app/packages/block-md/util/taskComposerStorage.tsindex 2aeb2c34c5..0b2bae4024 100644--- a/js/app/packages/block-md/util/taskComposerStorage.ts+++ b/js/app/packages/block-md/util/taskComposerStorage.ts@@ -1,4 +1,5 @@import type { PropertyApiValues } from '@property/types';+import type { TaskSimilarityResult } from '@service-storage/client';import type { SerializedEditorState } from 'lexical';const STORAGE_KEY = 'task-composer-draft';@@ -11,6 +12,9 @@ export interface TaskComposerDraft {/** Markdown text fallback (used by older drafts and for the createTask API) */content: string;propertyValues: Record<string, PropertyApiValues>;+ /** Possible-duplicate tasks last surfaced for this draft, persisted so they+ * reappear instantly when the draft is restored. */+ similarTasks?: TaskSimilarityResult[];timestamp: number;}diff --git a/js/app/packages/entity/src/composed/list-entity/narrow-layout.tsx b/js/app/packages/entity/src/composed/list-entity/narrow-layout.tsxindex 86019ab10c..48dcdc3b0f 100644--- a/js/app/packages/entity/src/composed/list-entity/narrow-layout.tsx+++ b/js/app/packages/entity/src/composed/list-entity/narrow-layout.tsx@@ -25,16 +25,18 @@ export function NarrowLayout(props: LayoutProps) {}}><Entity.Slot placement="indicator" class="relative self-start pt-3">- <div- class={cn('w-0 opacity-0 overflow-hidden', {- 'w-6 opacity-100': props.checked,- })}- >- <MultiSelectCheckbox- checked={props.checked}- onChecked={props.onChecked}- />- </div>+ <Show when={!props.hideCheckbox}>+ <div+ class={cn('w-0 opacity-0 overflow-hidden', {+ 'w-6 opacity-100': props.checked,+ })}+ >+ <MultiSelectCheckbox+ checked={props.checked}+ onChecked={props.onChecked}+ />+ </div>+ </Show></Entity.Slot><Entity.Slotdiff --git a/js/app/packages/entity/src/composed/list-entity/shared.tsx b/js/app/packages/entity/src/composed/list-entity/shared.tsxindex fa49fd4a59..0f3d72bac5 100644--- a/js/app/packages/entity/src/composed/list-entity/shared.tsx+++ b/js/app/packages/entity/src/composed/list-entity/shared.tsx@@ -26,6 +26,8 @@ export interface BaseListEntityProps<E extends EntityData = EntityData> {highlighted?: boolean;hovered?: boolean;hideContentHits?: boolean;+ /** Hide the multi-select checkbox (e.g. read-only embeds outside soup). */+ hideCheckbox?: boolean;onChecked?: (checked: boolean, shiftKey: boolean) => void;onMouseMove?: () => void;onProjectClick?: (@@ -44,6 +46,7 @@ const WIDE_BREAKPOINT = 512; // @lg container query = 32remexport interface LayoutProps {entity: WithNotification<EntityData>;checked?: boolean;+ hideCheckbox?: boolean;onChecked?: (checked: boolean, shiftKey: boolean) => void;unread: boolean;isShared: boolean;diff --git a/js/app/packages/queries/storage/keys.ts b/js/app/packages/queries/storage/keys.tsindex c4f07dcc6c..f24a820ba1 100644--- a/js/app/packages/queries/storage/keys.ts+++ b/js/app/packages/queries/storage/keys.ts@@ -58,8 +58,24 @@ export const entityKeys = createQueryKeys('entity', {projectData: (projectId: string) => ({queryKey: [projectId],}),+ taskDuplicates: (documentId: string) => ({+ queryKey: [documentId, 'duplicates'],+ }),});+export const taskSimilaritySearchKeys = createQueryKeys(+ 'taskSimilaritySearch',+ {+ forInput: (input: {+ title: string;+ markdown: string;+ shareWithTeam: boolean;+ }) => ({+ queryKey: [input.title, input.markdown, input.shareWithTeam],+ }),+ }+);+export const instructionsMdKeys = createQueryKeys('instructionsMd', {id: null,text: (id: string) => ({diff --git a/js/app/packages/queries/storage/task-duplicates.ts b/js/app/packages/queries/storage/task-duplicates.tsnew file mode 100644index 0000000000..3f6af4f647--- /dev/null+++ b/js/app/packages/queries/storage/task-duplicates.ts@@ -0,0 +1,128 @@+import { queryClient } from '@queries/client';+import {+ storageServiceClient,+ type TaskDuplicate,+ type TaskSimilarityResult,+} from '@service-storage/client';+import { useMutation, useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { entityKeys, taskSimilaritySearchKeys } from './keys';++type TaskDuplicateMatchesUpdatedPayload = {+ documentId: string;+};++export function invalidateTaskDuplicates(documentId: string) {+ return queryClient.invalidateQueries({+ queryKey: entityKeys.taskDuplicates(documentId).queryKey,+ });+}++export function handleTaskDuplicateMatchesUpdated(+ payload: TaskDuplicateMatchesUpdatedPayload+) {+ if (typeof payload.documentId !== 'string') {+ console.warn('Malformed task duplicate live update payload', payload);+ return;+ }+ invalidateTaskDuplicates(payload.documentId);+}++async function fetchTaskDuplicates(+ documentId: string+): Promise<TaskDuplicate[]> {+ const result = await storageServiceClient.getTaskDuplicates({ documentId });+ if (result.isErr()) {+ throw new Error('Failed to fetch task duplicates');+ }+ return result.value;+}++export function useTaskDuplicatesQuery(documentId: Accessor<string>) {+ return useQuery(() => ({+ queryKey: entityKeys.taskDuplicates(documentId()).queryKey,+ queryFn: () => fetchTaskDuplicates(documentId()),+ enabled: !!documentId(),+ staleTime: 30 * 1000,+ }));+}++export function useDismissTaskDuplicatesMutation(documentId: Accessor<string>) {+ return useMutation(() => ({+ mutationFn: async (params: {+ matchIds: string[];+ otherDocumentIds?: string[];+ }) => {+ const result = await storageServiceClient.dismissTaskDuplicates({+ documentId: documentId(),+ matchIds: params.matchIds,+ });+ if (result.isErr()) throw new Error('Failed to dismiss duplicate');+ },+ onSuccess: (_data, params) => {+ invalidateTaskDuplicates(documentId());+ for (const otherDocumentId of params.otherDocumentIds ?? []) {+ invalidateTaskDuplicates(otherDocumentId);+ }+ },+ }));+}++/** Minimum title length before the live similarity search fires. */+export const SIMILARITY_SEARCH_MIN_TITLE_LENGTH = 3;++type TaskSimilaritySearchInput = {+ title: string;+ markdown: string;+ shareWithTeam: boolean;+};++async function searchSimilarTasks(+ input: TaskSimilaritySearchInput+): Promise<TaskSimilarityResult[]> {+ const result = await storageServiceClient.searchSimilarTasks({+ taskName: input.title,+ markdown: input.markdown,+ shareWithTeam: input.shareWithTeam,+ });+ if (result.isErr()) {+ throw new Error('Failed to search for similar tasks');+ }+ return result.value;+}++/**+ * Live, ephemeral similarity search used by the task composer. Hits the+ * stateless `/documents/similarity_search` HTTP endpoint — nothing is+ * persisted, so there is no cache invalidation or dismiss flow.+ *+ * `initialData` lets a restored composer draft seed the results for its+ * initial input so saved matches render instantly without a refetch flash.+ */+export function useTaskSimilaritySearchQuery(+ input: Accessor<TaskSimilaritySearchInput>,+ initialData?: Accessor<TaskSimilarityResult[] | undefined>+) {+ return useQuery(() => ({+ queryKey: taskSimilaritySearchKeys.forInput(input()).queryKey,+ queryFn: () => searchSimilarTasks(input()),+ enabled: input().title.trim().length >= SIMILARITY_SEARCH_MIN_TITLE_LENGTH,+ staleTime: 30 * 1000,+ placeholderData: (prev) => prev,+ initialData: initialData?.(),+ }));+}++export function useDeleteThisDuplicateTaskMutation(+ documentId: Accessor<string>+) {+ return useMutation(() => ({+ mutationFn: async (matchId: string) => {+ const result = await storageServiceClient.deleteThisDuplicateTask({+ documentId: documentId(),+ matchId,+ });+ if (result.isErr()) throw new Error('Failed to delete task');+ },+ }));+}diff --git a/js/app/packages/queries/sync/SyncProvider.tsx b/js/app/packages/queries/sync/SyncProvider.tsxindex b2cece709d..0bac61d30a 100644--- a/js/app/packages/queries/sync/SyncProvider.tsx+++ b/js/app/packages/queries/sync/SyncProvider.tsx@@ -9,6 +9,7 @@ import {applyNotificationStatusUpdate,notificationStatusUpdatePayloadSchema,} from '@queries/notification/user-notifications';+import { handleTaskDuplicateMatchesUpdated } from '@queries/storage/task-duplicates';// Side-effect import: registers the scheduled-action live-update websocket// listener. Must be imported somewhere that always loads on app start — this// provider is guaranteed to mount alongside the other sync handlers.@@ -85,6 +86,13 @@ export function QuerySyncProvider(props: SyncProviderProps) {}applyNotificationStatusUpdate(result.data);})+ .with({ type: 'task_duplicate_matches_updated' }, () => {+ withParsedWebsocketPayload(+ data.type,+ data.data,+ handleTaskDuplicateMatchesUpdated+ );+ }).otherwise(() => {});});diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.tsindex c92226d5a9..eb77dcb0f4 100644--- a/js/app/packages/service-clients/service-storage/client.ts+++ b/js/app/packages/service-clients/service-storage/client.ts@@ -182,6 +182,30 @@ export type { GetOrCreateChannelResponse } from './generated/schemas/getOrCreateexport type IdResponse = { id: string };export type MessageResponse = { message: string };+export type TaskDuplicate = {+ id: string;+ taskId: string;+ taskName: string;+ vectorScore: number;+ rerankScore: number;+ judgeReason?: string | null;+};++export type TaskDuplicatesResponse = {+ duplicates: TaskDuplicate[];+};++export type TaskSimilarityResult = {+ taskId: string;+ taskName: string;+ vectorScore: number;+ rerankScore: number;+};++export type TaskSimilaritySearchResponse = {+ results: TaskSimilarityResult[];+};+type WithChannelId = { channel_id: string };type WithMessageId = { message_id: string };type WithMentionId = { mention_id: string };@@ -969,6 +993,63 @@ export const storageServiceClient = {return ok(response);},+ async getTaskDuplicates(params: { documentId: string }) {+ return (+ await dssFetch<TaskDuplicatesResponse>(+ `/documents/${params.documentId}/duplicates`+ )+ ).map((result) => result.duplicates);+ },++ async searchSimilarTasks(params: {+ taskName: string;+ markdown?: string;+ shareWithTeam?: boolean;+ }) {+ return (+ await dssFetch<TaskSimilaritySearchResponse>(+ `/documents/similarity_search`,+ {+ method: 'POST',+ body: JSON.stringify({+ taskName: params.taskName,+ markdown: params.markdown,+ shareWithTeam: params.shareWithTeam ?? false,+ }),+ }+ )+ ).map((result) => result.results);+ },++ async dismissTaskDuplicates(params: {+ documentId: string;+ matchIds: string[];+ }) {+ return (+ await dssFetch<SuccessResponse>(+ `/documents/${params.documentId}/duplicates/dismiss`,+ {+ method: 'POST',+ body: JSON.stringify({ matchIds: params.matchIds }),+ }+ )+ ).map((result) => result.data);+ },++ async deleteThisDuplicateTask(params: {+ documentId: string;+ matchId: string;+ }) {+ return (+ await dssFetch<SuccessResponse>(+ `/documents/${params.documentId}/duplicates/${params.matchId}/delete_this`,+ {+ method: 'POST',+ }+ )+ ).map((result) => result.data);+ },+async copyDocument(params: {documentId: string;documentVersionId?: number;diff --git a/js/lexmark_test.mjs b/js/lexmark_test.mjsnew file mode 100644index 0000000000..e69de29bb2diff --git a/rust/cloud-storage/.sqlx/query-0c2a70e1c21ea156df7ebcfac398759e58dad1a553de9c0bbbb2480f65eadc13.json b/rust/cloud-storage/.sqlx/query-0c2a70e1c21ea156df7ebcfac398759e58dad1a553de9c0bbbb2480f65eadc13.jsonnew file mode 100644index 0000000000..a50b80bf97--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-0c2a70e1c21ea156df7ebcfac398759e58dad1a553de9c0bbbb2480f65eadc13.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH ranked AS (\n SELECT\n id,\n ROW_NUMBER() OVER (\n ORDER BY rerank_score DESC, vector_score DESC, created_at DESC\n ) AS rn\n FROM task_duplicate_match\n WHERE status = 'active'\n AND (task_id = $1 OR duplicate_task_id = $1)\n )\n UPDATE task_duplicate_match m\n SET status = 'dismissed', updated_at = NOW()\n FROM ranked r\n WHERE m.id = r.id\n AND r.rn > $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Int8"+ ]+ },+ "nullable": []+ },+ "hash": "0c2a70e1c21ea156df7ebcfac398759e58dad1a553de9c0bbbb2480f65eadc13"+}diff --git a/rust/cloud-storage/.sqlx/query-10bf501670966259cfcb441f519bf04a5ff4827980d61db77cf7645ed9bf551b.json b/rust/cloud-storage/.sqlx/query-10bf501670966259cfcb441f519bf04a5ff4827980d61db77cf7645ed9bf551b.jsonnew file mode 100644index 0000000000..21b13aae0d--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-10bf501670966259cfcb441f519bf04a5ff4827980d61db77cf7645ed9bf551b.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH RECURSIVE edges(left_id, right_id) AS (\n SELECT m.task_id, m.duplicate_task_id\n FROM task_duplicate_match m\n JOIN \"Document\" left_document ON left_document.id = m.task_id\n JOIN \"Document\" right_document ON right_document.id = m.duplicate_task_id\n WHERE m.status = 'active'\n AND left_document.\"deletedAt\" IS NULL\n AND right_document.\"deletedAt\" IS NULL\n ),\n component(document_id) AS (\n SELECT DISTINCT unnest($1::text[])\n UNION\n SELECT CASE\n WHEN edges.left_id = component.document_id THEN edges.right_id\n ELSE edges.left_id\n END\n FROM edges\n JOIN component\n ON component.document_id = edges.left_id\n OR component.document_id = edges.right_id\n )\n SELECT DISTINCT document_id AS \"document_id!\"\n FROM component\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "document_id!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "10bf501670966259cfcb441f519bf04a5ff4827980d61db77cf7645ed9bf551b"+}diff --git a/rust/cloud-storage/.sqlx/query-44ab35ac16518bff10aff07ec9a9998785d481f1b38b453e06bd97f971cd6338.json b/rust/cloud-storage/.sqlx/query-44ab35ac16518bff10aff07ec9a9998785d481f1b38b453e06bd97f971cd6338.jsonnew file mode 100644index 0000000000..02dbdeac4b--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-44ab35ac16518bff10aff07ec9a9998785d481f1b38b453e06bd97f971cd6338.json@@ -0,0 +1,43 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n e.document_id,\n d.name AS \"name!\",\n e.content,\n 1 - (e.embedding <=> $3::text::vector) AS \"vector_score!\"\n FROM task_duplicate_embedding e\n JOIN \"Document\" d ON d.id = e.document_id\n JOIN document_sub_type dst ON dst.document_id = d.id AND dst.sub_type = 'task'\n LEFT JOIN team_task tt ON tt.document_id = d.id\n WHERE d.\"deletedAt\" IS NULL\n AND (\n d.owner = $1\n OR ($2::uuid IS NOT NULL AND tt.team_id = $2)\n )\n ORDER BY e.embedding <=> $3::text::vector\n LIMIT $4\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "document_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "name!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "content",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "vector_score!",+ "type_info": "Float8"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid",+ "Text",+ "Int8"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ null+ ]+ },+ "hash": "44ab35ac16518bff10aff07ec9a9998785d481f1b38b453e06bd97f971cd6338"+}diff --git a/rust/cloud-storage/.sqlx/query-4b12c2d75c8b90ec6c843ce8e6770c30f06903a19285042b197941acd47a8149.json b/rust/cloud-storage/.sqlx/query-4b12c2d75c8b90ec6c843ce8e6770c30f06903a19285042b197941acd47a8149.jsonnew file mode 100644index 0000000000..a3ad5805fa--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-4b12c2d75c8b90ec6c843ce8e6770c30f06903a19285042b197941acd47a8149.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO task_duplicate_match (\n id,\n task_id,\n duplicate_task_id,\n status,\n vector_score,\n rerank_score,\n judge_model,\n judge_reason\n )\n VALUES ($1, $2, $3, 'active', $4, $5, $6, $7)\n ON CONFLICT (task_id, duplicate_task_id) DO UPDATE\n SET status = 'active',\n vector_score = EXCLUDED.vector_score,\n rerank_score = EXCLUDED.rerank_score,\n judge_model = EXCLUDED.judge_model,\n judge_reason = EXCLUDED.judge_reason,\n updated_at = NOW()\n WHERE task_duplicate_match.status <> 'dismissed'\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Float8",+ "Float8",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "4b12c2d75c8b90ec6c843ce8e6770c30f06903a19285042b197941acd47a8149"+}diff --git a/rust/cloud-storage/.sqlx/query-6a9de1564f16007df9f5758baad9f9d5c22ca624f08f29bed7fe9e265288eba9.json b/rust/cloud-storage/.sqlx/query-6a9de1564f16007df9f5758baad9f9d5c22ca624f08f29bed7fe9e265288eba9.jsonnew file mode 100644index 0000000000..80b721af4a--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-6a9de1564f16007df9f5758baad9f9d5c22ca624f08f29bed7fe9e265288eba9.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE task_duplicate_match\n SET status = 'dismissed',\n dismissed_by = $3,\n dismissed_at = NOW(),\n updated_at = NOW()\n WHERE id = $1\n AND (task_id = $2 OR duplicate_task_id = $2)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "6a9de1564f16007df9f5758baad9f9d5c22ca624f08f29bed7fe9e265288eba9"+}diff --git a/rust/cloud-storage/.sqlx/query-6f9c55c52025db2dbe4b76be30d2ca5c95970ef6ad421ec0f5fbe89bea212ff5.json b/rust/cloud-storage/.sqlx/query-6f9c55c52025db2dbe4b76be30d2ca5c95970ef6ad421ec0f5fbe89bea212ff5.jsonnew file mode 100644index 0000000000..0d25c6312d--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-6f9c55c52025db2dbe4b76be30d2ca5c95970ef6ad421ec0f5fbe89bea212ff5.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM task_duplicate_match\n WHERE id = $1\n AND (task_id = $2 OR duplicate_task_id = $2)\n )\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "exists",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "6f9c55c52025db2dbe4b76be30d2ca5c95970ef6ad421ec0f5fbe89bea212ff5"+}diff --git a/rust/cloud-storage/.sqlx/query-72db8a2592b5a60ef17fa2842994503ba8506e3b792d40d26cc7c31e750081a8.json b/rust/cloud-storage/.sqlx/query-72db8a2592b5a60ef17fa2842994503ba8506e3b792d40d26cc7c31e750081a8.jsonnew file mode 100644index 0000000000..aa9684ef62--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-72db8a2592b5a60ef17fa2842994503ba8506e3b792d40d26cc7c31e750081a8.json@@ -0,0 +1,52 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n m.id,\n CASE WHEN m.task_id = $1 THEN m.duplicate_task_id ELSE m.task_id END AS \"other_task_id!\",\n d.name AS \"other_task_name!\",\n m.vector_score AS \"vector_score!\",\n m.rerank_score AS \"rerank_score!\",\n m.judge_reason\n FROM task_duplicate_match m\n JOIN \"Document\" d\n ON d.id = CASE WHEN m.task_id = $1 THEN m.duplicate_task_id ELSE m.task_id END\n WHERE m.status = 'active'\n AND (m.task_id = $1 OR m.duplicate_task_id = $1)\n AND d.\"deletedAt\" IS NULL\n ORDER BY m.rerank_score DESC, m.vector_score DESC, m.created_at DESC\n LIMIT 10\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "other_task_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "other_task_name!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "vector_score!",+ "type_info": "Float8"+ },+ {+ "ordinal": 4,+ "name": "rerank_score!",+ "type_info": "Float8"+ },+ {+ "ordinal": 5,+ "name": "judge_reason",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ null,+ false,+ false,+ false,+ true+ ]+ },+ "hash": "72db8a2592b5a60ef17fa2842994503ba8506e3b792d40d26cc7c31e750081a8"+}diff --git a/rust/cloud-storage/.sqlx/query-88e5097f74825c09d6477ee3807b21e5814a9e67cd94f9c34a044d26c147f1fe.json b/rust/cloud-storage/.sqlx/query-88e5097f74825c09d6477ee3807b21e5814a9e67cd94f9c34a044d26c147f1fe.jsonnew file mode 100644index 0000000000..c21a7340d1--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-88e5097f74825c09d6477ee3807b21e5814a9e67cd94f9c34a044d26c147f1fe.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE task_duplicate_match\n SET status = 'dismissed', dismissed_by = $2, dismissed_at = NOW(), updated_at = NOW()\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "88e5097f74825c09d6477ee3807b21e5814a9e67cd94f9c34a044d26c147f1fe"+}diff --git a/rust/cloud-storage/.sqlx/query-89fac636d8ad3699c72ad57a4a5f2bf9211061274491815b8af4c634e62cee06.json b/rust/cloud-storage/.sqlx/query-89fac636d8ad3699c72ad57a4a5f2bf9211061274491815b8af4c634e62cee06.jsonnew file mode 100644index 0000000000..75964adfc9--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-89fac636d8ad3699c72ad57a4a5f2bf9211061274491815b8af4c634e62cee06.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE task_duplicate_match\n SET status = 'dismissed', updated_at = NOW()\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "89fac636d8ad3699c72ad57a4a5f2bf9211061274491815b8af4c634e62cee06"+}diff --git a/rust/cloud-storage/.sqlx/query-c2f61e1119ac4ba2155f472075b5857e086b3ece6e489b6d47a933aea87a02b9.json b/rust/cloud-storage/.sqlx/query-c2f61e1119ac4ba2155f472075b5857e086b3ece6e489b6d47a933aea87a02b9.jsonnew file mode 100644index 0000000000..43b2b133c0--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-c2f61e1119ac4ba2155f472075b5857e086b3ece6e489b6d47a933aea87a02b9.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT task_id, duplicate_task_id\n FROM task_duplicate_match\n WHERE id = $1\n AND (task_id = $2 OR duplicate_task_id = $2)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "task_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "duplicate_task_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "c2f61e1119ac4ba2155f472075b5857e086b3ece6e489b6d47a933aea87a02b9"+}diff --git a/rust/cloud-storage/.sqlx/query-f04c859304822b052e31a56628de7ade7c72155fc232cb0ec08b543530d47758.json b/rust/cloud-storage/.sqlx/query-f04c859304822b052e31a56628de7ade7c72155fc232cb0ec08b543530d47758.jsonnew file mode 100644index 0000000000..f8ffdb3e70--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-f04c859304822b052e31a56628de7ade7c72155fc232cb0ec08b543530d47758.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO task_duplicate_embedding (document_id, model, content, embedding)\n VALUES ($1, $2, $3, $4::text::vector)\n ON CONFLICT (document_id) DO UPDATE\n SET model = EXCLUDED.model,\n content = EXCLUDED.content,\n embedding = EXCLUDED.embedding,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "f04c859304822b052e31a56628de7ade7c72155fc232cb0ec08b543530d47758"+}diff --git a/rust/cloud-storage/.sqlx/query-f62b5eb569c1751fe1b85a81c1b50811245e71af919de567277e505bb59d62e5.json b/rust/cloud-storage/.sqlx/query-f62b5eb569c1751fe1b85a81c1b50811245e71af919de567277e505bb59d62e5.jsonnew file mode 100644index 0000000000..a5c0451b89--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-f62b5eb569c1751fe1b85a81c1b50811245e71af919de567277e505bb59d62e5.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT task_id, duplicate_task_id\n FROM task_duplicate_match\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "task_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "duplicate_task_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "f62b5eb569c1751fe1b85a81c1b50811245e71af919de567277e505bb59d62e5"+}diff --git a/rust/cloud-storage/.sqlx/query-fed750ca47b0b07b0220ebc66fbc970dbe397c91a94a6b7cae1c93e7e078fca5.json b/rust/cloud-storage/.sqlx/query-fed750ca47b0b07b0220ebc66fbc970dbe397c91a94a6b7cae1c93e7e078fca5.jsonnew file mode 100644index 0000000000..806dd516a2--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-fed750ca47b0b07b0220ebc66fbc970dbe397c91a94a6b7cae1c93e7e078fca5.json@@ -0,0 +1,38 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n e.document_id,\n e.content,\n 1 - (e.embedding <=> $2::text::vector) AS \"vector_score!\"\n FROM task_duplicate_embedding e\n JOIN \"Document\" d ON d.id = e.document_id\n JOIN document_sub_type dst ON dst.document_id = d.id AND dst.sub_type = 'task'\n LEFT JOIN team_task tt ON tt.document_id = d.id\n WHERE e.document_id <> $1\n AND d.\"deletedAt\" IS NULL\n AND (\n d.owner = $3\n OR ($4::uuid IS NOT NULL AND tt.team_id = $4)\n )\n AND NOT EXISTS (\n SELECT 1\n FROM task_duplicate_match m\n WHERE (\n m.task_id = LEAST($1, e.document_id)\n AND m.duplicate_task_id = GREATEST($1, e.document_id)\n AND m.status = 'dismissed'\n )\n )\n ORDER BY e.embedding <=> $2::text::vector\n LIMIT $5\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "document_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "content",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "vector_score!",+ "type_info": "Float8"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Uuid",+ "Int8"+ ]+ },+ "nullable": [+ false,+ false,+ null+ ]+ },+ "hash": "fed750ca47b0b07b0220ebc66fbc970dbe397c91a94a6b7cae1c93e7e078fca5"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 9f25e7c8d1..a882de5708 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -3463,6 +3463,7 @@ dependencies = ["sync_service","sync_service_client","system_properties",+ "task_dedup","thiserror 2.0.18","tokio","tower 0.5.3",@@ -3601,6 +3602,7 @@ dependencies = ["sha2 0.10.9","sqlx","sync_service_client",+ "task_dedup","thiserror 2.0.18","tokio","tower 0.5.3",@@ -11400,6 +11402,27 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417"+[[package]]+name = "task_dedup"+version = "0.1.0"+dependencies = [+ "agent",+ "anyhow",+ "async-trait",+ "connection_gateway_client",+ "macro_db_migrator",+ "model-entity",+ "reqwest 0.13.3",+ "serde",+ "serde_json",+ "sqlx",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "utoipa",+ "uuid",+]+[[package]]name = "teams"version = "0.1.0"diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 3414e2058e..2cd07447f6 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -44,6 +44,7 @@ members = ["seed_cli","sha_cleanup_worker","static_file_service",+ "task_dedup","tools/native_app_server","unfurl","unfurl_service",diff --git a/rust/cloud-storage/agent/src/lib.rs b/rust/cloud-storage/agent/src/lib.rsindex dd0a0ed883..8425db2cbe 100644--- a/rust/cloud-storage/agent/src/lib.rs+++ b/rust/cloud-storage/agent/src/lib.rs@@ -24,4 +24,5 @@ pub use model::AgentModel;pub use stream::{ChatCompletionStream, McpInfo, StreamPart, ToolCall, ToolResponse, Usage};pub use tool_adapter::{DynToolSetAdapter, ToolsetToolAdapter};+pub use rig_core::message::Message;pub use rig_core::tool::{Tool, ToolDyn};diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex 20264cd47a..0978d01ef7 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -52,6 +52,7 @@ cowlike = { path = "../cowlike" }crm = { path = "../crm" }document_sub_type = { path = "../document_sub_type" }documents_hex = { path = "../documents", package = "documents" }+task_dedup = { path = "../task_dedup" }dynamodb_client = { path = "../dynamodb_client" }email = { path = "../email", features = ["outbound", "ports"] }entity_access = { path = "../entity_access", features = ["inbound", "schema"] }diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 1b2bd7cae5..a8da0ac3f1 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -87,6 +87,14 @@ use sqlx::postgres::PgPoolOptions;use std::sync::Arc;use sync_service_client::SyncServiceClient;use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};+use task_dedup::{+ TaskDedupConfig, TaskDedupService,+ outbound::{+ connection_gateway::ConnectionGatewayTaskDedupNotifier,+ embedding::OpenAiOrLocalTaskEmbedder, judge::AgentDuplicateJudge,+ postgres::PgTaskDedupRepo,+ },+};mod api;mod config;@@ -563,6 +571,18 @@ async fn main() -> anyhow::Result<()> {let sqs_client = Arc::new(sqs_client);let conn_gateway_client = Arc::new(conn_gateway_client);+ let task_dedup_config = TaskDedupConfig::default();+ let task_dedup_service = Arc::new(TaskDedupService::new(+ task_dedup_config.clone(),+ Arc::new(PgTaskDedupRepo::new(db.clone())),+ Arc::new(OpenAiOrLocalTaskEmbedder::new(+ task_dedup_config.embedding_model.clone(),+ )),+ Arc::new(AgentDuplicateJudge::new(0.56)),+ Arc::new(ConnectionGatewayTaskDedupNotifier::new(+ conn_gateway_client.clone(),+ )),+ ));let channels_repo = PgChannelsRepo::new(db.clone());let bots_service = bots::domain::service::BotServiceImpl::new(bots::outbound::pg_bots_repo::PgBotsRepo::new(db.clone()),@@ -621,6 +641,7 @@ async fn main() -> anyhow::Result<()> {service: document_service.clone(),access_service: entity_access_service.clone(),pool: db.clone(),+ task_dedup_service,creator: documents_hex::domain::create::DocumentCreator::new(document_service,markdown_initializer,diff --git a/rust/cloud-storage/documents/Cargo.toml b/rust/cloud-storage/documents/Cargo.tomlindex 386a9d12c1..04e7581428 100644--- a/rust/cloud-storage/documents/Cargo.toml+++ b/rust/cloud-storage/documents/Cargo.toml@@ -33,6 +33,7 @@ axum = ["dep:axum-extra","dep:model-error-response","dep:model_user",+ "dep:task_dedup","dep:utoipa","entity_access/axum",]@@ -112,6 +113,7 @@ futures = { workspace = true }hex = { workspace = true, optional = true }sqlx = { workspace = true, optional = true }sync_service_client = { path = "../sync_service_client" }+task_dedup = { path = "../task_dedup", optional = true }urlencoding = { workspace = true }# AI Tool dependenciesdiff --git a/rust/cloud-storage/documents/src/inbound/axum_router.rs b/rust/cloud-storage/documents/src/inbound/axum_router.rsindex f2e8b69046..2bfb29639b 100644--- a/rust/cloud-storage/documents/src/inbound/axum_router.rs+++ b/rust/cloud-storage/documents/src/inbound/axum_router.rs@@ -25,6 +25,7 @@ pub mod get_document;pub mod get_github_pull_requests;pub mod get_location;pub mod get_short_id;+pub mod task_duplicates;use std::sync::Arc;@@ -40,15 +41,25 @@ use entity_access::domain::ports::EntityAccessService;use model_error_response::ErrorResponse;use serde::Deserialize;use sqlx::PgPool;+use task_dedup::TaskDedupService;#[cfg(feature = "document_create")]use self::create_markdown::create_markdown_handler;use self::{- copy_document::copy_document_handler, create_document::create_document_handler,- create_task::create_task_handler, delete_document::delete_document_handler,- edit_document::edit_document_handler, get_branch_name::get_branch_name_handler,- get_document::get_document_handler, get_github_pull_requests::get_github_pull_requests_handler,- get_location::get_location_v3_handler, get_short_id::get_short_id_handler,+ copy_document::copy_document_handler,+ create_document::create_document_handler,+ create_task::create_task_handler,+ delete_document::delete_document_handler,+ edit_document::edit_document_handler,+ get_branch_name::get_branch_name_handler,+ get_document::get_document_handler,+ get_github_pull_requests::get_github_pull_requests_handler,+ get_location::get_location_v3_handler,+ get_short_id::get_short_id_handler,+ task_duplicates::{+ delete_this_duplicate_task_handler, dismiss_task_duplicates_handler,+ get_task_duplicates_handler, task_similarity_search_handler,+ },};use crate::domain::models::DocumentError;@@ -98,6 +109,8 @@ pub struct DocumentRouterState<T, Svc> {pub access_service: Arc<Svc>,/// The database pool (used by middleware for document lookups).pub pool: PgPool,+ /// Task duplicate detection service.+ pub task_dedup_service: Arc<TaskDedupService>,/// Backend-owned document creation use case.#[cfg(feature = "document_create_adapters")]pub creator: DefaultDocumentCreator<T>,@@ -110,6 +123,7 @@ impl<T, Svc> Clone for DocumentRouterState<T, Svc> {service: self.service.clone(),access_service: self.access_service.clone(),pool: self.pool.clone(),+ task_dedup_service: self.task_dedup_service.clone(),#[cfg(feature = "document_create_adapters")]creator: self.creator.clone(),}@@ -162,6 +176,18 @@ where.route("/{document_id}/copy",axum::routing::post(copy_document_handler::<T, Svc>),+ )+ .route(+ "/{document_id}/duplicates",+ axum::routing::get(get_task_duplicates_handler::<T, Svc>),+ )+ .route(+ "/{document_id}/duplicates/dismiss",+ axum::routing::post(dismiss_task_duplicates_handler::<T, Svc>),+ )+ .route(+ "/{document_id}/duplicates/{match_id}/delete_this",+ axum::routing::post(delete_this_duplicate_task_handler::<T, Svc>),);let document_id_routes = document_id_routes.layer(middleware::from_fn_with_state(@@ -175,6 +201,10 @@ where.route("/create_task",axum::routing::post(create_task_handler::<T, Svc>),+ )+ .route(+ "/similarity_search",+ axum::routing::post(task_similarity_search_handler::<T, Svc>),);#[cfg(feature = "document_create")]diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/create_task.rs b/rust/cloud-storage/documents/src/inbound/axum_router/create_task.rsindex be181de162..3171faab3c 100644--- a/rust/cloud-storage/documents/src/inbound/axum_router/create_task.rs+++ b/rust/cloud-storage/documents/src/inbound/axum_router/create_task.rs@@ -14,6 +14,9 @@ use crate::domain::create::{MarkdownSubtype, NewDocumentMetadata, NewMarkdownTexuse crate::domain::models::{CreateTaskRequest, CreateTaskResponse, DocumentError};use crate::domain::ports::DocumentService;use crate::domain::ports::create::DocumentCreationService;+use task_dedup::NewTask;++use super::task_duplicates::spawn_task_duplicate_detection;/// Creates a task document with properties and initialized markdown content in/// one backend-owned lifecycle.@@ -40,8 +43,11 @@ pub async fn create_task_handler<project: ProjectBodyAccessLevelExtractor<EditAccessLevel, CreateTaskRequest, Svc>,) -> Result<Json<CreateTaskResponse>, DocumentError> {let req = project.into_inner();+ let task_name = req.task_name.clone();+ let markdown = req.markdown.clone().unwrap_or_default();+ let owner = user_context.macro_user_id.as_ref().to_string();- let mut metadata = NewDocumentMetadata::builder(req.task_name.clone());+ let mut metadata = NewDocumentMetadata::builder(task_name.clone());if let Some(project_id) = req.project_id {metadata = metadata.project_id(project_id);}@@ -60,7 +66,7 @@ pub async fn create_task_handler<user_context.macro_user_id,NewMarkdownTextDocument {metadata: metadata.build(),- markdown: req.markdown.unwrap_or_default(),+ markdown: markdown.clone(),subtype: MarkdownSubtype::Task {property_values: req.property_values,share_with_team: req.share_with_team && team_id.is_some(), // we should only try and share if the user is in a team and they have share_with_team set@@ -71,9 +77,20 @@ pub async fn create_task_handler<.await?;let task_metadata = &created.response().document_response.document_metadata;+ let document_id = created.document_id().to_string();+ spawn_task_duplicate_detection(+ state.task_dedup_service.clone(),+ NewTask {+ document_id: document_id.clone(),+ owner,+ team_id: task_metadata.team_id,+ title: task_name,+ markdown,+ },+ );Ok(Json(CreateTaskResponse {- document_id: created.document_id().to_string(),+ document_id,team_id: task_metadata.team_id,team_task_id: task_metadata.team_task_id,}))diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/task_duplicates.rs b/rust/cloud-storage/documents/src/inbound/axum_router/task_duplicates.rsnew file mode 100644index 0000000000..ec8ae15275--- /dev/null+++ b/rust/cloud-storage/documents/src/inbound/axum_router/task_duplicates.rs@@ -0,0 +1,195 @@+//! Task duplicate detection endpoints.++use std::sync::Arc;++use axum::{+ Extension, Json,+ extract::{Path, State},+};+use entity_access::domain::models::MemberTeamRole;+use entity_access::domain::ports::EntityAccessService;+use entity_access::inbound::axum_extractors::{+ DocumentAccessExtractor, OptionalMacroUserTeamExtractor,+};+use model::document::DocumentBasic;+use model::response::GenericSuccessResponse;+use model_user::axum_extractor::MacroUserExtractor;+use models_permissions::share_permission::access_level::{OwnerAccessLevel, ViewAccessLevel};+use serde::{Deserialize, Serialize};+use task_dedup::{NewTask, TaskDedupError, TaskDedupService, TaskDuplicate, TaskSimilarityResult};+use uuid::Uuid;++use super::{DocumentRouterState, Params};+use crate::domain::models::DocumentError;+use crate::domain::ports::DocumentService;++/// Response for duplicate task lookup.+#[derive(Debug, Serialize, Deserialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct TaskDuplicatesResponse {+ /// Active duplicate matches for the requested task.+ pub duplicates: Vec<TaskDuplicate>,+}++/// Request body for dismissing duplicate matches.+#[derive(Debug, Serialize, Deserialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct DismissTaskDuplicatesRequest {+ /// Match ids to dismiss.+ pub match_ids: Vec<Uuid>,+}++/// Request body for searching tasks similar to an unsaved draft.+#[derive(Debug, Serialize, Deserialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct TaskSimilaritySearchRequest {+ /// Draft task title.+ pub task_name: String,+ /// Draft task markdown body.+ pub markdown: Option<String>,+ /// Whether the task will be shared with the user's team, which widens the+ /// search scope to team tasks.+ #[serde(default)]+ pub share_with_team: bool,+}++/// Response for searching tasks similar to an unsaved draft.+#[derive(Debug, Serialize, Deserialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct TaskSimilaritySearchResponse {+ /// Existing tasks similar to the draft.+ pub results: Vec<TaskSimilarityResult>,+}++/// Handler for `GET /documents/{document_id}/duplicates`.+#[tracing::instrument(skip(state, _access), err)]+pub async fn get_task_duplicates_handler<T: DocumentService, Svc: EntityAccessService>(+ _access: DocumentAccessExtractor<ViewAccessLevel, Svc>,+ State(state): State<DocumentRouterState<T, Svc>>,+ Path(Params { document_id }): Path<Params>,+) -> Result<Json<TaskDuplicatesResponse>, DocumentError> {+ let duplicates = state+ .task_dedup_service+ .active_duplicates(&document_id)+ .await+ .map_err(task_dedup_error)?;++ Ok(Json(TaskDuplicatesResponse { duplicates }))+}++/// Handler for `POST /documents/similarity_search`.+///+/// Returns existing tasks similar to an unsaved draft. Runs vector retrieval ++/// rerank only and persists nothing.+#[utoipa::path(+ tag = "document",+ post,+ path = "/documents/similarity_search",+ request_body = TaskSimilaritySearchRequest,+ responses(+ (status = 200, body = inline(TaskSimilaritySearchResponse)),+ (status = 401, body = model_error_response::ErrorResponse),+ (status = 500, body = model_error_response::ErrorResponse),+ )+)]+#[tracing::instrument(skip(state, user, optional_team, request), fields(user_id=?user.macro_user_id), err)]+pub async fn task_similarity_search_handler<T: DocumentService, Svc: EntityAccessService>(+ State(state): State<DocumentRouterState<T, Svc>>,+ user: MacroUserExtractor,+ optional_team: OptionalMacroUserTeamExtractor<MemberTeamRole, Svc>,+ Json(request): Json<TaskSimilaritySearchRequest>,+) -> Result<Json<TaskSimilaritySearchResponse>, DocumentError> {+ let team_id = if request.share_with_team {+ optional_team+ .entity_access_receipt+ .map(|team| macro_uuid::string_to_uuid(&team.entity().entity_id).unwrap())+ } else {+ None+ };+ let markdown = request.markdown.unwrap_or_default();++ let results = state+ .task_dedup_service+ .similarity_search(+ user.macro_user_id.as_ref(),+ team_id,+ &request.task_name,+ &markdown,+ )+ .await+ .map_err(task_dedup_error)?;++ Ok(Json(TaskSimilaritySearchResponse { results }))+}++/// Handler for `POST /documents/{document_id}/duplicates/dismiss`.+#[tracing::instrument(skip(state, _access, user), err)]+pub async fn dismiss_task_duplicates_handler<T: DocumentService, Svc: EntityAccessService>(+ _access: DocumentAccessExtractor<ViewAccessLevel, Svc>,+ State(state): State<DocumentRouterState<T, Svc>>,+ user: model_user::axum_extractor::MacroUserExtractor,+ Path(Params { document_id }): Path<Params>,+ Json(request): Json<DismissTaskDuplicatesRequest>,+) -> Result<Json<GenericSuccessResponse>, DocumentError> {+ state+ .task_dedup_service+ .dismiss_matches(+ &document_id,+ &request.match_ids,+ user.macro_user_id.as_ref(),+ )+ .await+ .map_err(task_dedup_error)?;++ Ok(Json(GenericSuccessResponse { success: true }))+}++/// Handler for `POST /documents/{document_id}/duplicates/{match_id}/delete_this`.+#[tracing::instrument(skip(state, access, doc), err)]+pub async fn delete_this_duplicate_task_handler<T: DocumentService, Svc: EntityAccessService>(+ access: DocumentAccessExtractor<OwnerAccessLevel, Svc>,+ State(state): State<DocumentRouterState<T, Svc>>,+ doc: Extension<DocumentBasic>,+ Path((document_id, match_id)): Path<(String, Uuid)>,+) -> Result<Json<GenericSuccessResponse>, DocumentError> {+ state+ .task_dedup_service+ .ensure_match_contains(&document_id, match_id)+ .await+ .map_err(task_dedup_error)?;+ state+ .service+ .delete_document(access.entity_access_receipt, doc.project_id.clone())+ .await?;+ state+ .task_dedup_service+ .dismiss_match_by_id(match_id)+ .await+ .map_err(task_dedup_error)?;++ Ok(Json(GenericSuccessResponse { success: true }))+}++/// Spawn duplicate detection for a newly created task.+pub fn spawn_task_duplicate_detection(task_dedup_service: Arc<TaskDedupService>, task: NewTask) {+ tokio::spawn(async move {+ let _ = task_dedup_service+ .detect_new_task(task)+ .await+ .inspect_err(|error| tracing::error!(error=?error, "task duplicate detection failed"));+ });+}++fn task_dedup_error(error: TaskDedupError) -> DocumentError {+ match error {+ TaskDedupError::MatchNotFound => {+ DocumentError::NotFound("duplicate match not found".to_string())+ }+ TaskDedupError::Storage(error) => DocumentError::Internal(error.into()),+ TaskDedupError::Dependency(error) => DocumentError::Internal(error),+ }+}diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex 32ca73793e..e8a5c33f0d 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -99,6 +99,7 @@ setup_test_envs:echo "DATABASE_URL={{ DATABASE_URL }}" >> ./entity_access_db_utils/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./mcp_client/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./document_storage_service/.env+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./task_dedup/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./crm/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./bots/.envdiff --git a/rust/cloud-storage/macro_db_client/migrations/20260528120000_task_duplicate_detection.sql b/rust/cloud-storage/macro_db_client/migrations/20260528120000_task_duplicate_detection.sqlnew file mode 100644index 0000000000..68662bd1ee--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260528120000_task_duplicate_detection.sql@@ -0,0 +1,46 @@+CREATE EXTENSION IF NOT EXISTS vector;++CREATE TABLE task_duplicate_embedding (+ document_id TEXT PRIMARY KEY REFERENCES "Document"(id) ON DELETE CASCADE,+ model TEXT NOT NULL,+ content TEXT NOT NULL,+ embedding vector(1536) NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);++CREATE INDEX task_duplicate_embedding_vector_idx+ ON task_duplicate_embedding+ USING ivfflat (embedding vector_cosine_ops)+ -- IVFFlat lists should track roughly rows / 1000. lists = 100 is sized+ -- for about 100k task_duplicate_embedding rows; tune this index as task+ -- volume grows and query latency/recall data changes.+ WITH (lists = 100);++CREATE TABLE task_duplicate_match (+ id UUID PRIMARY KEY,+ task_id TEXT NOT NULL REFERENCES "Document"(id) ON DELETE CASCADE,+ duplicate_task_id TEXT NOT NULL REFERENCES "Document"(id) ON DELETE CASCADE,+ status TEXT NOT NULL DEFAULT 'active',+ vector_score DOUBLE PRECISION NOT NULL,+ rerank_score DOUBLE PRECISION NOT NULL,+ judge_model TEXT,+ judge_reason TEXT,+ dismissed_by TEXT,+ dismissed_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ CONSTRAINT task_duplicate_match_order CHECK (task_id < duplicate_task_id),+ CONSTRAINT task_duplicate_match_status CHECK (status IN ('active', 'dismissed'))+);++CREATE UNIQUE INDEX task_duplicate_match_pair_idx+ ON task_duplicate_match(task_id, duplicate_task_id);++CREATE INDEX task_duplicate_match_task_id_idx+ ON task_duplicate_match(task_id)+ WHERE status = 'active';++CREATE INDEX task_duplicate_match_duplicate_task_id_idx+ ON task_duplicate_match(duplicate_task_id)+ WHERE status = 'active';diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-0c2a70e1c21ea156df7ebcfac398759e58dad1a553de9c0bbbb2480f65eadc13.json b/rust/cloud-storage/task_dedup/.sqlx/query-0c2a70e1c21ea156df7ebcfac398759e58dad1a553de9c0bbbb2480f65eadc13.jsonnew file mode 100644index 0000000000..a50b80bf97--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-0c2a70e1c21ea156df7ebcfac398759e58dad1a553de9c0bbbb2480f65eadc13.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH ranked AS (\n SELECT\n id,\n ROW_NUMBER() OVER (\n ORDER BY rerank_score DESC, vector_score DESC, created_at DESC\n ) AS rn\n FROM task_duplicate_match\n WHERE status = 'active'\n AND (task_id = $1 OR duplicate_task_id = $1)\n )\n UPDATE task_duplicate_match m\n SET status = 'dismissed', updated_at = NOW()\n FROM ranked r\n WHERE m.id = r.id\n AND r.rn > $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Int8"+ ]+ },+ "nullable": []+ },+ "hash": "0c2a70e1c21ea156df7ebcfac398759e58dad1a553de9c0bbbb2480f65eadc13"+}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-3a902cc0d2b3a42bedbf844958cf1239aa0a076eae544ec95afd931896039410.json b/rust/cloud-storage/task_dedup/.sqlx/query-3a902cc0d2b3a42bedbf844958cf1239aa0a076eae544ec95afd931896039410.jsonnew file mode 100644index 0000000000..f2b540873e--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-3a902cc0d2b3a42bedbf844958cf1239aa0a076eae544ec95afd931896039410.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"Document\" (id, name, \"fileType\", owner)\n VALUES ($1, $2, 'md', $3)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "3a902cc0d2b3a42bedbf844958cf1239aa0a076eae544ec95afd931896039410"+}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-4b12c2d75c8b90ec6c843ce8e6770c30f06903a19285042b197941acd47a8149.json b/rust/cloud-storage/task_dedup/.sqlx/query-4b12c2d75c8b90ec6c843ce8e6770c30f06903a19285042b197941acd47a8149.jsonnew file mode 100644index 0000000000..a3ad5805fa--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-4b12c2d75c8b90ec6c843ce8e6770c30f06903a19285042b197941acd47a8149.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO task_duplicate_match (\n id,\n task_id,\n duplicate_task_id,\n status,\n vector_score,\n rerank_score,\n judge_model,\n judge_reason\n )\n VALUES ($1, $2, $3, 'active', $4, $5, $6, $7)\n ON CONFLICT (task_id, duplicate_task_id) DO UPDATE\n SET status = 'active',\n vector_score = EXCLUDED.vector_score,\n rerank_score = EXCLUDED.rerank_score,\n judge_model = EXCLUDED.judge_model,\n judge_reason = EXCLUDED.judge_reason,\n updated_at = NOW()\n WHERE task_duplicate_match.status <> 'dismissed'\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Float8",+ "Float8",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "4b12c2d75c8b90ec6c843ce8e6770c30f06903a19285042b197941acd47a8149"+}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-57f8eb3279187d90ab77d297fca263964019aae4d17817dad0715c6e02ba3de2.json b/rust/cloud-storage/task_dedup/.sqlx/query-57f8eb3279187d90ab77d297fca263964019aae4d17817dad0715c6e02ba3de2.jsonnew file mode 100644index 0000000000..def6c7e7bc--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-57f8eb3279187d90ab77d297fca263964019aae4d17817dad0715c6e02ba3de2.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO team_task (team_id, document_id, task_num)\n VALUES ($1, $2, $3)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Int4"+ ]+ },+ "nullable": []+ },+ "hash": "57f8eb3279187d90ab77d297fca263964019aae4d17817dad0715c6e02ba3de2"+}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-5856f5d32b88bea8ae9ddde6b363ebc4e88bab59ef2f14c24069911a0b56b1e3.json b/rust/cloud-storage/task_dedup/.sqlx/query-5856f5d32b88bea8ae9ddde6b363ebc4e88bab59ef2f14c24069911a0b56b1e3.jsonnew file mode 100644index 0000000000..e031341d0a--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-5856f5d32b88bea8ae9ddde6b363ebc4e88bab59ef2f14c24069911a0b56b1e3.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO document_sub_type (document_id, sub_type)\n VALUES ($1, 'task')\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "5856f5d32b88bea8ae9ddde6b363ebc4e88bab59ef2f14c24069911a0b56b1e3"+}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-6a9de1564f16007df9f5758baad9f9d5c22ca624f08f29bed7fe9e265288eba9.json b/rust/cloud-storage/task_dedup/.sqlx/query-6a9de1564f16007df9f5758baad9f9d5c22ca624f08f29bed7fe9e265288eba9.jsonnew file mode 100644index 0000000000..80b721af4a--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-6a9de1564f16007df9f5758baad9f9d5c22ca624f08f29bed7fe9e265288eba9.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE task_duplicate_match\n SET status = 'dismissed',\n dismissed_by = $3,\n dismissed_at = NOW(),\n updated_at = NOW()\n WHERE id = $1\n AND (task_id = $2 OR duplicate_task_id = $2)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "6a9de1564f16007df9f5758baad9f9d5c22ca624f08f29bed7fe9e265288eba9"+}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-6f9c55c52025db2dbe4b76be30d2ca5c95970ef6ad421ec0f5fbe89bea212ff5.json b/rust/cloud-storage/task_dedup/.sqlx/query-6f9c55c52025db2dbe4b76be30d2ca5c95970ef6ad421ec0f5fbe89bea212ff5.jsonnew file mode 100644index 0000000000..0d25c6312d--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-6f9c55c52025db2dbe4b76be30d2ca5c95970ef6ad421ec0f5fbe89bea212ff5.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM task_duplicate_match\n WHERE id = $1\n AND (task_id = $2 OR duplicate_task_id = $2)\n )\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "exists",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "6f9c55c52025db2dbe4b76be30d2ca5c95970ef6ad421ec0f5fbe89bea212ff5"+}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-72db8a2592b5a60ef17fa2842994503ba8506e3b792d40d26cc7c31e750081a8.json b/rust/cloud-storage/task_dedup/.sqlx/query-72db8a2592b5a60ef17fa2842994503ba8506e3b792d40d26cc7c31e750081a8.jsonnew file mode 100644index 0000000000..aa9684ef62--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-72db8a2592b5a60ef17fa2842994503ba8506e3b792d40d26cc7c31e750081a8.json@@ -0,0 +1,52 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n m.id,\n CASE WHEN m.task_id = $1 THEN m.duplicate_task_id ELSE m.task_id END AS \"other_task_id!\",\n d.name AS \"other_task_name!\",\n m.vector_score AS \"vector_score!\",\n m.rerank_score AS \"rerank_score!\",\n m.judge_reason\n FROM task_duplicate_match m\n JOIN \"Document\" d\n ON d.id = CASE WHEN m.task_id = $1 THEN m.duplicate_task_id ELSE m.task_id END\n WHERE m.status = 'active'\n AND (m.task_id = $1 OR m.duplicate_task_id = $1)\n AND d.\"deletedAt\" IS NULL\n ORDER BY m.rerank_score DESC, m.vector_score DESC, m.created_at DESC\n LIMIT 10\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "other_task_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "other_task_name!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "vector_score!",+ "type_info": "Float8"+ },+ {+ "ordinal": 4,+ "name": "rerank_score!",+ "type_info": "Float8"+ },+ {+ "ordinal": 5,+ "name": "judge_reason",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ null,+ false,+ false,+ false,+ true+ ]+ },+ "hash": "72db8a2592b5a60ef17fa2842994503ba8506e3b792d40d26cc7c31e750081a8"+}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-847a84afff39b82082e62f6dc54873b131243152c9e1a3ff9a9d64e8f4b0ed15.json b/rust/cloud-storage/task_dedup/.sqlx/query-847a84afff39b82082e62f6dc54873b131243152c9e1a3ff9a9d64e8f4b0ed15.jsonnew file mode 100644index 0000000000..d798cffca4--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-847a84afff39b82082e62f6dc54873b131243152c9e1a3ff9a9d64e8f4b0ed15.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO task_duplicate_embedding (document_id, model, content, embedding)\n VALUES ($1, $2, $3, $4::text::vector)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "847a84afff39b82082e62f6dc54873b131243152c9e1a3ff9a9d64e8f4b0ed15"+}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-88e5097f74825c09d6477ee3807b21e5814a9e67cd94f9c34a044d26c147f1fe.json b/rust/cloud-storage/task_dedup/.sqlx/query-88e5097f74825c09d6477ee3807b21e5814a9e67cd94f9c34a044d26c147f1fe.jsonnew file mode 100644index 0000000000..c21a7340d1--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-88e5097f74825c09d6477ee3807b21e5814a9e67cd94f9c34a044d26c147f1fe.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE task_duplicate_match\n SET status = 'dismissed', dismissed_by = $2, dismissed_at = NOW(), updated_at = NOW()\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "88e5097f74825c09d6477ee3807b21e5814a9e67cd94f9c34a044d26c147f1fe"+}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-89fac636d8ad3699c72ad57a4a5f2bf9211061274491815b8af4c634e62cee06.json b/rust/cloud-storage/task_dedup/.sqlx/query-89fac636d8ad3699c72ad57a4a5f2bf9211061274491815b8af4c634e62cee06.jsonnew file mode 100644index 0000000000..75964adfc9--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-89fac636d8ad3699c72ad57a4a5f2bf9211061274491815b8af4c634e62cee06.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE task_duplicate_match\n SET status = 'dismissed', updated_at = NOW()\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "89fac636d8ad3699c72ad57a4a5f2bf9211061274491815b8af4c634e62cee06"+}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-ab394ab1dcafaff117ba75dd454c9ef5dc894f2a86012e54c8bd5e085458a89d.json b/rust/cloud-storage/task_dedup/.sqlx/query-ab394ab1dcafaff117ba75dd454c9ef5dc894f2a86012e54c8bd5e085458a89d.jsonnew file mode 100644index 0000000000..b80b95917b--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-ab394ab1dcafaff117ba75dd454c9ef5dc894f2a86012e54c8bd5e085458a89d.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE \"Document\"\n SET \"deletedAt\" = NOW()\n WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "ab394ab1dcafaff117ba75dd454c9ef5dc894f2a86012e54c8bd5e085458a89d"+}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-b1794f52c72781e2f98bcbf955877d6164866e80ac593213de77252333f7d338.json b/rust/cloud-storage/task_dedup/.sqlx/query-b1794f52c72781e2f98bcbf955877d6164866e80ac593213de77252333f7d338.jsonnew file mode 100644index 0000000000..80ba0890a2--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-b1794f52c72781e2f98bcbf955877d6164866e80ac593213de77252333f7d338.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO task_duplicate_match (\n id,\n task_id,\n duplicate_task_id,\n status,\n vector_score,\n rerank_score,\n judge_model,\n judge_reason\n )\n VALUES ($1, $2, $3, 'active', 0.95, $4, 'test', 'same implementation work')\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Float8"+ ]+ },+ "nullable": []+ },+ "hash": "b1794f52c72781e2f98bcbf955877d6164866e80ac593213de77252333f7d338"+}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-c2f61e1119ac4ba2155f472075b5857e086b3ece6e489b6d47a933aea87a02b9.json b/rust/cloud-storage/task_dedup/.sqlx/query-c2f61e1119ac4ba2155f472075b5857e086b3ece6e489b6d47a933aea87a02b9.jsonnew file mode 100644index 0000000000..43b2b133c0--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-c2f61e1119ac4ba2155f472075b5857e086b3ece6e489b6d47a933aea87a02b9.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT task_id, duplicate_task_id\n FROM task_duplicate_match\n WHERE id = $1\n AND (task_id = $2 OR duplicate_task_id = $2)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "task_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "duplicate_task_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "c2f61e1119ac4ba2155f472075b5857e086b3ece6e489b6d47a933aea87a02b9"+}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-f04c859304822b052e31a56628de7ade7c72155fc232cb0ec08b543530d47758.json b/rust/cloud-storage/task_dedup/.sqlx/query-f04c859304822b052e31a56628de7ade7c72155fc232cb0ec08b543530d47758.jsonnew file mode 100644index 0000000000..f8ffdb3e70--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-f04c859304822b052e31a56628de7ade7c72155fc232cb0ec08b543530d47758.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO task_duplicate_embedding (document_id, model, content, embedding)\n VALUES ($1, $2, $3, $4::text::vector)\n ON CONFLICT (document_id) DO UPDATE\n SET model = EXCLUDED.model,\n content = EXCLUDED.content,\n embedding = EXCLUDED.embedding,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "f04c859304822b052e31a56628de7ade7c72155fc232cb0ec08b543530d47758"+}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-f62b5eb569c1751fe1b85a81c1b50811245e71af919de567277e505bb59d62e5.json b/rust/cloud-storage/task_dedup/.sqlx/query-f62b5eb569c1751fe1b85a81c1b50811245e71af919de567277e505bb59d62e5.jsonnew file mode 100644index 0000000000..a5c0451b89--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-f62b5eb569c1751fe1b85a81c1b50811245e71af919de567277e505bb59d62e5.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT task_id, duplicate_task_id\n FROM task_duplicate_match\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "task_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "duplicate_task_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "f62b5eb569c1751fe1b85a81c1b50811245e71af919de567277e505bb59d62e5"+}diff --git a/rust/cloud-storage/task_dedup/.sqlx/query-fed750ca47b0b07b0220ebc66fbc970dbe397c91a94a6b7cae1c93e7e078fca5.json b/rust/cloud-storage/task_dedup/.sqlx/query-fed750ca47b0b07b0220ebc66fbc970dbe397c91a94a6b7cae1c93e7e078fca5.jsonnew file mode 100644index 0000000000..806dd516a2--- /dev/null+++ b/rust/cloud-storage/task_dedup/.sqlx/query-fed750ca47b0b07b0220ebc66fbc970dbe397c91a94a6b7cae1c93e7e078fca5.json@@ -0,0 +1,38 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n e.document_id,\n e.content,\n 1 - (e.embedding <=> $2::text::vector) AS \"vector_score!\"\n FROM task_duplicate_embedding e\n JOIN \"Document\" d ON d.id = e.document_id\n JOIN document_sub_type dst ON dst.document_id = d.id AND dst.sub_type = 'task'\n LEFT JOIN team_task tt ON tt.document_id = d.id\n WHERE e.document_id <> $1\n AND d.\"deletedAt\" IS NULL\n AND (\n d.owner = $3\n OR ($4::uuid IS NOT NULL AND tt.team_id = $4)\n )\n AND NOT EXISTS (\n SELECT 1\n FROM task_duplicate_match m\n WHERE (\n m.task_id = LEAST($1, e.document_id)\n AND m.duplicate_task_id = GREATEST($1, e.document_id)\n AND m.status = 'dismissed'\n )\n )\n ORDER BY e.embedding <=> $2::text::vector\n LIMIT $5\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "document_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "content",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "vector_score!",+ "type_info": "Float8"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Uuid",+ "Int8"+ ]+ },+ "nullable": [+ false,+ false,+ null+ ]+ },+ "hash": "fed750ca47b0b07b0220ebc66fbc970dbe397c91a94a6b7cae1c93e7e078fca5"+}diff --git a/rust/cloud-storage/task_dedup/Cargo.toml b/rust/cloud-storage/task_dedup/Cargo.tomlnew file mode 100644index 0000000000..73c1fd7973--- /dev/null+++ b/rust/cloud-storage/task_dedup/Cargo.toml@@ -0,0 +1,24 @@+[package]+edition = "2024"+name = "task_dedup"+publish = false+version = "0.1.0"++[dependencies]+agent = { path = "../agent" }+anyhow = { workspace = true }+async-trait = { workspace = true }+connection_gateway_client = { path = "../connection_gateway_client" }+model-entity = { path = "../model-entity" }+reqwest = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+sqlx = { workspace = true }+thiserror = { workspace = true }+tracing = { workspace = true }+utoipa = { workspace = true }+uuid = { workspace = true }++[dev-dependencies]+macro_db_migrator = { path = "../macro_db_migrator" }+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }diff --git a/rust/cloud-storage/task_dedup/src/domain/mod.rs b/rust/cloud-storage/task_dedup/src/domain/mod.rsnew file mode 100644index 0000000000..509698651c--- /dev/null+++ b/rust/cloud-storage/task_dedup/src/domain/mod.rs@@ -0,0 +1,5 @@+//! Domain model, ports, and service for task duplicate detection.++pub mod models;+pub mod ports;+pub mod service;diff --git a/rust/cloud-storage/task_dedup/src/domain/models.rs b/rust/cloud-storage/task_dedup/src/domain/models.rsnew file mode 100644index 0000000000..e0e53352b2--- /dev/null+++ b/rust/cloud-storage/task_dedup/src/domain/models.rs@@ -0,0 +1,103 @@+//! Domain models for task duplicate detection.++use serde::{Deserialize, Serialize};+use uuid::Uuid;++/// A newly-created task to index and compare.+#[derive(Debug, Clone)]+pub struct NewTask {+ /// Document id of the created task.+ pub document_id: String,+ /// Owner user id.+ pub owner: String,+ /// Team id when the task is shared with a team.+ pub team_id: Option<Uuid>,+ /// Task title.+ pub title: String,+ /// Task markdown body.+ pub markdown: String,+}++/// A duplicate task candidate shown on the task surface.+#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct TaskDuplicate {+ /// Match row id.+ pub id: Uuid,+ /// The other task in the duplicate pair.+ pub task_id: String,+ /// The other task's display name.+ pub task_name: String,+ /// Cosine similarity from vector search.+ pub vector_score: f64,+ /// Deterministic rerank score.+ pub rerank_score: f64,+ /// LLM judge explanation when available.+ pub judge_reason: Option<String>,+}++/// Candidate returned by the retrieval layer before deterministic rerank and+/// judging.+#[derive(Debug, Clone)]+pub struct TaskDuplicateCandidate {+ /// Candidate task document id.+ pub document_id: String,+ /// Candidate embedding content.+ pub content: String,+ /// Candidate vector similarity.+ pub vector_score: f64,+}++/// A similar existing task computed for an unsaved draft, returned to the task+/// composer without persisting any embedding or match state.+#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct TaskSimilarityResult {+ /// The matching existing task.+ pub task_id: String,+ /// The matching task's display name.+ pub task_name: String,+ /// Cosine similarity from vector search.+ pub vector_score: f64,+ /// Deterministic rerank score.+ pub rerank_score: f64,+}++/// Candidate returned by the similarity-search retrieval layer, carrying the+/// task display name so the composer can render a match without a match row.+#[derive(Debug, Clone)]+pub struct TaskSimilarityCandidate {+ /// Candidate task document id.+ pub document_id: String,+ /// Candidate task display name.+ pub name: String,+ /// Candidate embedding content.+ pub content: String,+ /// Candidate vector similarity.+ pub vector_score: f64,+}++/// Output from a duplicate judge.+#[derive(Debug, Clone)]+pub struct JudgeResult {+ /// Whether the two task descriptions are duplicates.+ pub is_duplicate: bool,+ /// Judge model name, when a remote model was used.+ pub model: Option<String>,+ /// Optional judge explanation.+ pub reason: Option<String>,+}++/// Errors produced by task duplicate detection.+#[derive(Debug, thiserror::Error)]+pub enum TaskDedupError {+ /// A referenced duplicate match was not found.+ #[error("duplicate match not found")]+ MatchNotFound,+ /// Persistence failed.+ #[error(transparent)]+ Storage(#[from] sqlx::Error),+ /// Pipeline dependency failed.+ #[error(transparent)]+ Dependency(#[from] anyhow::Error),+}diff --git a/rust/cloud-storage/task_dedup/src/domain/ports.rs b/rust/cloud-storage/task_dedup/src/domain/ports.rsnew file mode 100644index 0000000000..fb1c41befc--- /dev/null+++ b/rust/cloud-storage/task_dedup/src/domain/ports.rs@@ -0,0 +1,124 @@+//! Ports for the task duplicate detection pipeline.++use async_trait::async_trait;+use uuid::Uuid;++use super::models::{+ JudgeResult, NewTask, TaskDedupError, TaskDuplicate, TaskDuplicateCandidate,+ TaskSimilarityCandidate,+};++/// Embeds task text into a vector representation.+#[async_trait]+pub trait TaskEmbedder: Send + Sync {+ /// Embeds `content`.+ async fn embed(&self, content: &str) -> anyhow::Result<Vec<f32>>;+}++/// Applies a semantic duplicate judgement after retrieval and deterministic+/// reranking.+#[async_trait]+pub trait TaskDuplicateJudge: Send + Sync {+ /// Judges whether `left` and `right` represent the same task.+ async fn judge(&self, left: &str, right: &str, rerank_score: f64) -> JudgeResult;+}++/// Persists embeddings, retrieves candidates, and manages match state.+#[async_trait]+pub trait TaskDedupRepo: Send + Sync {+ /// Upserts the current task embedding.+ async fn upsert_embedding(+ &self,+ document_id: &str,+ model: &str,+ content: &str,+ embedding: &[f32],+ ) -> Result<(), TaskDedupError>;++ /// Retrieves vector candidates for a task.+ async fn candidates(+ &self,+ task: &NewTask,+ embedding: &[f32],+ limit: i64,+ ) -> Result<Vec<TaskDuplicateCandidate>, TaskDedupError>;++ /// Retrieves vector candidates for an unsaved task scoped to `owner` and an+ /// optional `team_id`, without any self- or dismissed-match exclusion.+ async fn similarity_candidates(+ &self,+ owner: &str,+ team_id: Option<Uuid>,+ embedding: &[f32],+ limit: i64,+ ) -> Result<Vec<TaskSimilarityCandidate>, TaskDedupError>;++ /// Upserts an active duplicate match.+ async fn upsert_match(+ &self,+ task_id: &str,+ duplicate_task_id: &str,+ vector_score: f64,+ rerank_score: f64,+ judge_model: Option<&str>,+ judge_reason: Option<&str>,+ ) -> Result<(), TaskDedupError>;++ /// Returns all active documents connected to any seed document through+ /// active duplicate matches.+ async fn active_duplicate_component(+ &self,+ document_ids: &[String],+ ) -> Result<Vec<String>, TaskDedupError>;++ /// Trims active matches for `document_id`.+ async fn trim_matches(&self, document_id: &str, limit: i64) -> Result<(), TaskDedupError>;++ /// Lists active duplicate matches for `document_id`.+ async fn active_duplicates(+ &self,+ document_id: &str,+ ) -> Result<Vec<TaskDuplicate>, TaskDedupError>;++ /// Dismisses a match visible from `document_id`.+ async fn dismiss_match(+ &self,+ document_id: &str,+ match_id: Uuid,+ dismissed_by: &str,+ ) -> Result<bool, TaskDedupError>;++ /// Returns whether a match contains `document_id`.+ async fn match_contains(+ &self,+ document_id: &str,+ match_id: Uuid,+ ) -> Result<bool, TaskDedupError>;++ /// Returns the other task id in a match.+ async fn other_task_id(+ &self,+ document_id: &str,+ match_id: Uuid,+ ) -> Result<Option<String>, TaskDedupError>;++ /// Returns the task document ids in a match.+ async fn match_document_ids(&self, match_id: Uuid) -> Result<Vec<String>, TaskDedupError>;++ /// Dismisses a match without document-side filtering.+ async fn dismiss_match_by_id(&self, match_id: Uuid) -> Result<(), TaskDedupError>;++ /// Marks a match dismissed by a user.+ async fn dismiss_match_by_id_for_user(+ &self,+ match_id: Uuid,+ dismissed_by: &str,+ ) -> Result<(), TaskDedupError>;+}++/// Sends live updates for documents whose duplicate state changed.+#[async_trait]+pub trait TaskDedupNotifier: Send + Sync {+ /// Notifies that duplicate matches changed for `document_id`.+ async fn notify_matches_updated(&self, document_id: &str) -> anyhow::Result<()>;+}diff --git a/rust/cloud-storage/task_dedup/src/domain/service.rs b/rust/cloud-storage/task_dedup/src/domain/service.rsnew file mode 100644index 0000000000..d9c2966d4f--- /dev/null+++ b/rust/cloud-storage/task_dedup/src/domain/service.rs@@ -0,0 +1,471 @@+//! Domain service for task duplicate detection.++use std::collections::{HashMap, HashSet};+use std::sync::Arc;++use uuid::Uuid;++use super::models::{NewTask, TaskDedupError, TaskDuplicate, TaskSimilarityResult};+use super::ports::{TaskDedupNotifier, TaskDedupRepo, TaskDuplicateJudge, TaskEmbedder};++/// Configuration for the task duplicate detection pipeline.+#[derive(Debug, Clone)]+pub struct TaskDedupConfig {+ /// Embedding model identifier persisted with embedding rows.+ pub embedding_model: String,+ /// Maximum vector candidates to retrieve.+ pub vector_candidate_limit: i64,+ /// Maximum active duplicate matches to keep per task.+ pub duplicate_limit: i64,+ /// Minimum vector score before reranking.+ pub min_vector_similarity: f64,+ /// Minimum deterministic rerank score before judging.+ pub min_rerank_score: f64,+}++impl Default for TaskDedupConfig {+ fn default() -> Self {+ Self {+ embedding_model: "text-embedding-3-small".to_string(),+ vector_candidate_limit: 24,+ duplicate_limit: 5,+ min_vector_similarity: 0.74,+ min_rerank_score: 0.42,+ }+ }+}++/// Task duplicate detection service.+#[derive(Clone)]+pub struct TaskDedupService {+ config: TaskDedupConfig,+ repo: Arc<dyn TaskDedupRepo>,+ embedder: Arc<dyn TaskEmbedder>,+ judge: Arc<dyn TaskDuplicateJudge>,+ notifier: Arc<dyn TaskDedupNotifier>,+}++impl TaskDedupService {+ /// Creates a new service from its ports.+ pub fn new(+ config: TaskDedupConfig,+ repo: Arc<dyn TaskDedupRepo>,+ embedder: Arc<dyn TaskEmbedder>,+ judge: Arc<dyn TaskDuplicateJudge>,+ notifier: Arc<dyn TaskDedupNotifier>,+ ) -> Self {+ Self {+ config,+ repo,+ embedder,+ judge,+ notifier,+ }+ }++ /// Lists active duplicate matches for a document.+ pub async fn active_duplicates(+ &self,+ document_id: &str,+ ) -> Result<Vec<TaskDuplicate>, TaskDedupError> {+ self.repo.active_duplicates(document_id).await+ }++ /// Dismisses a visible match.+ pub async fn dismiss_match(+ &self,+ document_id: &str,+ match_id: Uuid,+ dismissed_by: &str,+ ) -> Result<(), TaskDedupError> {+ let affected_document_ids = self.match_document_ids(match_id).await?;+ let dismissed = self+ .repo+ .dismiss_match(document_id, match_id, dismissed_by)+ .await?;+ if dismissed {+ self.notify_documents(affected_document_ids).await;+ Ok(())+ } else {+ Err(TaskDedupError::MatchNotFound)+ }+ }++ /// Dismisses visible matches.+ pub async fn dismiss_matches(+ &self,+ document_id: &str,+ match_ids: &[Uuid],+ dismissed_by: &str,+ ) -> Result<(), TaskDedupError> {+ let unique_match_ids = match_ids.iter().copied().collect::<HashSet<_>>();+ if unique_match_ids.is_empty() {+ return Ok(());+ }++ let mut affected_document_ids = HashSet::new();+ for match_id in &unique_match_ids {+ if !self.repo.match_contains(document_id, *match_id).await? {+ return Err(TaskDedupError::MatchNotFound);+ }+ affected_document_ids.extend(self.match_document_ids(*match_id).await?);+ }++ for match_id in unique_match_ids {+ let dismissed = self+ .repo+ .dismiss_match(document_id, match_id, dismissed_by)+ .await?;+ if !dismissed {+ return Err(TaskDedupError::MatchNotFound);+ }+ }++ self.notify_documents(affected_document_ids).await;+ Ok(())+ }++ /// Ensures a match contains the given document.+ pub async fn ensure_match_contains(+ &self,+ document_id: &str,+ match_id: Uuid,+ ) -> Result<(), TaskDedupError> {+ if self.repo.match_contains(document_id, match_id).await? {+ Ok(())+ } else {+ Err(TaskDedupError::MatchNotFound)+ }+ }++ /// Returns the other task in a duplicate match.+ pub async fn other_task_id(+ &self,+ document_id: &str,+ match_id: Uuid,+ ) -> Result<String, TaskDedupError> {+ self.repo+ .other_task_id(document_id, match_id)+ .await?+ .ok_or(TaskDedupError::MatchNotFound)+ }++ /// Dismisses a match by id.+ pub async fn dismiss_match_by_id(&self, match_id: Uuid) -> Result<(), TaskDedupError> {+ let affected_document_ids = self.match_document_ids(match_id).await?;+ self.repo.dismiss_match_by_id(match_id).await?;+ self.notify_documents(affected_document_ids).await;+ Ok(())+ }++ /// Marks a match dismissed by a user.+ pub async fn dismiss_match_by_id_for_user(+ &self,+ match_id: Uuid,+ dismissed_by: &str,+ ) -> Result<(), TaskDedupError> {+ let affected_document_ids = self.match_document_ids(match_id).await?;+ self.repo+ .dismiss_match_by_id_for_user(match_id, dismissed_by)+ .await?;+ self.notify_documents(affected_document_ids).await;+ Ok(())+ }++ /// Finds existing tasks similar to an unsaved draft as the user composes it.+ ///+ /// Runs vector retrieval + deterministic rerank only (no judge) and+ /// persists nothing: the embedding is computed in memory and discarded.+ pub async fn similarity_search(+ &self,+ owner: &str,+ team_id: Option<Uuid>,+ title: &str,+ markdown: &str,+ ) -> Result<Vec<TaskSimilarityResult>, TaskDedupError> {+ let content = task_embedding_content(title, markdown);+ let embedding = self.embedder.embed(&content).await?;++ let candidates = self+ .repo+ .similarity_candidates(+ owner,+ team_id,+ &embedding,+ self.config.vector_candidate_limit,+ )+ .await?;++ let mut results = Vec::new();+ for candidate in candidates {+ if candidate.vector_score < self.config.min_vector_similarity {+ continue;+ }++ let rerank_score = lexical_rerank_score(&content, &candidate.content);+ if rerank_score < self.config.min_rerank_score {+ continue;+ }++ results.push(TaskSimilarityResult {+ task_id: candidate.document_id,+ task_name: candidate.name,+ vector_score: candidate.vector_score,+ rerank_score,+ });+ }++ results.sort_by(|a, b| {+ b.rerank_score+ .partial_cmp(&a.rerank_score)+ .unwrap_or(std::cmp::Ordering::Equal)+ .then_with(|| {+ b.vector_score+ .partial_cmp(&a.vector_score)+ .unwrap_or(std::cmp::Ordering::Equal)+ })+ });+ results.truncate(self.config.duplicate_limit.max(0) as usize);++ Ok(results)+ }++ /// Detects duplicates for a newly-created task and sends live updates for+ /// documents that now have active matches.+ pub async fn detect_new_task(&self, task: NewTask) -> Result<Vec<String>, TaskDedupError> {+ let content = task_embedding_content(&task.title, &task.markdown);+ let embedding = self.embedder.embed(&content).await?;+ let mut changed_document_ids = HashSet::new();++ self.repo+ .upsert_embedding(+ &task.document_id,+ &self.config.embedding_model,+ &content,+ &embedding,+ )+ .await?;++ let candidates = self+ .repo+ .candidates(&task, &embedding, self.config.vector_candidate_limit)+ .await?;++ for candidate in candidates {+ if candidate.vector_score < self.config.min_vector_similarity {+ continue;+ }++ let rerank_score = lexical_rerank_score(&content, &candidate.content);+ if rerank_score < self.config.min_rerank_score {+ continue;+ }++ let judge = self+ .judge+ .judge(&content, &candidate.content, rerank_score)+ .await;+ if !judge.is_duplicate {+ continue;+ }++ let (task_id, duplicate_task_id) =+ ordered_pair(&task.document_id, &candidate.document_id);+ let component = self+ .duplicate_component([task_id.to_string(), duplicate_task_id.to_string()])+ .await?;+ let reason = inferred_judge_reason(judge.reason.as_deref());+ for (left, right) in complete_graph_pairs(&component) {+ self.repo+ .upsert_match(+ left,+ right,+ candidate.vector_score,+ rerank_score,+ judge.model.as_deref(),+ Some(&reason),+ )+ .await?;++ changed_document_ids.insert(left.to_string());+ changed_document_ids.insert(right.to_string());+ }+ }++ for changed_document_id in &changed_document_ids {+ self.repo+ .trim_matches(changed_document_id, self.config.duplicate_limit)+ .await?;+ }++ let mut active_document_ids = Vec::new();+ for changed_document_id in changed_document_ids {+ if !self+ .repo+ .active_duplicates(&changed_document_id)+ .await?+ .is_empty()+ {+ active_document_ids.push(changed_document_id);+ }+ }++ self.notify_documents(active_document_ids.clone()).await;+ Ok(active_document_ids)+ }++ async fn notify_documents<I>(&self, document_ids: I)+ where+ I: IntoIterator<Item = String>,+ {+ for document_id in document_ids {+ if let Err(error) = self.notifier.notify_matches_updated(&document_id).await {+ tracing::error!(+ error=?error,+ document_id,+ "failed to send task duplicate live update"+ );+ }+ }+ }++ async fn match_document_ids(&self, match_id: Uuid) -> Result<Vec<String>, TaskDedupError> {+ let document_ids = self.repo.match_document_ids(match_id).await?;+ if document_ids.is_empty() {+ Err(TaskDedupError::MatchNotFound)+ } else {+ Ok(document_ids)+ }+ }++ async fn duplicate_component<I>(&self, document_ids: I) -> Result<Vec<String>, TaskDedupError>+ where+ I: IntoIterator<Item = String>,+ {+ let seeds = document_ids.into_iter().collect::<HashSet<_>>();+ let seed_list = seeds.iter().cloned().collect::<Vec<_>>();+ let mut component = self+ .repo+ .active_duplicate_component(&seed_list)+ .await?+ .into_iter()+ .collect::<HashSet<_>>();+ component.extend(seeds);++ let mut component = component.into_iter().collect::<Vec<_>>();+ component.sort();+ Ok(component)+ }+}++/// Builds the text embedded for a task.+pub fn task_embedding_content(title: &str, markdown: &str) -> String {+ format!("Title: {}\n\n{}", title.trim(), markdown.trim())+}++/// Returns a stable ordered pair.+pub fn ordered_pair<'a>(a: &'a str, b: &'a str) -> (&'a str, &'a str) {+ if a < b { (a, b) } else { (b, a) }+}++fn complete_graph_pairs(document_ids: &[String]) -> Vec<(&str, &str)> {+ let mut pairs = Vec::new();+ for (index, left) in document_ids.iter().enumerate() {+ for right in document_ids.iter().skip(index + 1) {+ pairs.push(ordered_pair(left.as_str(), right.as_str()));+ }+ }+ pairs+}++fn inferred_judge_reason(reason: Option<&str>) -> String {+ match reason {+ Some(reason) if !reason.trim().is_empty() => {+ format!("duplicate graph closure: {}", reason.trim())+ }+ _ => "duplicate graph closure".to_string(),+ }+}++/// Deterministic lexical rerank score.+pub fn lexical_rerank_score(left: &str, right: &str) -> f64 {+ let left_tokens = tokenize(left);+ let right_tokens = tokenize(right);+ if left_tokens.is_empty() || right_tokens.is_empty() {+ return 0.0;+ }++ let left_counts = token_counts(&left_tokens);+ let right_counts = token_counts(&right_tokens);+ let left_set: HashSet<&str> = left_tokens.iter().map(String::as_str).collect();+ let right_set: HashSet<&str> = right_tokens.iter().map(String::as_str).collect();++ let overlap = left_set.intersection(&right_set).count() as f64;+ let union = left_set.union(&right_set).count() as f64;+ let jaccard = if union > 0.0 { overlap / union } else { 0.0 };++ let mut dot = 0.0;+ for (token, left_count) in &left_counts {+ if let Some(right_count) = right_counts.get(token) {+ dot += f64::from(*left_count) * f64::from(*right_count);+ }+ }+ let left_norm = left_counts+ .values()+ .map(|count| f64::from(*count) * f64::from(*count))+ .sum::<f64>()+ .sqrt();+ let right_norm = right_counts+ .values()+ .map(|count| f64::from(*count) * f64::from(*count))+ .sum::<f64>()+ .sqrt();+ let cosine = if left_norm > 0.0 && right_norm > 0.0 {+ dot / (left_norm * right_norm)+ } else {+ 0.0+ };++ (jaccard * 0.35) + (cosine * 0.65)+}++fn token_counts(tokens: &[String]) -> HashMap<&str, u16> {+ let mut counts = HashMap::new();+ for token in tokens {+ *counts.entry(token.as_str()).or_insert(0) += 1;+ }+ counts+}++fn tokenize(text: &str) -> Vec<String> {+ text.split(|ch: char| !ch.is_alphanumeric())+ .map(str::to_lowercase)+ .filter(|token| token.len() > 2 && !STOP_WORDS.contains(&token.as_str()))+ .collect()+}++const STOP_WORDS: &[&str] = &[+ "the", "and", "for", "with", "that", "this", "from", "into", "task", "todo", "make", "add",+ "fix", "use", "using", "should", "would", "could", "will", "are", "was", "were", "has", "have",+ "had", "you", "your", "our", "not", "but", "all", "any", "can",+];++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn lexical_rerank_separates_similar_and_unrelated_tasks() {+ let similar = lexical_rerank_score(+ "Use pgvector embeddings to detect duplicate tasks and show a duplicates pill",+ "Detect duplicate tasks with pgvector embeddings and show duplicate suggestions",+ );+ let unrelated = lexical_rerank_score(+ "Use pgvector embeddings to detect duplicate tasks and show a duplicates pill",+ "Fix billing email copy and update subscription receipt text",+ );++ assert!(similar > TaskDedupConfig::default().min_rerank_score);+ assert!(unrelated < TaskDedupConfig::default().min_rerank_score);+ }+}diff --git a/rust/cloud-storage/task_dedup/src/lib.rs b/rust/cloud-storage/task_dedup/src/lib.rsnew file mode 100644index 0000000000..6f7a66f912--- /dev/null+++ b/rust/cloud-storage/task_dedup/src/lib.rs@@ -0,0 +1,15 @@+#![deny(missing_docs)]+//! Task duplicate detection.+//!+//! The crate keeps the duplicate-detection workflow behind domain ports so the+//! embedding model, candidate retrieval, judge, persistence repo, and live+//! update transport can be swapped independently.++pub mod domain;+pub mod outbound;++pub use domain::models::{+ JudgeResult, NewTask, TaskDedupError, TaskDuplicate, TaskDuplicateCandidate,+ TaskSimilarityResult,+};+pub use domain::service::{TaskDedupConfig, TaskDedupService};diff --git a/rust/cloud-storage/task_dedup/src/outbound/connection_gateway.rs b/rust/cloud-storage/task_dedup/src/outbound/connection_gateway.rsnew file mode 100644index 0000000000..1cef356990--- /dev/null+++ b/rust/cloud-storage/task_dedup/src/outbound/connection_gateway.rs@@ -0,0 +1,50 @@+//! Connection-gateway live-update adapter.++use std::sync::Arc;++use async_trait::async_trait;+use connection_gateway_client::client::ConnectionGatewayClient;+use model_entity::EntityType;+use serde_json::json;++use crate::domain::ports::TaskDedupNotifier;++const TASK_DUPLICATE_MATCHES_UPDATED_MESSAGE_TYPE: &str = "task_duplicate_matches_updated";++/// Notifier that sends document-scoped live updates through connection gateway.+pub struct ConnectionGatewayTaskDedupNotifier {+ client: Arc<ConnectionGatewayClient>,+}++impl ConnectionGatewayTaskDedupNotifier {+ /// Creates a connection-gateway notifier.+ pub fn new(client: Arc<ConnectionGatewayClient>) -> Self {+ Self { client }+ }+}++#[async_trait]+impl TaskDedupNotifier for ConnectionGatewayTaskDedupNotifier {+ async fn notify_matches_updated(&self, document_id: &str) -> anyhow::Result<()> {+ let payload = json!({ "documentId": document_id });+ let entity = EntityType::Document.with_entity_str(document_id);+ self.client+ .send_message(+ entity,+ TASK_DUPLICATE_MATCHES_UPDATED_MESSAGE_TYPE.to_string(),+ payload,+ )+ .await?;+ Ok(())+ }+}++/// No-op notifier.+pub struct NoopTaskDedupNotifier;++#[async_trait]+impl TaskDedupNotifier for NoopTaskDedupNotifier {+ async fn notify_matches_updated(&self, _document_id: &str) -> anyhow::Result<()> {+ Ok(())+ }+}diff --git a/rust/cloud-storage/task_dedup/src/outbound/embedding.rs b/rust/cloud-storage/task_dedup/src/outbound/embedding.rsnew file mode 100644index 0000000000..61395d6190--- /dev/null+++ b/rust/cloud-storage/task_dedup/src/outbound/embedding.rs@@ -0,0 +1,126 @@+//! Embedding adapters for task duplicate detection.++use async_trait::async_trait;+use serde_json::json;++use crate::domain::ports::TaskEmbedder;++/// Expected embedding dimensions for the current default embedding model.+pub const EMBEDDING_DIM: usize = 1536;++/// Embedder that uses OpenAI when `OPENAI_API_KEY` is set and falls back to a+/// deterministic local embedding otherwise.+pub struct OpenAiOrLocalTaskEmbedder {+ model: String,+ client: reqwest::Client,+}++impl OpenAiOrLocalTaskEmbedder {+ /// Creates a new embedder.+ pub fn new(model: impl Into<String>) -> Self {+ Self {+ model: model.into(),+ client: reqwest::Client::new(),+ }+ }+}++#[async_trait]+impl TaskEmbedder for OpenAiOrLocalTaskEmbedder {+ async fn embed(&self, content: &str) -> anyhow::Result<Vec<f32>> {+ let Ok(api_key) = std::env::var("OPENAI_API_KEY") else {+ return Ok(local_embedding(content));+ };++ if api_key.trim().is_empty() {+ return Ok(local_embedding(content));+ }++ let response = self+ .client+ .post("https://api.openai.com/v1/embeddings")+ .bearer_auth(api_key)+ .json(&json!({+ "model": self.model,+ "input": content,+ }))+ .send()+ .await;++ let response = match response.and_then(reqwest::Response::error_for_status) {+ Err(error) => {+ tracing::warn!(error=?error, "OpenAI embedding failed; using local task embedding");+ return Ok(local_embedding(content));+ }+ Ok(response) => response,+ };++ let response: serde_json::Value = match response.json().await {+ Ok(response) => response,+ Err(error) => {+ tracing::warn!(error=?error, "OpenAI embedding JSON failed; using local task embedding");+ return Ok(local_embedding(content));+ }+ };++ let embedding = response["data"][0]["embedding"]+ .as_array()+ .ok_or_else(|| anyhow::anyhow!("OpenAI embedding response missing data[0].embedding"))?+ .iter()+ .map(|value| {+ value+ .as_f64()+ .map(|number| number as f32)+ .ok_or_else(|| anyhow::anyhow!("OpenAI embedding value was not a number"))+ })+ .collect::<anyhow::Result<Vec<_>>>()?;++ anyhow::ensure!(+ embedding.len() == EMBEDDING_DIM,+ "expected {EMBEDDING_DIM} embedding dimensions, got {}",+ embedding.len()+ );++ Ok(embedding)+ }+}++/// Deterministic local embedder for tests and offline development.+pub struct LocalTaskEmbedder;++#[async_trait]+impl TaskEmbedder for LocalTaskEmbedder {+ async fn embed(&self, content: &str) -> anyhow::Result<Vec<f32>> {+ Ok(local_embedding(content))+ }+}++/// Deterministic local embedding used for tests and API fallback.+pub fn local_embedding(text: &str) -> Vec<f32> {+ let mut vector = vec![0.0_f32; EMBEDDING_DIM];+ for token in text+ .split(|ch: char| !ch.is_alphanumeric())+ .map(str::to_lowercase)+ .filter(|token| token.len() > 2)+ {+ let mut hash = 1469598103934665603_u64;+ for byte in token.as_bytes() {+ hash ^= u64::from(*byte);+ hash = hash.wrapping_mul(1099511628211);+ }+ let idx = (hash as usize) % EMBEDDING_DIM;+ let sign = if hash & 1 == 0 { 1.0 } else { -1.0 };+ vector[idx] += sign;+ }++ let norm = vector+ .iter()+ .map(|value| value * value)+ .sum::<f32>()+ .sqrt()+ .max(1.0);+ for value in &mut vector {+ *value /= norm;+ }+ vector+}diff --git a/rust/cloud-storage/task_dedup/src/outbound/judge.rs b/rust/cloud-storage/task_dedup/src/outbound/judge.rsnew file mode 100644index 0000000000..311f88f673--- /dev/null+++ b/rust/cloud-storage/task_dedup/src/outbound/judge.rs@@ -0,0 +1,131 @@+//! Duplicate judge adapters.++use agent::structured_output::{DynamicSchema, dynamic_structured_completion};+use agent::{AgentModel, Message};+use async_trait::async_trait;+use serde::{Deserialize, Serialize};+use serde_json::json;++use crate::domain::models::JudgeResult;+use crate::domain::ports::TaskDuplicateJudge;++/// Judge that uses the agent structured completion path and falls back to+/// deterministic rerank thresholds otherwise.+pub struct AgentDuplicateJudge {+ fallback_threshold: f64,+ model: AgentModel,+}++#[derive(Debug, Deserialize, Serialize)]+struct DuplicateJudgeOutput {+ is_duplicate: bool,+ reason: String,+}++impl AgentDuplicateJudge {+ /// Creates a new judge.+ pub fn new(fallback_threshold: f64) -> Self {+ Self {+ fallback_threshold,+ model: AgentModel::Fast,+ }+ }++ /// Creates a new judge with an explicit agent model.+ pub fn with_model(fallback_threshold: f64, model: AgentModel) -> Self {+ Self {+ fallback_threshold,+ model,+ }+ }++ fn fallback(&self, rerank_score: f64, model: Option<String>, reason: &str) -> JudgeResult {+ JudgeResult {+ is_duplicate: rerank_score >= self.fallback_threshold,+ model,+ reason: Some(reason.to_string()),+ }+ }+}++#[async_trait]+impl TaskDuplicateJudge for AgentDuplicateJudge {+ async fn judge(&self, left: &str, right: &str, rerank_score: f64) -> JudgeResult {+ let model_name = self.model.to_string();+ let prompt =+ format!("Task A:\n{left}\n\nTask B:\n{right}\n\nRerank score: {rerank_score:.3}");+ let schema = DynamicSchema {+ name: "TaskDuplicateJudgeOutput".to_string(),+ description: Some(+ "Judgement for whether two task descriptions represent the same work.".to_string(),+ ),+ schema: json!({+ "type": "object",+ "additionalProperties": false,+ "required": ["is_duplicate", "reason"],+ "properties": {+ "is_duplicate": {+ "type": "boolean",+ "description": "True only if completing one task would substantially complete the other."+ },+ "reason": {+ "type": "string",+ "description": "A concise reason for the judgement."+ }+ }+ }),+ };++ let value = dynamic_structured_completion(+ self.model,+ "You judge duplicate software/product tasks. Two tasks are duplicates only when completing one would substantially complete the other. Return false for merely related work, shared projects, or same feature area with different deliverables.",+ vec![Message::user(prompt)],+ schema,+ )+ .await;++ let Ok(value) = value else {+ return self.fallback(+ rerank_score,+ Some(model_name),+ "judge request failed; local rerank fallback",+ );+ };++ match serde_json::from_value::<DuplicateJudgeOutput>(value) {+ Ok(parsed) => JudgeResult {+ is_duplicate: parsed.is_duplicate,+ model: Some(model_name),+ reason: Some(parsed.reason),+ },+ Err(_) => self.fallback(+ rerank_score,+ Some(model_name),+ "judge JSON parse failed; local rerank fallback",+ ),+ }+ }+}++/// Local judge for tests.+pub struct LocalDuplicateJudge {+ threshold: f64,+}++impl LocalDuplicateJudge {+ /// Creates a local threshold judge.+ pub fn new(threshold: f64) -> Self {+ Self { threshold }+ }+}++#[async_trait]+impl TaskDuplicateJudge for LocalDuplicateJudge {+ async fn judge(&self, _left: &str, _right: &str, rerank_score: f64) -> JudgeResult {+ JudgeResult {+ is_duplicate: rerank_score >= self.threshold,+ model: None,+ reason: Some("local rerank fallback".to_string()),+ }+ }+}diff --git a/rust/cloud-storage/task_dedup/src/outbound/mod.rs b/rust/cloud-storage/task_dedup/src/outbound/mod.rsnew file mode 100644index 0000000000..33c2ad9363--- /dev/null+++ b/rust/cloud-storage/task_dedup/src/outbound/mod.rs@@ -0,0 +1,6 @@+//! Outbound adapters for task duplicate detection.++pub mod connection_gateway;+pub mod embedding;+pub mod judge;+pub mod postgres;diff --git a/rust/cloud-storage/task_dedup/src/outbound/postgres.rs b/rust/cloud-storage/task_dedup/src/outbound/postgres.rsnew file mode 100644index 0000000000..93550a9adf--- /dev/null+++ b/rust/cloud-storage/task_dedup/src/outbound/postgres.rs@@ -0,0 +1,777 @@+//! Postgres task duplicate repo.++use async_trait::async_trait;+use sqlx::PgPool;+use uuid::Uuid;++use crate::domain::models::{+ NewTask, TaskDedupError, TaskDuplicate, TaskDuplicateCandidate, TaskSimilarityCandidate,+};+use crate::domain::ports::TaskDedupRepo;+use crate::domain::service::ordered_pair;++/// Postgres-backed task duplicate repo using pgvector.+#[derive(Clone)]+pub struct PgTaskDedupRepo {+ pool: PgPool,+}++impl PgTaskDedupRepo {+ /// Creates a Postgres repo.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++#[async_trait]+impl TaskDedupRepo for PgTaskDedupRepo {+ async fn upsert_embedding(+ &self,+ document_id: &str,+ model: &str,+ content: &str,+ embedding: &[f32],+ ) -> Result<(), TaskDedupError> {+ let embedding_sql = vector_sql_literal(embedding);+ sqlx::query!(+ r#"+ INSERT INTO task_duplicate_embedding (document_id, model, content, embedding)+ VALUES ($1, $2, $3, $4::text::vector)+ ON CONFLICT (document_id) DO UPDATE+ SET model = EXCLUDED.model,+ content = EXCLUDED.content,+ embedding = EXCLUDED.embedding,+ updated_at = NOW()+ "#,+ document_id,+ model,+ content,+ embedding_sql,+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ async fn candidates(+ &self,+ task: &NewTask,+ embedding: &[f32],+ limit: i64,+ ) -> Result<Vec<TaskDuplicateCandidate>, TaskDedupError> {+ let embedding_sql = vector_sql_literal(embedding);+ let rows = sqlx::query!(+ r#"+ SELECT+ e.document_id,+ e.content,+ 1 - (e.embedding <=> $2::text::vector) AS "vector_score!"+ FROM task_duplicate_embedding e+ JOIN "Document" d ON d.id = e.document_id+ JOIN document_sub_type dst ON dst.document_id = d.id AND dst.sub_type = 'task'+ LEFT JOIN team_task tt ON tt.document_id = d.id+ WHERE e.document_id <> $1+ AND d."deletedAt" IS NULL+ AND (+ d.owner = $3+ OR ($4::uuid IS NOT NULL AND tt.team_id = $4)+ )+ AND NOT EXISTS (+ SELECT 1+ FROM task_duplicate_match m+ WHERE (+ m.task_id = LEAST($1, e.document_id)+ AND m.duplicate_task_id = GREATEST($1, e.document_id)+ AND m.status = 'dismissed'+ )+ )+ ORDER BY e.embedding <=> $2::text::vector+ LIMIT $5+ "#,+ task.document_id.as_str(),+ embedding_sql,+ task.owner.as_str(),+ task.team_id,+ limit,+ )+ .fetch_all(&self.pool)+ .await?;++ Ok(rows+ .into_iter()+ .map(|row| TaskDuplicateCandidate {+ document_id: row.document_id,+ content: row.content,+ vector_score: row.vector_score,+ })+ .collect())+ }++ async fn similarity_candidates(+ &self,+ owner: &str,+ team_id: Option<Uuid>,+ embedding: &[f32],+ limit: i64,+ ) -> Result<Vec<TaskSimilarityCandidate>, TaskDedupError> {+ let embedding_sql = vector_sql_literal(embedding);+ let rows = sqlx::query!(+ r#"+ SELECT+ e.document_id,+ d.name AS "name!",+ e.content,+ 1 - (e.embedding <=> $3::text::vector) AS "vector_score!"+ FROM task_duplicate_embedding e+ JOIN "Document" d ON d.id = e.document_id+ JOIN document_sub_type dst ON dst.document_id = d.id AND dst.sub_type = 'task'+ LEFT JOIN team_task tt ON tt.document_id = d.id+ WHERE d."deletedAt" IS NULL+ AND (+ d.owner = $1+ OR ($2::uuid IS NOT NULL AND tt.team_id = $2)+ )+ ORDER BY e.embedding <=> $3::text::vector+ LIMIT $4+ "#,+ owner,+ team_id,+ embedding_sql,+ limit,+ )+ .fetch_all(&self.pool)+ .await?;++ Ok(rows+ .into_iter()+ .map(|row| TaskSimilarityCandidate {+ document_id: row.document_id,+ name: row.name,+ content: row.content,+ vector_score: row.vector_score,+ })+ .collect())+ }++ async fn upsert_match(+ &self,+ task_id: &str,+ duplicate_task_id: &str,+ vector_score: f64,+ rerank_score: f64,+ judge_model: Option<&str>,+ judge_reason: Option<&str>,+ ) -> Result<(), TaskDedupError> {+ let (task_id, duplicate_task_id) = ordered_pair(task_id, duplicate_task_id);+ sqlx::query!(+ r#"+ INSERT INTO task_duplicate_match (+ id,+ task_id,+ duplicate_task_id,+ status,+ vector_score,+ rerank_score,+ judge_model,+ judge_reason+ )+ VALUES ($1, $2, $3, 'active', $4, $5, $6, $7)+ ON CONFLICT (task_id, duplicate_task_id) DO UPDATE+ SET status = 'active',+ vector_score = EXCLUDED.vector_score,+ rerank_score = EXCLUDED.rerank_score,+ judge_model = EXCLUDED.judge_model,+ judge_reason = EXCLUDED.judge_reason,+ updated_at = NOW()+ WHERE task_duplicate_match.status <> 'dismissed'+ "#,+ Uuid::new_v4(),+ task_id,+ duplicate_task_id,+ vector_score,+ rerank_score,+ judge_model,+ judge_reason,+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ async fn active_duplicate_component(+ &self,+ document_ids: &[String],+ ) -> Result<Vec<String>, TaskDedupError> {+ let rows = sqlx::query!(+ r#"+ WITH RECURSIVE edges(left_id, right_id) AS (+ SELECT m.task_id, m.duplicate_task_id+ FROM task_duplicate_match m+ JOIN "Document" left_document ON left_document.id = m.task_id+ JOIN "Document" right_document ON right_document.id = m.duplicate_task_id+ WHERE m.status = 'active'+ AND left_document."deletedAt" IS NULL+ AND right_document."deletedAt" IS NULL+ ),+ component(document_id) AS (+ SELECT DISTINCT unnest($1::text[])+ UNION+ SELECT CASE+ WHEN edges.left_id = component.document_id THEN edges.right_id+ ELSE edges.left_id+ END+ FROM edges+ JOIN component+ ON component.document_id = edges.left_id+ OR component.document_id = edges.right_id+ )+ SELECT DISTINCT document_id AS "document_id!"+ FROM component+ "#,+ document_ids,+ )+ .fetch_all(&self.pool)+ .await?;++ Ok(rows.into_iter().map(|row| row.document_id).collect())+ }++ async fn trim_matches(&self, document_id: &str, limit: i64) -> Result<(), TaskDedupError> {+ sqlx::query!(+ r#"+ WITH ranked AS (+ SELECT+ id,+ ROW_NUMBER() OVER (+ ORDER BY rerank_score DESC, vector_score DESC, created_at DESC+ ) AS rn+ FROM task_duplicate_match+ WHERE status = 'active'+ AND (task_id = $1 OR duplicate_task_id = $1)+ )+ UPDATE task_duplicate_match m+ SET status = 'dismissed', updated_at = NOW()+ FROM ranked r+ WHERE m.id = r.id+ AND r.rn > $2+ "#,+ document_id,+ limit,+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ async fn active_duplicates(+ &self,+ document_id: &str,+ ) -> Result<Vec<TaskDuplicate>, TaskDedupError> {+ let rows = sqlx::query!(+ r#"+ SELECT+ m.id,+ CASE WHEN m.task_id = $1 THEN m.duplicate_task_id ELSE m.task_id END AS "other_task_id!",+ d.name AS "other_task_name!",+ m.vector_score AS "vector_score!",+ m.rerank_score AS "rerank_score!",+ m.judge_reason+ FROM task_duplicate_match m+ JOIN "Document" d+ ON d.id = CASE WHEN m.task_id = $1 THEN m.duplicate_task_id ELSE m.task_id END+ WHERE m.status = 'active'+ AND (m.task_id = $1 OR m.duplicate_task_id = $1)+ AND d."deletedAt" IS NULL+ ORDER BY m.rerank_score DESC, m.vector_score DESC, m.created_at DESC+ LIMIT 10+ "#,+ document_id,+ )+ .fetch_all(&self.pool)+ .await?;++ Ok(rows+ .into_iter()+ .map(|row| TaskDuplicate {+ id: row.id,+ task_id: row.other_task_id,+ task_name: row.other_task_name,+ vector_score: row.vector_score,+ rerank_score: row.rerank_score,+ judge_reason: row.judge_reason,+ })+ .collect())+ }++ async fn dismiss_match(+ &self,+ document_id: &str,+ match_id: Uuid,+ dismissed_by: &str,+ ) -> Result<bool, TaskDedupError> {+ let rows = sqlx::query!(+ r#"+ UPDATE task_duplicate_match+ SET status = 'dismissed',+ dismissed_by = $3,+ dismissed_at = NOW(),+ updated_at = NOW()+ WHERE id = $1+ AND (task_id = $2 OR duplicate_task_id = $2)+ "#,+ match_id,+ document_id,+ dismissed_by,+ )+ .execute(&self.pool)+ .await?+ .rows_affected();++ Ok(rows > 0)+ }++ async fn match_contains(+ &self,+ document_id: &str,+ match_id: Uuid,+ ) -> Result<bool, TaskDedupError> {+ let exists = sqlx::query_scalar!(+ r#"+ SELECT EXISTS (+ SELECT 1+ FROM task_duplicate_match+ WHERE id = $1+ AND (task_id = $2 OR duplicate_task_id = $2)+ )+ "#,+ match_id,+ document_id,+ )+ .fetch_one(&self.pool)+ .await?;++ Ok(exists.unwrap_or(false))+ }++ async fn other_task_id(+ &self,+ document_id: &str,+ match_id: Uuid,+ ) -> Result<Option<String>, TaskDedupError> {+ let row = sqlx::query!(+ r#"+ SELECT task_id, duplicate_task_id+ FROM task_duplicate_match+ WHERE id = $1+ AND (task_id = $2 OR duplicate_task_id = $2)+ "#,+ match_id,+ document_id,+ )+ .fetch_optional(&self.pool)+ .await?;++ Ok(row.map(|row| {+ if row.task_id == document_id {+ row.duplicate_task_id+ } else {+ row.task_id+ }+ }))+ }++ async fn match_document_ids(&self, match_id: Uuid) -> Result<Vec<String>, TaskDedupError> {+ let row = sqlx::query!(+ r#"+ SELECT task_id, duplicate_task_id+ FROM task_duplicate_match+ WHERE id = $1+ "#,+ match_id,+ )+ .fetch_optional(&self.pool)+ .await?;++ Ok(row+ .map(|row| vec![row.task_id, row.duplicate_task_id])+ .unwrap_or_default())+ }++ async fn dismiss_match_by_id(&self, match_id: Uuid) -> Result<(), TaskDedupError> {+ sqlx::query!(+ r#"+ UPDATE task_duplicate_match+ SET status = 'dismissed', updated_at = NOW()+ WHERE id = $1+ "#,+ match_id,+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ async fn dismiss_match_by_id_for_user(+ &self,+ match_id: Uuid,+ dismissed_by: &str,+ ) -> Result<(), TaskDedupError> {+ sqlx::query!(+ r#"+ UPDATE task_duplicate_match+ SET status = 'dismissed', dismissed_by = $2, dismissed_at = NOW(), updated_at = NOW()+ WHERE id = $1+ "#,+ match_id,+ dismissed_by,+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }+}++/// Converts an embedding vector into a pgvector literal.+pub fn vector_sql_literal(embedding: &[f32]) -> String {+ let values = embedding+ .iter()+ .map(|value| format!("{value:.8}"))+ .collect::<Vec<_>>()+ .join(",");+ format!("[{values}]")+}++#[cfg(test)]+mod tests {+ use std::sync::Arc;++ use macro_db_migrator::MACRO_DB_MIGRATIONS;+ use sqlx::PgPool;++ use super::*;+ use crate::domain::ports::TaskDedupNotifier;+ use crate::domain::service::{TaskDedupConfig, TaskDedupService, task_embedding_content};+ use crate::outbound::embedding::{LocalTaskEmbedder, local_embedding};+ use crate::outbound::judge::LocalDuplicateJudge;++ const OWNER: &str = "macro|[email protected]";+ const TEAM_ID: Uuid = uuid::uuid!("a0000000-0000-0000-0000-000000000001");+ const TASK_ONE: &str = "d1000000-0000-0000-0000-000000000001";+ const TASK_TWO: &str = "d1000000-0000-0000-0000-000000000002";+ const TASK_THREE: &str = "d1000000-0000-0000-0000-000000000003";++ struct NoopNotifier;++ #[async_trait::async_trait]+ impl TaskDedupNotifier for NoopNotifier {+ async fn notify_matches_updated(&self, _document_id: &str) -> anyhow::Result<()> {+ Ok(())+ }+ }++ fn service(pool: PgPool) -> TaskDedupService {+ let config = TaskDedupConfig::default();+ TaskDedupService::new(+ config.clone(),+ Arc::new(PgTaskDedupRepo::new(pool)),+ Arc::new(LocalTaskEmbedder),+ Arc::new(LocalDuplicateJudge::new(0.56)),+ Arc::new(NoopNotifier),+ )+ }++ async fn insert_task(pool: &PgPool, id: &str, name: &str, owner: &str) {+ sqlx::query!(+ r#"+ INSERT INTO "Document" (id, name, "fileType", owner)+ VALUES ($1, $2, 'md', $3)+ "#,+ id,+ name,+ owner,+ )+ .execute(pool)+ .await+ .unwrap();++ sqlx::query!(+ r#"+ INSERT INTO document_sub_type (document_id, sub_type)+ VALUES ($1, 'task')+ "#,+ id,+ )+ .execute(pool)+ .await+ .unwrap();+ }++ async fn insert_team_task(pool: &PgPool, document_id: &str, task_num: i32) {+ sqlx::query!(+ r#"+ INSERT INTO team_task (team_id, document_id, task_num)+ VALUES ($1, $2, $3)+ "#,+ TEAM_ID,+ document_id,+ task_num,+ )+ .execute(pool)+ .await+ .unwrap();+ }++ async fn insert_embedding(pool: &PgPool, document_id: &str, content: &str) {+ let embedding = vector_sql_literal(&local_embedding(content));+ sqlx::query!(+ r#"+ INSERT INTO task_duplicate_embedding (document_id, model, content, embedding)+ VALUES ($1, $2, $3, $4::text::vector)+ "#,+ document_id,+ "text-embedding-3-small",+ content,+ embedding,+ )+ .execute(pool)+ .await+ .unwrap();+ }++ async fn insert_match(+ pool: &PgPool,+ task_id: &str,+ duplicate_task_id: &str,+ rerank_score: f64,+ ) -> Uuid {+ let id = Uuid::new_v4();+ let (task_id, duplicate_task_id) =+ crate::domain::service::ordered_pair(task_id, duplicate_task_id);+ sqlx::query!(+ r#"+ INSERT INTO task_duplicate_match (+ id,+ task_id,+ duplicate_task_id,+ status,+ vector_score,+ rerank_score,+ judge_model,+ judge_reason+ )+ VALUES ($1, $2, $3, 'active', 0.95, $4, 'test', 'same implementation work')+ "#,+ id,+ task_id,+ duplicate_task_id,+ rerank_score,+ )+ .execute(pool)+ .await+ .unwrap();+ id+ }++ async fn setup_tasks(pool: &PgPool) {+ insert_task(pool, TASK_ONE, "Add duplicate task detection", OWNER).await;+ insert_task(pool, TASK_TWO, "Detect duplicate tasks", OWNER).await;+ insert_task(pool, TASK_THREE, "Fix unrelated billing copy", OWNER).await;+ insert_team_task(pool, TASK_ONE, 1).await;+ insert_team_task(pool, TASK_TWO, 2).await;+ insert_team_task(pool, TASK_THREE, 3).await;+ }++ #[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../documents/fixtures", scripts("documents_test_data"))+ )]+ async fn lists_active_duplicates_for_either_side_of_pair(pool: PgPool) {+ setup_tasks(&pool).await;+ let match_id = insert_match(&pool, TASK_TWO, TASK_ONE, 0.88).await;+ let service = service(pool.clone());++ let duplicates = service.active_duplicates(TASK_ONE).await.unwrap();+ assert_eq!(duplicates.len(), 1);+ assert_eq!(duplicates[0].id, match_id);+ assert_eq!(duplicates[0].task_id, TASK_TWO);+ assert_eq!(duplicates[0].task_name, "Detect duplicate tasks");+ assert_eq!(+ duplicates[0].judge_reason.as_deref(),+ Some("same implementation work")+ );++ let duplicates = service.active_duplicates(TASK_TWO).await.unwrap();+ assert_eq!(duplicates.len(), 1);+ assert_eq!(duplicates[0].task_id, TASK_ONE);+ }++ #[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../documents/fixtures", scripts("documents_test_data"))+ )]+ async fn dismissed_matches_are_hidden(pool: PgPool) {+ setup_tasks(&pool).await;+ let match_id = insert_match(&pool, TASK_ONE, TASK_TWO, 0.88).await;+ let service = service(pool.clone());++ service+ .dismiss_match(TASK_ONE, match_id, OWNER)+ .await+ .unwrap();++ let duplicates = service.active_duplicates(TASK_ONE).await.unwrap();+ assert!(duplicates.is_empty());+ }++ #[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../documents/fixtures", scripts("documents_test_data"))+ )]+ async fn deleted_duplicate_tasks_are_hidden(pool: PgPool) {+ setup_tasks(&pool).await;+ insert_match(&pool, TASK_ONE, TASK_TWO, 0.88).await;+ let service = service(pool.clone());++ sqlx::query!(+ r#"+ UPDATE "Document"+ SET "deletedAt" = NOW()+ WHERE id = $1+ "#,+ TASK_TWO,+ )+ .execute(&pool)+ .await+ .unwrap();++ let duplicates = service.active_duplicates(TASK_ONE).await.unwrap();+ assert!(duplicates.is_empty());+ }++ #[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../documents/fixtures", scripts("documents_test_data"))+ )]+ async fn detection_inserts_match_for_similar_existing_task(pool: PgPool) {+ setup_tasks(&pool).await;++ let existing = task_embedding_content(+ "Add duplicate task detection",+ "Use pgvector embeddings to find duplicate task descriptions and show a duplicates pill.",+ );+ insert_embedding(&pool, TASK_TWO, &existing).await;++ let service = service(pool.clone());+ service+ .detect_new_task(NewTask {+ document_id: TASK_ONE.to_string(),+ owner: OWNER.to_string(),+ team_id: Some(TEAM_ID),+ title: "Add duplicate task detection".to_string(),+ markdown:+ "Use pgvector embeddings to find duplicate task descriptions and show a duplicates pill."+ .to_string(),+ })+ .await+ .unwrap();++ let duplicates = service.active_duplicates(TASK_ONE).await.unwrap();+ assert_eq!(duplicates.len(), 1);+ assert_eq!(duplicates[0].task_id, TASK_TWO);+ }++ #[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../documents/fixtures", scripts("documents_test_data"))+ )]+ async fn detection_closes_existing_duplicate_component(pool: PgPool) {+ setup_tasks(&pool).await;+ insert_match(&pool, TASK_TWO, TASK_THREE, 0.88).await;++ let existing = task_embedding_content(+ "Add duplicate task detection",+ "Use pgvector embeddings to find duplicate task descriptions and show a duplicates pill.",+ );+ insert_embedding(&pool, TASK_TWO, &existing).await;++ let service = service(pool.clone());+ service+ .detect_new_task(NewTask {+ document_id: TASK_ONE.to_string(),+ owner: OWNER.to_string(),+ team_id: Some(TEAM_ID),+ title: "Add duplicate task detection".to_string(),+ markdown:+ "Use pgvector embeddings to find duplicate task descriptions and show a duplicates pill."+ .to_string(),+ })+ .await+ .unwrap();++ let mut duplicate_ids = service+ .active_duplicates(TASK_ONE)+ .await+ .unwrap()+ .into_iter()+ .map(|duplicate| duplicate.task_id)+ .collect::<Vec<_>>();+ duplicate_ids.sort();++ assert_eq!(duplicate_ids, vec![TASK_TWO, TASK_THREE]);+ }++ #[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../documents/fixtures", scripts("documents_test_data"))+ )]+ async fn similarity_search_returns_similar_without_persisting(pool: PgPool) {+ setup_tasks(&pool).await;++ let similar = task_embedding_content(+ "Add duplicate task detection",+ "Use pgvector embeddings to find duplicate task descriptions and show a duplicates pill.",+ );+ insert_embedding(&pool, TASK_TWO, &similar).await;+ insert_embedding(+ &pool,+ TASK_THREE,+ &task_embedding_content(+ "Fix unrelated billing copy",+ "Update subscription receipt text.",+ ),+ )+ .await;++ let service = service(pool.clone());+ let results = service+ .similarity_search(+ OWNER,+ Some(TEAM_ID),+ "Add duplicate task detection",+ "Use pgvector embeddings to find duplicate task descriptions and show a duplicates pill.",+ )+ .await+ .unwrap();++ // Only the similar task is surfaced; the unrelated one is filtered out.+ assert_eq!(results.len(), 1);+ assert_eq!(results[0].task_id, TASK_TWO);+ assert_eq!(results[0].task_name, "Detect duplicate tasks");++ // Nothing was persisted for the unsaved task: no extra embedding rows+ // (only the two we seeded) and no match rows at all.+ let embedding_count =+ sqlx::query_scalar!(r#"SELECT COUNT(*) AS "count!" FROM task_duplicate_embedding"#)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(embedding_count, 2);++ let match_count =+ sqlx::query_scalar!(r#"SELECT COUNT(*) AS "count!" FROM task_duplicate_match"#)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(match_count, 0);+ }+}