Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix: task dedup mentions (#4009)

Eric Hayes0efbbcb341ba
diff --git a/js/app/packages/queries/storage/task-duplicates.ts b/js/app/packages/queries/storage/task-duplicates.ts
index f23deee3bb..f93c455aee 100644
--- a/js/app/packages/queries/storage/task-duplicates.ts
+++ b/js/app/packages/queries/storage/task-duplicates.ts
@@ -1,3 +1,4 @@
+import { markdownToEmbeddingText } from '@lexical-core/utils/parsers';
import { queryClient } from '@queries/client';
import {
storageServiceClient,
@@ -79,7 +80,10 @@ async function searchSimilarTasks(
): Promise<TaskSimilarityResult[]> {
const result = await storageServiceClient.searchSimilarTasks({
taskName: input.title,
- markdown: input.markdown,
+ // The backend embeds this text as-is, so reduce mention tags to the
+ // compact embedding format up front rather than round-tripping through
+ // lexical-service on a latency-sensitive as-you-type search.
+ markdown: markdownToEmbeddingText(input.markdown),
shareWithTeam: input.shareWithTeam,
});
if (result.isErr()) {
diff --git a/js/lexical-core/tests/mentions.test.ts b/js/lexical-core/tests/mentions.test.ts
index 869b9c1024..b73120179c 100644
--- a/js/lexical-core/tests/mentions.test.ts
+++ b/js/lexical-core/tests/mentions.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import {
+ markdownToEmbeddingText,
markdownToPlainText,
parseContactMentions,
parseDateMentions,
@@ -190,3 +191,127 @@ describe('markdownToPlainText', () => {
expect(markdownToPlainText('')).toBe('');
});
});
+
+describe('markdownToEmbeddingText', () => {
+ it('keeps document and channel ids from document mentions', () => {
+ const input =
+ 'Crash reported in <m-document-mention>{"documentId":"0195ceb6-ec2e-7023-80e4-6e084fa6cccd","blockName":"channel","documentName":"bug-reports","blockParams":{"channel_message_id":"019eb797-0ac1-7062-88ff-5202d1c81724"},"collapsed":false}</m-document-mention>';
+ expect(markdownToEmbeddingText(input)).toBe(
+ 'Crash reported in [bug-reports](channel:0195ceb6-ec2e-7023-80e4-6e084fa6cccd#019eb797-0ac1-7062-88ff-5202d1c81724)'
+ );
+ });
+
+ it('omits the fragment when there is no channel message id', () => {
+ const input =
+ '<m-document-mention>{"documentId":"doc-1","blockName":"md","documentName":"Report","blockParams":{}}</m-document-mention>';
+ expect(markdownToEmbeddingText(input)).toBe('[Report](md:doc-1)');
+ });
+
+ it('falls back to the document name without a document id', () => {
+ const input =
+ '<m-document-mention>{"documentName":"Report"}</m-document-mention>';
+ expect(markdownToEmbeddingText(input)).toBe('Report');
+ });
+
+ it('keeps ids from document cards', () => {
+ const input =
+ '<m-document-card>{"documentId":"doc-2","blockName":"md","documentName":"Spec","blockParams":{}}</m-document-card>';
+ expect(markdownToEmbeddingText(input)).toBe('[Spec](md:doc-2)');
+ });
+
+ it('keeps link urls', () => {
+ const input =
+ 'See <m-link>{"url":"https://example.com","text":"this link"}</m-link>.';
+ expect(markdownToEmbeddingText(input)).toBe(
+ 'See [this link](https://example.com).'
+ );
+ });
+
+ it('reduces other mentions like markdownToPlainText', () => {
+ const input =
+ 'Hello <m-user-mention>{"email":"[email protected]"}</m-user-mention> and ' +
+ '<m-group-mention>{"groupAlias":"here"}</m-group-mention>, due ' +
+ '<m-date-mention>{"displayFormat":"Friday"}</m-date-mention>.';
+ expect(markdownToEmbeddingText(input)).toBe(
+ 'Hello [email protected] and @here, due Friday.'
+ );
+ });
+
+ it('reduces contact and theme mentions to their names', () => {
+ const input =
+ 'Ping <m-contact-mention>{"contactId":"c1","name":"Ness Chu","emailOrDomain":"[email protected]","isCompany":false}</m-contact-mention> re ' +
+ '<m-theme-mention>{"name":"onboarding","data":{}}</m-theme-mention>';
+ expect(markdownToEmbeddingText(input)).toBe('Ping Ness Chu re onboarding');
+ });
+
+ it('keeps ids from snapshots', () => {
+ const input =
+ '<m-snapshot>{"documentId":"doc-3","documentName":"Spec","blockName":"md","content":"ignored","snapshotDate":"2025-01-01"}</m-snapshot>';
+ expect(markdownToEmbeddingText(input)).toBe('[Spec](md:doc-3)');
+ });
+
+ it('decodes base64 snapshots', () => {
+ const payload = btoa(
+ '{"documentId":"doc-3","documentName":"Spec","blockName":"md"}'
+ );
+ expect(
+ markdownToEmbeddingText(`<m-snapshot>${payload}</m-snapshot>`)
+ ).toBe('[Spec](md:doc-3)');
+ });
+
+ it('keeps stable ids for dss images and urls for videos', () => {
+ const input =
+ '<m-image>{"url":"https://signed.example.com/x?sig=abc","alt":"crash screenshot","srcType":"dss","id":"img-1"}</m-image> ' +
+ '<m-video>{"url":"https://videos.example.com/v1","srcType":"embed"}</m-video>';
+ expect(markdownToEmbeddingText(input)).toBe(
+ '[crash screenshot](dss:img-1) [video](https://videos.example.com/v1)'
+ );
+ });
+
+ it('keeps equation sources and await placeholder text', () => {
+ const input =
+ '<m-katex-equation>{"equation":"E = mc^2","inline":true}</m-katex-equation> ' +
+ '<m-await>{"awaitId":"a1","text":"generating...","inline":true}</m-await>';
+ expect(markdownToEmbeddingText(input)).toBe('E = mc^2 generating...');
+ });
+
+ it('flattens tables and resolves mentions inside cells', () => {
+ const input =
+ '<m-table>' +
+ '<m-table-row><m-table-cell>Owner</m-table-cell><m-table-cell>Task</m-table-cell></m-table-row>' +
+ '<m-table-row><m-table-cell><m-user-mention>{"email":"[email protected]"}</m-user-mention></m-table-cell><m-table-cell>fix\\nbug</m-table-cell></m-table-row>' +
+ '</m-table>';
+ expect(markdownToEmbeddingText(input)).toBe(
+ 'Owner | Task\[email protected] | fix bug'
+ );
+ });
+
+ it('unwraps email thread embeds and resolves mentions inside them', () => {
+ const input =
+ '<m-email-thread-embed>{"tag":"div","classes":["macro_quote"]}From <m-contact-mention>{"name":"Ness Chu"}</m-contact-mention>:\\nplease fix</m-email-thread-embed>';
+ expect(markdownToEmbeddingText(input)).toBe(
+ 'From Ness Chu:\nplease fix'
+ );
+ });
+
+ it('drops watermarks and unrecognized m-* tags entirely', () => {
+ const input =
+ 'before <m-watermark>{"content":"made with macro"}</m-watermark>' +
+ '<m-future-thing>{"some":"payload"}</m-future-thing> after';
+ expect(markdownToEmbeddingText(input)).toBe('before after');
+ });
+
+ it('drops tags with unparseable payloads', () => {
+ expect(
+ markdownToEmbeddingText(
+ 'x <m-document-mention>not json</m-document-mention> y'
+ )
+ ).toBe('x y');
+ });
+
+ it('returns original text when no mentions present', () => {
+ expect(markdownToEmbeddingText('Just plain text.')).toBe(
+ 'Just plain text.'
+ );
+ });
+});
diff --git a/js/lexical-core/utils/mentions.ts b/js/lexical-core/utils/mentions.ts
index fde16869c9..e0e3c47ab4 100644
--- a/js/lexical-core/utils/mentions.ts
+++ b/js/lexical-core/utils/mentions.ts
@@ -82,6 +82,7 @@ export function buildMentionMarkdownString(info: MentionInfo): string {
}
export {
+ markdownToEmbeddingText,
markdownToPlainText,
parseContactMentions,
parseDateMentions,
diff --git a/js/lexical-core/utils/parsers.ts b/js/lexical-core/utils/parsers.ts
index ed9427379d..441d995041 100644
--- a/js/lexical-core/utils/parsers.ts
+++ b/js/lexical-core/utils/parsers.ts
@@ -129,3 +129,165 @@ export function markdownToPlainText(markdown: string): string {
)
);
}
+
+/**
+ * The payload fields `markdownToEmbeddingText` reads across the internal
+ * format's `<m-*>` JSON tags. Each tag uses a small subset of these.
+ */
+type MentionTagPayload = {
+ documentId?: string;
+ documentName?: string;
+ blockName?: string;
+ blockParams?: { channel_message_id?: string };
+ url?: string;
+ text?: string;
+ alt?: string;
+ id?: string;
+ srcType?: string;
+ email?: string;
+ name?: string;
+ emailOrDomain?: string;
+ displayFormat?: string;
+ groupAlias?: string;
+ equation?: string;
+};
+
+/**
+ * Replaces every `<{tag}>{json}</{tag}>` occurrence with `render(payload)`.
+ * Unparseable payloads are dropped rather than left in place.
+ */
+function replaceJsonTag(
+ text: string,
+ tag: string,
+ render: (data: MentionTagPayload) => string
+): string {
+ return text.replace(
+ new RegExp(`<${tag}>(.*?)</${tag}>`, 'gs'),
+ (_, json) => {
+ try {
+ return render(JSON.parse(json));
+ } catch {
+ return '';
+ }
+ }
+ );
+}
+
+function documentRefToEmbeddingText(data: MentionTagPayload): string {
+ const name = data.documentName || '';
+ if (!data.documentId) return name;
+ const blockName = data.blockName || 'document';
+ const channelMessageId = data.blockParams?.channel_message_id;
+ const suffix = channelMessageId ? `#${channelMessageId}` : '';
+ return `[${name}](${blockName}:${data.documentId}${suffix})`;
+}
+
+/** Snapshot payloads may be base64-encoded (or raw JSON for backward compat). */
+function snapshotToEmbeddingText(encoded: string): string {
+ try {
+ const json = encoded.startsWith('{')
+ ? encoded
+ : new TextDecoder().decode(
+ Uint8Array.from(atob(encoded), (c) => c.charCodeAt(0))
+ );
+ return documentRefToEmbeddingText(JSON.parse(json));
+ } catch {
+ return '';
+ }
+}
+
+/**
+ * Flattens `<m-table>` markup into plain rows: one line per row, cells joined
+ * with ` | `. Cell payloads are markdown with newlines escaped as literal
+ * `\n`; any tags nested in cells are handled by the leaf passes afterwards.
+ */
+function flattenTables(text: string): string {
+ return text.replace(/<m-table>(.*?)<\/m-table>/gs, (_, table: string) =>
+ [...table.matchAll(/<m-table-row>(.*?)<\/m-table-row>/gs)]
+ .map((row) =>
+ [...row[1].matchAll(/<m-table-cell>(.*?)<\/m-table-cell>/gs)]
+ .map((cell) =>
+ cell[1].replace(/\\n/g, ' ').replaceAll('<br>', ' ').trim()
+ )
+ .join(' | ')
+ )
+ .join('\n')
+ );
+}
+
+/**
+ * Unwraps `<m-email-thread-embed>` blocks: the payload is a JSON metadata
+ * object immediately followed by the quoted thread's markdown with newlines
+ * escaped as literal `\n`.
+ */
+function flattenEmailThreadEmbeds(text: string): string {
+ return text.replace(
+ /<m-email-thread-embed>(.*?)<\/m-email-thread-embed>/gs,
+ (_, embed: string) => embed.replace(/^\{.*?\}/, '').replace(/\\n/g, '\n')
+ );
+}
+
+/**
+ * Converts internal markdown to compact, embedding-friendly text for task
+ * dedup. Every internal-format `<m-*>` tag is reduced to the identity that
+ * distinguishes it, dropping the JSON boilerplate that is the same in every
+ * tag:
+ * - Document mentions/cards/snapshots: `[documentName](blockName:documentId)`,
+ * with `#channel_message_id` appended when the mention targets a channel
+ * message
+ * - Links: `[text](url)`; videos: `[video](url)`; images: `[alt](dss:id|url)`
+ * - User mentions: email; contacts: name; dates: display format;
+ * groups: `@alias`; themes: name; equations: the source expression;
+ * awaits: placeholder text
+ * - Tables and email-thread embeds are flattened to their inner text
+ * - Watermarks and unrecognized `m-*` tags are dropped entirely
+ *
+ * This is the format the task dedup backend embeds: the task composer sends it
+ * directly to the similarity-search endpoint, and lexical-service produces it
+ * for stored tasks via the markdown endpoint's `embedding` target. Both sides
+ * must agree, so any change here changes what new embeddings look like and
+ * may warrant re-running the task embedding backfill.
+ */
+export function markdownToEmbeddingText(markdown: string): string {
+ // Containers first: their payloads nest further tags that the leaf passes
+ // below pick up.
+ let text = markdown.replace(
+ /<m-snapshot>(.*?)<\/m-snapshot>/gs,
+ (_, encoded) => snapshotToEmbeddingText(encoded)
+ );
+ text = flattenTables(text);
+ text = flattenEmailThreadEmbeds(text);
+
+ // Leaf tags.
+ text = replaceJsonTag(text, 'm-document-mention', documentRefToEmbeddingText);
+ text = replaceJsonTag(text, 'm-document-card', documentRefToEmbeddingText);
+ text = replaceJsonTag(text, 'm-link', (data) =>
+ data.url ? `[${data.text || data.url}](${data.url})` : data.text || ''
+ );
+ text = replaceJsonTag(text, 'm-image', (data) => {
+ // dss images get a stable id; urls elsewhere may be transient.
+ const target =
+ data.srcType === 'dss' && data.id ? `dss:${data.id}` : data.url;
+ return target ? `[${data.alt || 'image'}](${target})` : data.alt || '';
+ });
+ text = replaceJsonTag(text, 'm-video', (data) =>
+ data.url ? `[video](${data.url})` : ''
+ );
+ text = replaceJsonTag(text, 'm-katex-equation', (data) => data.equation || '');
+ text = replaceJsonTag(text, 'm-user-mention', (data) => data.email || '');
+ text = replaceJsonTag(
+ text,
+ 'm-contact-mention',
+ (data) => data.name || data.emailOrDomain || ''
+ );
+ text = replaceJsonTag(text, 'm-date-mention', (data) => data.displayFormat || '');
+ text = replaceJsonTag(text, 'm-group-mention', (data) => `@${data.groupAlias || ''}`);
+ text = replaceJsonTag(text, 'm-theme-mention', (data) => data.name || '');
+ text = replaceJsonTag(text, 'm-await', (data) => data.text || '');
+ text = replaceJsonTag(text, 'm-watermark', () => '');
+
+ // Anything still tagged is an unrecognized m-* node: drop it entirely so
+ // its payload cannot leak boilerplate into the embedding (the string
+ // analogue of the UNKNOWN_MENTION fallback transformer).
+ return text.replace(/<(m-[a-zA-Z0-9_-]+)>(.*?)<\/\1>/gs, '');
+}
diff --git a/js/lexical-service/src/endpoints/markdown.ts b/js/lexical-service/src/endpoints/markdown.ts
index 6c1ce81beb..f7181ec523 100644
--- a/js/lexical-service/src/endpoints/markdown.ts
+++ b/js/lexical-service/src/endpoints/markdown.ts
@@ -19,7 +19,10 @@ export class MarkdownEndpoint extends OpenAPIRoute {
request: {
params: docIdParam,
query: z.object({
- target: z.enum(['internal', 'external']).optional().default('internal'),
+ target: z
+ .enum(['internal', 'external', 'embedding'])
+ .optional()
+ .default('internal'),
}),
},
responses: {
diff --git a/js/lexical-service/src/lib/convsersions.ts b/js/lexical-service/src/lib/convsersions.ts
index 7703d50b7e..836458d2c5 100644
--- a/js/lexical-service/src/lib/convsersions.ts
+++ b/js/lexical-service/src/lib/convsersions.ts
@@ -6,6 +6,7 @@ import {
EXTERNAL_TRANSFORMERS,
type ImageNode,
INTERNAL_TRANSFORMERS,
+ markdownToEmbeddingText,
} from '@macro-inc/lexical-core';
import { $getRoot, $isElementNode, type SerializedEditorState } from 'lexical';
import type { CognitionNode, NewMdNode, SearchableNode } from '../types';
@@ -143,18 +144,25 @@ export function toCognitionV2(raw: SerializedEditorState): NewMdNode[] {
}
}
+export type MarkdownTarget = 'internal' | 'external' | 'embedding';
+
export function toMarkdownText(
raw: SerializedEditorState,
- target: 'internal' | 'external' = 'internal'
+ target: MarkdownTarget = 'internal'
) {
const editor = createEditor();
try {
const parsed = editor.parseEditorState(raw);
editor.setEditorState(parsed);
return editor.read(() => {
- return $convertToMarkdownString(
- target === 'internal' ? INTERNAL_TRANSFORMERS : EXTERNAL_TRANSFORMERS
+ const markdown = $convertToMarkdownString(
+ target === 'external' ? EXTERNAL_TRANSFORMERS : INTERNAL_TRANSFORMERS
);
+ // The embedding target is the internal format with mentions reduced to
+ // the compact representation task dedup embeds.
+ return target === 'embedding'
+ ? markdownToEmbeddingText(markdown)
+ : markdown;
});
} catch (error) {
if (error instanceof Error) {
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index d5317010ef..34c9ba31b2 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -685,6 +685,7 @@ async fn main() -> anyhow::Result<()> {
access_service: entity_access_service.clone(),
pool: db.clone(),
task_dedup_service,
+ lexical_client: lexical_client.clone(),
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.toml
index 0e8fa53c74..1d5cb41557 100644
--- a/rust/cloud-storage/documents/Cargo.toml
+++ b/rust/cloud-storage/documents/Cargo.toml
@@ -31,6 +31,7 @@ ai_tools = [
axum = [
"dep:axum",
"dep:axum-extra",
+ "dep:lexical_client",
"dep:model-error-response",
"dep:model_user",
"dep:task_dedup",
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router.rs b/rust/cloud-storage/documents/src/inbound/axum_router.rs
index 5cfe43912c..db5e231080 100644
--- a/rust/cloud-storage/documents/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/documents/src/inbound/axum_router.rs
@@ -45,6 +45,7 @@ use axum::{
response::IntoResponse,
};
use entity_access::domain::ports::EntityAccessService;
+use lexical_client::LexicalClient;
use model_error_response::ErrorResponse;
use serde::Deserialize;
use sqlx::PgPool;
@@ -123,6 +124,9 @@ pub struct DocumentRouterState<T, Svc> {
pub pool: PgPool,
/// Task duplicate detection service.
pub task_dedup_service: Arc<PgTaskDedupService>,
+ /// Lexical service client, used to fetch embedding-format markdown for
+ /// task duplicate detection.
+ pub lexical_client: Arc<LexicalClient>,
/// Backend-owned document creation use case.
#[cfg(feature = "document_create_adapters")]
pub creator: DefaultDocumentCreator<T>,
@@ -136,6 +140,7 @@ impl<T, Svc> Clone for DocumentRouterState<T, Svc> {
access_service: self.access_service.clone(),
pool: self.pool.clone(),
task_dedup_service: self.task_dedup_service.clone(),
+ lexical_client: self.lexical_client.clone(),
#[cfg(feature = "document_create_adapters")]
creator: self.creator.clone(),
}
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.rs
index 3171faab3c..6579b907e7 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
@@ -80,6 +80,7 @@ pub async fn create_task_handler<
let document_id = created.document_id().to_string();
spawn_task_duplicate_detection(
state.task_dedup_service.clone(),
+ state.lexical_client.clone(),
NewTask {
document_id: document_id.clone(),
owner,
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.rs
index 7c48676b11..d676711a3d 100644
--- a/rust/cloud-storage/documents/src/inbound/axum_router/task_duplicates.rs
+++ b/rust/cloud-storage/documents/src/inbound/axum_router/task_duplicates.rs
@@ -11,6 +11,7 @@ use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::{
DocumentAccessExtractor, OptionalMacroUserTeamExtractor,
};
+use lexical_client::{LexicalClient, parse_markdown::MarkdownTarget};
use model::document::DocumentBasic;
use model::response::GenericSuccessResponse;
use model_user::axum_extractor::MacroUserExtractor;
@@ -50,7 +51,11 @@ pub struct DismissTaskDuplicatesRequest {
pub struct TaskSimilaritySearchRequest {
/// Draft task title.
pub task_name: String,
- /// Draft task markdown body.
+ /// Draft task body as embedding-format markdown. The composer produces it
+ /// client-side with lexical-core's `markdownToEmbeddingText` (the same
+ /// format lexical-service's `/markdown/{id}?target=embedding` renders), so
+ /// this latency-sensitive endpoint embeds the text as-is without a
+ /// lexical-service round trip.
pub markdown: Option<String>,
/// Whether the task will be shared with the user's team, which widens the
/// search scope to team tasks.
@@ -177,8 +182,28 @@ pub async fn delete_this_duplicate_task_handler<T: DocumentService, Svc: EntityA
}
/// Spawn duplicate detection for a newly created task.
-pub fn spawn_task_duplicate_detection(task_dedup_service: Arc<PgTaskDedupService>, task: NewTask) {
+///
+/// The created document's body is fetched from lexical-service rendered as
+/// embedding-format markdown so the stored embedding matches the format the
+/// composer's similarity search sends. When that fetch fails, the markdown the
+/// task was created with (internal format) is used as a fallback.
+pub fn spawn_task_duplicate_detection(
+ task_dedup_service: Arc<PgTaskDedupService>,
+ lexical_client: Arc<LexicalClient>,
+ mut task: NewTask,
+) {
tokio::spawn(async move {
+ match lexical_client
+ .get_markdown(&task.document_id, MarkdownTarget::Embedding)
+ .await
+ {
+ Ok(markdown) => task.markdown = markdown,
+ Err(error) => tracing::warn!(
+ error=?error,
+ document_id=%task.document_id,
+ "failed to fetch embedding markdown for task dedup; using creation markdown"
+ ),
+ }
let _ = task_dedup_service
.detect_new_task(task)
.await
diff --git a/rust/cloud-storage/embedding/src/entity/task.rs b/rust/cloud-storage/embedding/src/entity/task.rs
index 3ea81ca9fd..c99bb3dcf5 100644
--- a/rust/cloud-storage/embedding/src/entity/task.rs
+++ b/rust/cloud-storage/embedding/src/entity/task.rs
@@ -9,7 +9,7 @@ static BODY: &str = "body";
pub struct Task<'a> {
/// task name
pub title: Cow<'a, str>,
- /// task body
+ /// task body, as internal markdown
pub body: Cow<'a, str>,
}
diff --git a/rust/cloud-storage/lexical_client/src/parse_markdown.rs b/rust/cloud-storage/lexical_client/src/parse_markdown.rs
index e3efc8e985..292eaa114a 100644
--- a/rust/cloud-storage/lexical_client/src/parse_markdown.rs
+++ b/rust/cloud-storage/lexical_client/src/parse_markdown.rs
@@ -28,6 +28,29 @@ struct MarkdownResponse {
data: String,
}
+/// Rendering target supported by the lexical service `/markdown` endpoint.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum MarkdownTarget {
+ /// Internal XML-tagged markdown (lossless round-trip format).
+ Internal,
+ /// GitHub-flavored markdown for external consumption.
+ External,
+ /// Compact embedding-friendly text: internal markdown with mentions
+ /// reduced to display names plus the ids they reference. Used for task
+ /// duplicate detection.
+ Embedding,
+}
+
+impl MarkdownTarget {
+ fn as_str(self) -> &'static str {
+ match self {
+ MarkdownTarget::Internal => "internal",
+ MarkdownTarget::External => "external",
+ MarkdownTarget::Embedding => "embedding",
+ }
+ }
+}
+
impl From<LexicalResponseItem> for MarkdownParseResult {
fn from(result: LexicalResponseItem) -> MarkdownParseResult {
MarkdownParseResult {
@@ -57,10 +80,16 @@ impl LexicalClient {
Ok(data.data.into_iter().map(Into::into).collect())
}
- /// Fetches the full document rendered as a single plain markdown string.
+ /// Fetches the full document rendered as a single markdown string in the
+ /// requested target format.
#[tracing::instrument(skip(self), err)]
- pub async fn get_markdown(&self, document_id: &str) -> Result<String> {
- let url = format!("{}/markdown/{}", self.url, document_id);
+ pub async fn get_markdown(&self, document_id: &str, target: MarkdownTarget) -> Result<String> {
+ let url = format!(
+ "{}/markdown/{}?target={}",
+ self.url,
+ document_id,
+ target.as_str()
+ );
let response: MarkdownResponse = self.get_json(&url).await?;
Ok(response.data)
}
diff --git a/rust/cloud-storage/task_dedup/src/bin/backfill_task_embeddings.rs b/rust/cloud-storage/task_dedup/src/bin/backfill_task_embeddings.rs
index 5786a7954a..d94ed5ee70 100644
--- a/rust/cloud-storage/task_dedup/src/bin/backfill_task_embeddings.rs
+++ b/rust/cloud-storage/task_dedup/src/bin/backfill_task_embeddings.rs
@@ -11,6 +11,7 @@ use embedding::entity::Task;
use embedding::{EmbeddingModel, VectorStore};
use futures::StreamExt;
use lexical_client::LexicalClient;
+use lexical_client::parse_markdown::MarkdownTarget;
use macro_env_var::env_var;
use macro_service_urls::LexicalServiceUrl;
use secretsmanager_client::{SecretManager, SecretsManager};
@@ -398,15 +399,19 @@ async fn embed_and_store(ctx: &Context, document_id: &str) -> Result<()> {
}
/// Builds the embeddable [`Task`] for a single document: its `Document.name`
-/// becomes the title and the lexical service's rendered markdown becomes the
-/// body. Map this over a task set to get the entities to embed.
+/// becomes the title and the lexical service's embedding-format markdown
+/// becomes the body — the same format the composer's similarity search sends.
+/// Map this over a task set to get the entities to embed.
async fn fetch_md_task(ctx: &Context, document_id: &str) -> Result<Task<'static>> {
let title = sqlx::query_scalar!(r#"SELECT name FROM "Document" WHERE id = $1"#, document_id)
.fetch_one(&ctx.pg)
.await
.map_err(anyhow::Error::from)?;
- let body = ctx.lexical.get_markdown(document_id).await?;
+ let body = ctx
+ .lexical
+ .get_markdown(document_id, MarkdownTarget::Embedding)
+ .await?;
Ok(Task {
title: Cow::Owned(title),
diff --git a/rust/cloud-storage/task_dedup/src/domain/models.rs b/rust/cloud-storage/task_dedup/src/domain/models.rs
index 38bf4de607..b512899bb0 100644
--- a/rust/cloud-storage/task_dedup/src/domain/models.rs
+++ b/rust/cloud-storage/task_dedup/src/domain/models.rs
@@ -17,7 +17,9 @@ pub struct NewTask {
pub team_id: Option<Uuid>,
/// Task title.
pub title: String,
- /// Task markdown body.
+ /// Task body, ideally as embedding-format markdown (lexical-service's
+ /// `embedding` markdown target): the body is embedded as-is, so mention
+ /// tags left in other formats skew similarity toward their serialization.
pub markdown: String,
}
diff --git a/rust/cloud-storage/task_dedup/src/domain/service.rs b/rust/cloud-storage/task_dedup/src/domain/service.rs
index 1582545712..61931d3ea3 100644
--- a/rust/cloud-storage/task_dedup/src/domain/service.rs
+++ b/rust/cloud-storage/task_dedup/src/domain/service.rs
@@ -167,7 +167,8 @@ where
///
/// Runs vector retrieval + rerank only (no judge) and persists nothing: the
/// embedding is computed in memory and discarded. Results are ordered by the
- /// reranker's relevance score.
+ /// reranker's relevance score. `markdown` is embedded as-is and should be
+ /// embedding-format markdown, matching how stored tasks are embedded.
pub async fn similarity_search(
&self,
owner: &str,