Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(onboarding): add Notion understanding source (#18110)

Neko8aa1e9bdde1d
diff --git a/apps/server/src/routers/lambda/__tests__/user.test.ts b/apps/server/src/routers/lambda/__tests__/user.test.ts
index f1ad724dee0..9da1d7c4a4e 100644
--- a/apps/server/src/routers/lambda/__tests__/user.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/user.test.ts
@@ -129,13 +129,20 @@ describe('userRouter', () => {
const workspaceCtx = { ...mockCtx, workspaceId: 'workspace-1' };
it('returns supported apps separately from currently available sources', async () => {
- /** @example Gmail remains connectable while only GitHub is currently usable. */
+ /** @example Gmail and Notion remain connectable while only GitHub is currently usable. */
mockUnderstandingService.listSourceProviderIds.mockResolvedValueOnce(['github']);
+ // ROOT CAUSE:
+ //
+ // The supported-provider expectation still listed only GitHub and Gmail after Notion was
+ // registered, so the router correctly returned one more provider than the stale assertion.
+ //
+ // We keep the expectation aligned with the provider registry while preserving the separate
+ // sourceProviderIds assertion for providers that are currently usable by this user.
await expect(
userRouter.createCaller(scopedCtx).getSupportedUnderstandingProviders(),
).resolves.toEqual({
- providerIds: ['github', 'gmail'],
+ providerIds: ['github', 'gmail', 'notion'],
sourceProviderIds: ['github'],
});
});
diff --git a/apps/server/src/services/connectorData/index.test.ts b/apps/server/src/services/connectorData/index.test.ts
index 141c38c0bfa..807d797888a 100644
--- a/apps/server/src/services/connectorData/index.test.ts
+++ b/apps/server/src/services/connectorData/index.test.ts
@@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({
createGitHubComposioClient: vi.fn(),
createGitHubOAuthClient: vi.fn(),
createGmailClient: vi.fn(),
+ createNotionClient: vi.fn(),
ensureFreshConnectorToken: vi.fn(),
findById: vi.fn(),
getAccount: vi.fn(),
@@ -29,6 +30,10 @@ vi.mock('@lobechat/connector-data/gmail', () => ({
createGmailConnectorClient: mocks.createGmailClient,
}));
+vi.mock('@lobechat/connector-data/notion', () => ({
+ createNotionConnectorClient: mocks.createNotionClient,
+}));
+
vi.mock('@/database/models/connector', () => ({
ConnectorModel: vi.fn(() => ({
findById: mocks.findById,
@@ -80,6 +85,7 @@ describe('ConnectorDataService', () => {
mocks.markComposioUnavailable.mockResolvedValue(false);
mocks.getAccount.mockResolvedValue({ externalAccountId: 'gmail-account', scopes: [] });
mocks.createGmailClient.mockReturnValue({ getAccount: mocks.getAccount, kind: 'gmail-client' });
+ mocks.createNotionClient.mockReturnValue({ kind: 'notion-client' });
mocks.queryReferences.mockResolvedValue([]);
mocks.queryComposioReferences.mockResolvedValue([]);
});
@@ -382,6 +388,32 @@ describe('ConnectorDataService', () => {
expect(mocks.markComposioUnavailable).not.toHaveBeenCalled();
});
+ /** @example An ACTIVE Notion connection resolves through the registry-backed provider client. */
+ it('creates Notion from the first active Composio connector', async () => {
+ mocks.queryComposioReferences.mockResolvedValue([
+ {
+ composio: {
+ appSlug: 'notion',
+ connectedAccountId: 'notion-account',
+ ownerUserId: 'notion-owner',
+ status: 'ACTIVE',
+ },
+ id: 'notion-a',
+ isEnabled: true,
+ status: 'connected',
+ },
+ ]);
+
+ await expect(
+ new ConnectorDataService(authDb([]), 'user-1').getNotionClient(),
+ ).resolves.toEqual({ kind: 'notion-client' });
+ expect(mocks.createNotionClient).toHaveBeenCalledWith({
+ composio: expect.objectContaining({ kind: 'composio' }),
+ connectedAccountId: 'notion-account',
+ userId: 'notion-owner',
+ });
+ });
+
it('lists only providers whose connector client can currently be resolved', async () => {
/** @example A stale Gmail connection is excluded while GitHub OAuth remains available. */
const service = new ConnectorDataService(
@@ -389,7 +421,7 @@ describe('ConnectorDataService', () => {
'user-1',
);
- await expect(service.listAvailableProviderIds(['github', 'gmail'])).resolves.toEqual([
+ await expect(service.listAvailableProviderIds(['github', 'gmail', 'notion'])).resolves.toEqual([
'github',
]);
});
diff --git a/apps/server/src/services/connectorData/index.ts b/apps/server/src/services/connectorData/index.ts
index 790b687d390..e93decdfb88 100644
--- a/apps/server/src/services/connectorData/index.ts
+++ b/apps/server/src/services/connectorData/index.ts
@@ -1,4 +1,8 @@
-import { ConnectorDataError } from '@lobechat/connector-data';
+import {
+ ConnectorDataError,
+ type ConnectorDataProvider,
+ isConnectorDataProvider,
+} from '@lobechat/connector-data';
import type { GitHubConnectorClient } from '@lobechat/connector-data/github';
import {
createGitHubComposioConnectorClient,
@@ -6,6 +10,8 @@ import {
} from '@lobechat/connector-data/github';
import type { GmailConnectorClient } from '@lobechat/connector-data/gmail';
import { createGmailConnectorClient } from '@lobechat/connector-data/gmail';
+import type { NotionConnectorClient } from '@lobechat/connector-data/notion';
+import { createNotionConnectorClient } from '@lobechat/connector-data/notion';
import { and, eq } from 'drizzle-orm';
import { ConnectorModel } from '@/database/models/connector';
@@ -17,7 +23,7 @@ import { ensureFreshConnectorToken } from '@/server/services/connector/tokens';
const TOKEN_EXPIRY_SKEW_MS = 60_000;
-const unavailable = (provider: 'github' | 'gmail') =>
+const unavailable = (provider: ConnectorDataProvider) =>
new ConnectorDataError({
code: `${provider}_authorization_unavailable`,
operation: 'getClient',
@@ -25,7 +31,7 @@ const unavailable = (provider: 'github' | 'gmail') =>
retryable: false,
});
-const isConfirmedProviderUnavailableError = (error: unknown, provider: 'github' | 'gmail') =>
+const isConfirmedProviderUnavailableError = (error: unknown, provider: ConnectorDataProvider) =>
error instanceof ConnectorDataError &&
error.provider === provider &&
!error.retryable &&
@@ -46,7 +52,7 @@ const isActiveComposioReference = (
isEnabled: boolean;
status: string;
},
- provider: 'github' | 'gmail',
+ provider: ConnectorDataProvider,
) =>
isActiveReference(reference) &&
reference.composio?.appSlug.slice(0, 32).toLowerCase() === provider &&
@@ -80,6 +86,15 @@ export class ConnectorDataService {
private readonly workspaceId?: string,
) {}
+ private resolveProviderClient = (providerId: ConnectorDataProvider): Promise<unknown> => {
+ const resolvers: Record<ConnectorDataProvider, () => Promise<unknown>> = {
+ github: () => this.getGitHubClient(),
+ gmail: () => this.getGmailClient(),
+ notion: () => this.getNotionClient(),
+ };
+ return resolvers[providerId]();
+ };
+
/**
* Lists provider identifiers with a connector client that can be resolved now.
*
@@ -95,21 +110,19 @@ export class ConnectorDataService {
listAvailableProviderIds = async (providerIds: readonly string[]): Promise<string[]> => {
const availability = await Promise.all(
providerIds.map(async (providerId) => {
- const provider = providerId === 'github' || providerId === 'gmail' ? providerId : undefined;
- if (!provider) return;
+ if (!isConnectorDataProvider(providerId)) return;
try {
- if (provider === 'github') await this.getGitHubClient();
- else await this.getGmailClient();
- return provider;
+ await this.resolveProviderClient(providerId);
+ return providerId;
} catch (error) {
- if (isConfirmedProviderUnavailableError(error, provider)) return;
+ if (isConfirmedProviderUnavailableError(error, providerId)) return;
throw error;
}
}),
);
return availability.filter(
- (providerId): providerId is 'github' | 'gmail' => providerId !== undefined,
+ (providerId): providerId is ConnectorDataProvider => providerId !== undefined,
);
};
@@ -228,4 +241,47 @@ export class ConnectorDataService {
}
throw unavailable('gmail');
};
+
+ /**
+ * Resolves the first active Notion Composio account for this user scope.
+ *
+ * Use when:
+ * - An onboarding collector needs read-only Notion workspace evidence
+ *
+ * Expects:
+ * - A connected Notion reference whose remote Composio account remains ACTIVE
+ *
+ * Returns:
+ * - A user-scoped Notion connector client
+ */
+ getNotionClient = async (): Promise<NotionConnectorClient> => {
+ const connectorModel = new ConnectorModel(this.db, this.userId, this.workspaceId);
+ const references = (await connectorModel.queryComposioReferencesByIdentifiers(['notion']))
+ .filter((reference) => isActiveComposioReference(reference, 'notion'))
+ .toSorted((left, right) => left.id.localeCompare(right.id));
+
+ for (const reference of references) {
+ const composio = reference.composio;
+ if (!composio) continue;
+ try {
+ const composioClient = getComposioClient();
+ const connectedAccount = await composioClient.connectedAccounts.get(
+ composio.connectedAccountId,
+ );
+ if (connectedAccount.status !== 'ACTIVE') continue;
+ return createNotionConnectorClient({
+ composio: composioClient,
+ connectedAccountId: composio.connectedAccountId,
+ userId: composio.ownerUserId,
+ });
+ } catch (error) {
+ if (!isComposioConnectedAccountLookupNotFoundError(error)) throw error;
+ await connectorModel.markComposioConnectionUnavailable(
+ reference.id,
+ composio.connectedAccountId,
+ );
+ }
+ }
+ throw unavailable('notion');
+ };
}
diff --git a/apps/server/src/services/taskRecommendation/config.test.ts b/apps/server/src/services/taskRecommendation/config.test.ts
index 488cfb43902..4d8367fbe81 100644
--- a/apps/server/src/services/taskRecommendation/config.test.ts
+++ b/apps/server/src/services/taskRecommendation/config.test.ts
@@ -17,13 +17,10 @@ describe('TaskRecommendationConfigurator', () => {
expect(new TaskRecommendationConfigurator().recommendationsPerProvider(0)).toBe(0);
});
- /** @example Runtime collection limits remain paired with prompt-package provider guides. */
- it('combines operational provider settings with prompt guides', () => {
- const { providers, writing } = new TaskRecommendationConfigurator();
+ /** @example Shared writing policy stays independent from provider-owned collectors and guides. */
+ it('exposes the shared recommendation writing policy', () => {
+ const { writing } = new TaskRecommendationConfigurator();
- expect(providers.github).toMatchObject({ maxContextLength: 24_000, maxSignals: 24 });
- expect(providers.github.examples.length).toBeGreaterThan(0);
- expect(providers.gmail.queries).toHaveLength(3);
expect(writing.maxSourcesPerRecommendation).toBe(4);
});
});
diff --git a/apps/server/src/services/taskRecommendation/config.ts b/apps/server/src/services/taskRecommendation/config.ts
index fe91b3c431b..ed47d557eb7 100644
--- a/apps/server/src/services/taskRecommendation/config.ts
+++ b/apps/server/src/services/taskRecommendation/config.ts
@@ -44,17 +44,27 @@ export interface GmailTaskRecommendationProviderConfig extends TaskRecommendatio
queries: GmailTaskRecommendationQuery[];
}
+/** Notion collection policy for task-oriented workspace signals. */
+export interface NotionTaskRecommendationProviderConfig extends TaskRecommendationProviderConfig {
+ /** Maximum pages enriched with Notion-flavored Markdown. */
+ maxContentPages: number;
+ /** Maximum actionable Notion records serialized into one recommendation call. */
+ maxSignals: number;
+ /** Age after the last edit at which a page becomes a maintenance review candidate. */
+ staleAfterDays: number;
+ /**
+ * Minimum share of dated visible items that must be stale before coverage-first guidance applies.
+ * @default 0.9
+ */
+ staleItemRatioThreshold: number;
+ /** Additional trusted writing policy used when the visible Notion scan is stale-dominant. */
+ staleWorkspacePrinciples: readonly string[];
+}
+
/** Complete configurable policy for onboarding task generation. */
export interface TaskRecommendationConfig {
/** Cross-provider recommendation allocation policy. */
allocation: TaskRecommendationAllocationConfig;
- /** Provider playbooks keyed by connector identifier. */
- providers: {
- /** GitHub recommendation and collection policy. */
- github: GitHubTaskRecommendationProviderConfig;
- /** Gmail recommendation and collection policy. */
- gmail: GmailTaskRecommendationProviderConfig;
- };
/** Cross-provider recommendation writing policy. */
writing: OnboardingTaskRecommendationWritingGuide;
}
@@ -66,41 +76,17 @@ export const defaultTaskRecommendationConfig: TaskRecommendationConfig = {
minPerProvider: 2,
targetTotal: 4,
},
- providers: {
- github: {
- ...DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG.providers.github,
- maxContextLength: 24_000,
- maxSignals: 24,
- staleAfterDays: 120,
- },
- gmail: {
- ...DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG.providers.gmail,
- maxContextLength: 24_000,
- maxSignals: 32,
- queries: [
- { kind: 'actionable', query: 'in:inbox newer_than:30d (is:important OR is:starred)' },
- { kind: 'follow_up_candidate', query: 'in:sent older_than:7d newer_than:90d' },
- {
- kind: 'subscription_cleanup',
- query: 'newer_than:180d (category:promotions OR unsubscribe)',
- },
- ],
- },
- },
writing: DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG.writing,
};
/** Computes provider budgets from an injectable recommendation policy. */
export class TaskRecommendationConfigurator {
private readonly allocation: TaskRecommendationAllocationConfig;
- /** Provider-specific collection and prompt policy keyed by connector. */
- readonly providers: TaskRecommendationConfig['providers'];
/** Shared title, instruction, and source policy for every provider writer. */
readonly writing: OnboardingTaskRecommendationWritingGuide;
constructor(config: TaskRecommendationConfig = defaultTaskRecommendationConfig) {
this.allocation = config.allocation;
- this.providers = config.providers;
this.writing = config.writing;
}
diff --git a/apps/server/src/services/taskRecommendation/materializer.test.ts b/apps/server/src/services/taskRecommendation/materializer.test.ts
index 31b7b0ce63a..27ebd48f10f 100644
--- a/apps/server/src/services/taskRecommendation/materializer.test.ts
+++ b/apps/server/src/services/taskRecommendation/materializer.test.ts
@@ -22,6 +22,11 @@ const recommendationSession = (): OnboardingTaskRecommendationSession => ({
sources: [
{ type: 'github', url: 'https://github.com/lobehub/lobehub/pull/1' },
{ subject: 'CI result', type: 'gmail', url: 'gmail:thread:1' },
+ {
+ title: 'Launch plan',
+ type: 'notion',
+ url: 'https://www.notion.so/launch-plan',
+ },
],
title: 'Inspect the pull request state',
},
@@ -84,6 +89,7 @@ describe('TaskRecommendationMaterializer', () => {
'Sources:',
'- https://github.com/lobehub/lobehub/pull/1',
'- CI result: gmail:thread:1',
+ '- Launch plan: https://www.notion.so/launch-plan',
].join('\n'),
}),
);
diff --git a/apps/server/src/services/taskRecommendation/materializer.ts b/apps/server/src/services/taskRecommendation/materializer.ts
index 3c573b95da4..66cbb575123 100644
--- a/apps/server/src/services/taskRecommendation/materializer.ts
+++ b/apps/server/src/services/taskRecommendation/materializer.ts
@@ -77,8 +77,8 @@ export class TaskRecommendationMaterializer {
);
if (!recommendation) return { status: 'not-found' };
- const sourceList = recommendation.sources.map(({ subject, url }) =>
- subject ? `- ${subject}: ${url}` : `- ${url}`,
+ const sourceList = recommendation.sources.map(({ subject, title, url }) =>
+ title || subject ? `- ${title ?? subject}: ${url}` : `- ${url}`,
);
const task = await this.createTask(transaction as unknown as LobeChatDatabase, {
assigneeAgentId: input.assigneeAgentId,
diff --git a/apps/server/src/services/taskRecommendation/providers/github.ts b/apps/server/src/services/taskRecommendation/providers/github.ts
index 4dcd745d30b..219ee3fa7b0 100644
--- a/apps/server/src/services/taskRecommendation/providers/github.ts
+++ b/apps/server/src/services/taskRecommendation/providers/github.ts
@@ -4,10 +4,10 @@ import type {
GitHubPullRequest,
GitHubRepository,
} from '@lobechat/connector-data/github';
+import { DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG } from '@lobechat/prompts';
import type { OnboardingTaskSource } from '@lobechat/types';
import type { GitHubTaskRecommendationProviderConfig } from '../config';
-import { defaultTaskRecommendationConfig } from '../config';
import type { TaskRecommendationProvider } from '../types';
type GitHubSignal =
@@ -32,9 +32,15 @@ type GitHubSignal =
/** Creates the independent GitHub task recommendation collector. */
export const createGitHubTaskRecommendationProvider = (
- config: GitHubTaskRecommendationProviderConfig = defaultTaskRecommendationConfig.providers.github,
+ config: GitHubTaskRecommendationProviderConfig = {
+ ...DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG.providers.github,
+ maxContextLength: 24_000,
+ maxSignals: 24,
+ staleAfterDays: 120,
+ },
): TaskRecommendationProvider => ({
id: 'github',
+ guide: { examples: config.examples, principles: config.principles },
collect: async ({ connectorData }) => {
const client = await connectorData.getGitHubClient();
const [repositoryResult, pullRequestResult, contributionResult] = await Promise.allSettled([
diff --git a/apps/server/src/services/taskRecommendation/providers/gmail.test.ts b/apps/server/src/services/taskRecommendation/providers/gmail.test.ts
index 0f194d3270c..1f47f2ef837 100644
--- a/apps/server/src/services/taskRecommendation/providers/gmail.test.ts
+++ b/apps/server/src/services/taskRecommendation/providers/gmail.test.ts
@@ -1,7 +1,6 @@
// @vitest-environment node
import { describe, expect, it, vi } from 'vitest';
-import { defaultTaskRecommendationConfig } from '../config';
import { createGmailTaskRecommendationProvider } from './gmail';
/** @example Gmail evidence retains trusted subjects for source presentation. */
@@ -15,9 +14,7 @@ describe('createGmailTaskRecommendationProvider', () => {
subject: 'Your receipt from Comfy Org',
};
const searchMessages = vi.fn(async () => [message]);
- const provider = createGmailTaskRecommendationProvider(
- defaultTaskRecommendationConfig.providers.gmail,
- );
+ const provider = createGmailTaskRecommendationProvider();
const result = await provider.collect({
connectorData: {
@@ -32,5 +29,6 @@ describe('createGmailTaskRecommendationProvider', () => {
url: 'gmail:thread:thread-1',
},
]);
+ expect(provider.guide.examples.length).toBeGreaterThan(0);
});
});
diff --git a/apps/server/src/services/taskRecommendation/providers/gmail.ts b/apps/server/src/services/taskRecommendation/providers/gmail.ts
index 22d3d41f887..af2d9ff327d 100644
--- a/apps/server/src/services/taskRecommendation/providers/gmail.ts
+++ b/apps/server/src/services/taskRecommendation/providers/gmail.ts
@@ -1,9 +1,9 @@
import { ConnectorDataError } from '@lobechat/connector-data';
import type { GmailMessage } from '@lobechat/connector-data/gmail';
+import { DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG } from '@lobechat/prompts';
import type { OnboardingTaskSource } from '@lobechat/types';
import type { GmailTaskRecommendationProviderConfig } from '../config';
-import { defaultTaskRecommendationConfig } from '../config';
import type { TaskRecommendationProvider } from '../types';
interface GmailSignal {
@@ -13,9 +13,22 @@ interface GmailSignal {
/** Creates the independent Gmail task recommendation collector. */
export const createGmailTaskRecommendationProvider = (
- config: GmailTaskRecommendationProviderConfig = defaultTaskRecommendationConfig.providers.gmail,
+ config: GmailTaskRecommendationProviderConfig = {
+ ...DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG.providers.gmail,
+ maxContextLength: 24_000,
+ maxSignals: 32,
+ queries: [
+ { kind: 'actionable', query: 'in:inbox newer_than:30d (is:important OR is:starred)' },
+ { kind: 'follow_up_candidate', query: 'in:sent older_than:7d newer_than:90d' },
+ {
+ kind: 'subscription_cleanup',
+ query: 'newer_than:180d (category:promotions OR unsubscribe)',
+ },
+ ],
+ },
): TaskRecommendationProvider => ({
id: 'gmail',
+ guide: { examples: config.examples, principles: config.principles },
collect: async ({ connectorData }) => {
const client = await connectorData.getGmailClient();
const maxResults = Math.max(1, Math.ceil(config.maxSignals / config.queries.length));
diff --git a/apps/server/src/services/taskRecommendation/providers/index.ts b/apps/server/src/services/taskRecommendation/providers/index.ts
index ba21fe2092c..7429bf94f6d 100644
--- a/apps/server/src/services/taskRecommendation/providers/index.ts
+++ b/apps/server/src/services/taskRecommendation/providers/index.ts
@@ -1,11 +1,13 @@
import type { TaskRecommendationProvider } from '../types';
import { createGitHubTaskRecommendationProvider } from './github';
import { createGmailTaskRecommendationProvider } from './gmail';
+import { createNotionTaskRecommendationProvider } from './notion';
/** Independent connector providers used by the onboarding task workflow. */
export const taskRecommendationProviders = [
createGitHubTaskRecommendationProvider(),
createGmailTaskRecommendationProvider(),
+ createNotionTaskRecommendationProvider(),
] as const satisfies readonly TaskRecommendationProvider[];
/** Provider registry used for connector validation and workflow dispatch. */
diff --git a/apps/server/src/services/taskRecommendation/providers/notion.test.ts b/apps/server/src/services/taskRecommendation/providers/notion.test.ts
new file mode 100644
index 00000000000..31d2c650700
--- /dev/null
+++ b/apps/server/src/services/taskRecommendation/providers/notion.test.ts
@@ -0,0 +1,207 @@
+// @vitest-environment node
+import type { NotionItem } from '@lobechat/connector-data/notion';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createNotionTaskRecommendationProvider } from './notion';
+
+const page = (overrides: Partial<NotionItem> = {}): NotionItem => ({
+ id: 'page-1',
+ kind: 'page',
+ lastEditedAt: '2026-08-01T00:00:00.000Z',
+ propertyNames: ['Name'],
+ sourceUrl: 'https://www.notion.so/page-1',
+ title: 'Launch plan',
+ ...overrides,
+});
+
+/** @example Notion task signals remain read-only and grounded in exact page URLs. */
+describe('createNotionTaskRecommendationProvider', () => {
+ /** @example Unchecked tasks become a trusted recommendation signal and titled source. */
+ it('collects open action items from page Markdown', async () => {
+ const provider = createNotionTaskRecommendationProvider();
+ const result = await provider.collect({
+ connectorData: {
+ getNotionClient: vi.fn(async () => ({
+ getPageMarkdown: vi.fn(async () => '# Launch\n- [ ] Prepare release notes'),
+ listItems: vi.fn(async () => [page()]),
+ })),
+ },
+ } as never);
+
+ expect(result).toMatchObject({
+ diagnostics: { evidenceCount: 1, failedCount: 0 },
+ signalCount: 1,
+ sources: [
+ {
+ title: 'Launch plan',
+ type: 'notion',
+ url: 'https://www.notion.so/page-1',
+ },
+ ],
+ });
+ expect(result.context).toContain('open_action_items');
+ });
+
+ /** @example A recently edited page without action markers does not create generic busywork. */
+ it('returns no signals for non-actionable page content', async () => {
+ const provider = createNotionTaskRecommendationProvider();
+ const result = await provider.collect({
+ connectorData: {
+ getNotionClient: vi.fn(async () => ({
+ getPageMarkdown: vi.fn(async () => '# Team handbook\nWelcome to the team.'),
+ listItems: vi.fn(async () => [page()]),
+ })),
+ },
+ } as never);
+
+ expect(result).toMatchObject({ signalCount: 0, sources: [] });
+ });
+
+ /** @example An entirely old authorized workspace becomes one coverage-first review. */
+ it('adds a coverage-first generation policy when every visible item is stale', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-08-09T00:00:00.000Z'));
+
+ try {
+ const provider = createNotionTaskRecommendationProvider();
+ const result = await provider.collect({
+ connectorData: {
+ getNotionClient: vi.fn(async () => ({
+ getPageMarkdown: vi.fn(async () => '# Old plan\n- [ ] Ship the old milestone'),
+ listItems: vi.fn(async () => [
+ page({ lastEditedAt: '2021-08-30T00:00:00.000Z' }),
+ page({
+ id: 'page-2',
+ lastEditedAt: '2022-01-01T00:00:00.000Z',
+ sourceUrl: 'https://www.notion.so/page-2',
+ title: 'Architecture notes',
+ }),
+ ]),
+ })),
+ },
+ } as never);
+
+ expect(result.recommendationLimit).toBe(1);
+ expect(result.promptPrinciples).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining('2 of 2 Notion items returned by the current bounded connector scan'),
+ expect.stringContaining('Do not turn old TODOs'),
+ expect.stringContaining('workspace, account, integration, page, and Teamspace access'),
+ ]),
+ );
+ expect(result.context).toContain('"mode": "stale_dominant"');
+ expect(result.context).toContain('"latestEditedAt": "2022-01-01T00:00:00.000Z"');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ /** @example A balanced current-and-old scan keeps normal content-oriented recommendation policy. */
+ it('keeps normal recommendation policy when stale items are not dominant', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-08-09T00:00:00.000Z'));
+
+ try {
+ const provider = createNotionTaskRecommendationProvider();
+ const result = await provider.collect({
+ connectorData: {
+ getNotionClient: vi.fn(async () => ({
+ getPageMarkdown: vi.fn(async () => '# Plan\n- [ ] Review the current milestone'),
+ listItems: vi.fn(async () => [
+ page({ lastEditedAt: '2021-08-30T00:00:00.000Z' }),
+ page({
+ id: 'page-2',
+ lastEditedAt: '2026-08-01T00:00:00.000Z',
+ sourceUrl: 'https://www.notion.so/page-2',
+ }),
+ ]),
+ })),
+ },
+ } as never);
+
+ expect(result.recommendationLimit).toBeUndefined();
+ expect(result.promptPrinciples).toBeUndefined();
+ expect(result.context).toContain('"mode": "mixed_or_current"');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ /** @example One recently touched hub does not make many old project pages look current. */
+ it('adds coverage-first guidance when old items dominate a recently touched hub', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-08-09T00:00:00.000Z'));
+
+ try {
+ const provider = createNotionTaskRecommendationProvider();
+ const stalePages = Array.from({ length: 9 }, (_, index) =>
+ page({
+ id: `old-page-${index}`,
+ lastEditedAt: '2021-08-30T00:00:00.000Z',
+ sourceUrl: `https://www.notion.so/old-page-${index}`,
+ title: `Old project page ${index}`,
+ }),
+ );
+ const result = await provider.collect({
+ connectorData: {
+ getNotionClient: vi.fn(async () => ({
+ getPageMarkdown: vi.fn(async () => '# Project index'),
+ listItems: vi.fn(async () => [
+ page({
+ id: 'recent-hub',
+ lastEditedAt: '2026-08-01T00:00:00.000Z',
+ sourceUrl: 'https://www.notion.so/recent-hub',
+ title: 'Workspace hub',
+ }),
+ ...stalePages,
+ ]),
+ })),
+ },
+ } as never);
+
+ expect(result.recommendationLimit).toBe(1);
+ expect(result.promptPrinciples).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining('9 of 10 Notion items'),
+ expect.stringContaining('hub, index, or access-related page'),
+ ]),
+ );
+ expect(result.context).toContain('"mode": "stale_dominant"');
+ expect(result.context).toContain('"recentItemCount": 1');
+ expect(result.context).toContain('"staleItemRatio": 0.9');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ /** @example Missing edit dates cannot prove that the bounded visible sample is entirely old. */
+ it('does not infer stale-only policy when any visible item has unknown recency', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-08-09T00:00:00.000Z'));
+
+ try {
+ const provider = createNotionTaskRecommendationProvider();
+ const result = await provider.collect({
+ connectorData: {
+ getNotionClient: vi.fn(async () => ({
+ getPageMarkdown: vi.fn(async () => '# Plan\n- [ ] Review this item'),
+ listItems: vi.fn(async () => [
+ page({ lastEditedAt: '2021-08-30T00:00:00.000Z' }),
+ page({
+ id: 'page-2',
+ lastEditedAt: undefined,
+ sourceUrl: 'https://www.notion.so/page-2',
+ }),
+ ]),
+ })),
+ },
+ } as never);
+
+ expect(result.recommendationLimit).toBeUndefined();
+ expect(result.promptPrinciples).toBeUndefined();
+ expect(result.context).toContain('"mode": "mixed_or_current"');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/apps/server/src/services/taskRecommendation/providers/notion.ts b/apps/server/src/services/taskRecommendation/providers/notion.ts
new file mode 100644
index 00000000000..a66eeff6068
--- /dev/null
+++ b/apps/server/src/services/taskRecommendation/providers/notion.ts
@@ -0,0 +1,197 @@
+import { ConnectorDataError } from '@lobechat/connector-data';
+import type { NotionItem } from '@lobechat/connector-data/notion';
+import { DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG } from '@lobechat/prompts';
+import type { OnboardingTaskSource } from '@lobechat/types';
+
+import type { NotionTaskRecommendationProviderConfig } from '../config';
+import type { TaskRecommendationProvider } from '../types';
+
+interface NotionSignal {
+ excerpt?: string;
+ kind: 'follow_up_notes' | 'open_action_items' | 'stale_page_review';
+ lastEditedAt?: string;
+ openTaskCount?: number;
+ sourceUrl: string;
+ title: string;
+}
+
+const MAX_EXCERPT_LENGTH = 6000;
+const MAX_WORKSPACE_ITEMS = 50;
+const UNCHECKED_TASK_PATTERN = /^[\t ]*[-*][\t ]+\[[\t ]\][\t ]+/gm;
+const FOLLOW_UP_PATTERN = /\b(?:TODO|TBD|FIXME|follow[- ]?up|next steps?)\b/i;
+
+const editTime = ({ lastEditedAt }: NotionItem): number => {
+ if (!lastEditedAt) return 0;
+ const milliseconds = new Date(lastEditedAt).getTime();
+ return Number.isFinite(milliseconds) ? milliseconds : 0;
+};
+
+const staleBefore = (days: number): number =>
+ // Convert the product-facing day threshold to milliseconds before comparing Notion timestamps.
+ Date.now() - days * 24 * 60 * 60 * 1000;
+
+const contentSignal = (item: NotionItem, markdown: string): NotionSignal | undefined => {
+ const uncheckedTasks = markdown.match(UNCHECKED_TASK_PATTERN) ?? [];
+ if (uncheckedTasks.length > 0) {
+ return {
+ excerpt: markdown.slice(0, MAX_EXCERPT_LENGTH),
+ kind: 'open_action_items',
+ lastEditedAt: item.lastEditedAt,
+ openTaskCount: uncheckedTasks.length,
+ sourceUrl: item.sourceUrl,
+ title: item.title,
+ };
+ }
+ if (FOLLOW_UP_PATTERN.test(markdown)) {
+ return {
+ excerpt: markdown.slice(0, MAX_EXCERPT_LENGTH),
+ kind: 'follow_up_notes',
+ lastEditedAt: item.lastEditedAt,
+ sourceUrl: item.sourceUrl,
+ title: item.title,
+ };
+ }
+};
+
+/**
+ * Creates the independent Notion task recommendation collector.
+ *
+ * Use when:
+ * - The onboarding task workflow needs actionable signals from connected Notion pages
+ * - Tests or product tuning need to inject a bounded Notion collection policy
+ *
+ * Expects:
+ * - A read-only Notion connector available through Connector Data
+ * - Prompt examples and principles that preserve external side-effect boundaries
+ *
+ * Returns:
+ * - A registry-ready provider that emits grounded page URLs and bounded evidence
+ */
+export const createNotionTaskRecommendationProvider = (
+ config: NotionTaskRecommendationProviderConfig = {
+ ...DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG.providers.notion,
+ maxContentPages: 12,
+ maxContextLength: 24_000,
+ maxSignals: 24,
+ staleAfterDays: 180,
+ staleItemRatioThreshold: 0.9,
+ },
+): TaskRecommendationProvider => ({
+ id: 'notion',
+ guide: { examples: config.examples, principles: config.principles },
+ collect: async ({ connectorData }) => {
+ const client = await connectorData.getNotionClient();
+ const items = await client.listItems({ maxResults: MAX_WORKSPACE_ITEMS });
+ const freshnessCutoff = staleBefore(config.staleAfterDays);
+ const itemEditTimes = items.map(editTime);
+ const staleItemCount = itemEditTimes.filter(
+ (milliseconds) => milliseconds > 0 && milliseconds < freshnessCutoff,
+ ).length;
+ const unknownItemCount = itemEditTimes.filter((milliseconds) => milliseconds === 0).length;
+ const recentItemCount = itemEditTimes.length - staleItemCount - unknownItemCount;
+ // Clamp the injectable ratio so a configuration mistake cannot make every scan stale-dominant.
+ const staleItemRatioThreshold = Math.min(1, Math.max(0, config.staleItemRatioThreshold));
+ const staleItemRatio = itemEditTimes.length > 0 ? staleItemCount / itemEditTimes.length : 0;
+ const isStaleDominant =
+ itemEditTimes.length > 0 &&
+ unknownItemCount === 0 &&
+ staleItemRatio >= staleItemRatioThreshold;
+ const latestItem = items.toSorted(
+ (left, right) => editTime(right) - editTime(left) || left.id.localeCompare(right.id),
+ )[0];
+ const freshness = {
+ itemCount: items.length,
+ ...(latestItem?.lastEditedAt ? { latestEditedAt: latestItem.lastEditedAt } : {}),
+ mode: isStaleDominant ? ('stale_dominant' as const) : ('mixed_or_current' as const),
+ recentItemCount,
+ scanLimit: MAX_WORKSPACE_ITEMS,
+ staleAfterDays: config.staleAfterDays,
+ staleItemCount,
+ staleItemRatio,
+ staleItemRatioThreshold,
+ unknownItemCount,
+ };
+ const contentCandidates = items
+ .filter(({ kind }) => kind === 'page')
+ .toSorted(
+ (left, right) => editTime(right) - editTime(left) || left.id.localeCompare(right.id),
+ )
+ .slice(0, config.maxContentPages);
+ const settledContent = await Promise.allSettled(
+ contentCandidates.map(({ id }) => client.getPageMarkdown(id)),
+ );
+ const errors = settledContent.flatMap((result, index) =>
+ result.status === 'rejected'
+ ? [
+ {
+ code: 'NOTION_TASK_CONTENT_COLLECTION_FAILED',
+ message: 'Notion task signal collection failed',
+ operation: `page_content_${index}`,
+ provider: 'notion',
+ retryable:
+ result.reason instanceof ConnectorDataError ? result.reason.retryable : true,
+ },
+ ]
+ : [],
+ );
+ const actionableSignals = settledContent.flatMap((result, index): NotionSignal[] => {
+ if (result.status !== 'fulfilled' || !result.value) return [];
+ const signal = contentSignal(contentCandidates[index], result.value);
+ return signal ? [signal] : [];
+ });
+ const actionableUrls = new Set(actionableSignals.map(({ sourceUrl }) => sourceUrl));
+ const maintenanceSignals = items.flatMap((item): NotionSignal[] => {
+ if (
+ actionableUrls.has(item.sourceUrl) ||
+ !item.lastEditedAt ||
+ editTime(item) >= freshnessCutoff
+ ) {
+ return [];
+ }
+ return [
+ {
+ kind: 'stale_page_review',
+ lastEditedAt: item.lastEditedAt,
+ sourceUrl: item.sourceUrl,
+ title: item.title,
+ },
+ ];
+ });
+ const signals = [...actionableSignals, ...maintenanceSignals].slice(0, config.maxSignals);
+ const sources = [
+ ...new Map(
+ signals.map((signal) => [
+ signal.sourceUrl,
+ {
+ title: signal.title.slice(0, 500),
+ type: 'notion',
+ url: signal.sourceUrl,
+ } satisfies OnboardingTaskSource,
+ ]),
+ ).values(),
+ ];
+
+ const promptPrinciples = isStaleDominant
+ ? [
+ `Freshness assessment: ${staleItemCount} of ${items.length} Notion items returned by the current bounded connector scan have valid edit dates older than ${config.staleAfterDays} days; ${recentItemCount} are newer, none have unknown dates, and the latest visible edit is ${latestItem?.lastEditedAt}. The stale share ${staleItemRatio.toFixed(3)} meets the configured ${staleItemRatioThreshold.toFixed(3)} stale-dominance threshold.`,
+ ...config.staleWorkspacePrinciples,
+ ]
+ : undefined;
+
+ return {
+ context: JSON.stringify({ freshness, provider: 'notion', signals }, null, 2).slice(
+ 0,
+ config.maxContextLength,
+ ),
+ diagnostics: {
+ errors,
+ evidenceCount: signals.length,
+ failedCount: errors.length,
+ succeededCount: 1 + settledContent.filter(({ status }) => status === 'fulfilled').length,
+ },
+ ...(promptPrinciples ? { promptPrinciples, recommendationLimit: 1 } : {}),
+ signalCount: signals.length,
+ sources,
+ };
+ },
+});
diff --git a/apps/server/src/services/taskRecommendation/service.test.ts b/apps/server/src/services/taskRecommendation/service.test.ts
index 336625cb781..dd4d6af2886 100644
--- a/apps/server/src/services/taskRecommendation/service.test.ts
+++ b/apps/server/src/services/taskRecommendation/service.test.ts
@@ -5,6 +5,8 @@ import { describe, expect, it, vi } from 'vitest';
import { TaskRecommendationConfigurator } from './config';
import { TaskRecommendationService } from './service';
+const providerGuide = { examples: [], principles: [] };
+
const session: OnboardingTaskRecommendationSession = {
completedAt: '2026-07-30T00:00:00.000Z',
createdTaskIds: {},
@@ -40,8 +42,8 @@ describe('TaskRecommendationService', () => {
connectorData: {},
onboarding: {},
providers: new Map([
- ['github', { collect: vi.fn(), id: 'github' }],
- ['gmail', { collect: vi.fn(), id: 'gmail' }],
+ ['github', { collect: vi.fn(), guide: providerGuide, id: 'github' }],
+ ['gmail', { collect: vi.fn(), guide: providerGuide, id: 'gmail' }],
]),
task: {},
topic: {
@@ -112,6 +114,7 @@ describe('TaskRecommendationService', () => {
{ type: 'github', url: 'https://github.com/lobehub/lobe-chat/issues/2' },
],
})),
+ guide: providerGuide,
id: 'github',
},
],
@@ -158,6 +161,7 @@ describe('TaskRecommendationService', () => {
signalCount: 1,
sources: [{ type: 'github', url: 'https://github.com/lobehub/lobe-chat/pull/1' }],
})),
+ guide: providerGuide,
id: 'github',
},
],
@@ -204,6 +208,7 @@ describe('TaskRecommendationService', () => {
signalCount: 3,
sources,
})),
+ guide: providerGuide,
id: 'github',
},
],
@@ -231,6 +236,66 @@ describe('TaskRecommendationService', () => {
]);
});
+ /** @example A provider freshness gate can narrow its budget and add trusted prompt policy. */
+ it('applies provider-owned generation policy before invoking the writer', async () => {
+ const source = { type: 'notion' as const, url: 'https://www.notion.so/old-page' };
+ const generate = vi.fn(async () => [
+ {
+ instruction: 'Return a private Notion access and freshness checklist.',
+ reason: 'The visible workspace evidence is old.',
+ sourceUrls: [source.url],
+ title: 'Review Notion workspace coverage',
+ },
+ {
+ instruction: 'Execute an old implementation plan.',
+ reason: 'An old page contains a TODO.',
+ sourceUrls: [source.url],
+ title: 'Implement the old plan',
+ },
+ ]);
+ const service = new TaskRecommendationService({
+ configurator: new TaskRecommendationConfigurator(),
+ connectorData: {},
+ onboarding: {},
+ providers: new Map([
+ [
+ 'notion',
+ {
+ collect: vi.fn(async () => ({
+ context: '{"provider":"notion"}',
+ diagnostics: { errors: [], evidenceCount: 1, failedCount: 0, succeededCount: 1 },
+ promptPrinciples: ['Prioritize a Notion coverage and freshness review.'],
+ recommendationLimit: 1,
+ signalCount: 1,
+ sources: [source],
+ })),
+ guide: providerGuide,
+ id: 'notion',
+ },
+ ],
+ ]),
+ task: {},
+ topic: {},
+ userId: 'user-1',
+ writer: { generate },
+ } as never);
+
+ const result = await service.generateProvider('notion', 2, 'en-US');
+
+ expect(generate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ guide: {
+ examples: [],
+ principles: ['Prioritize a Notion coverage and freshness review.'],
+ },
+ limit: 1,
+ }),
+ );
+ expect(result.recommendations.map(({ title }) => title)).toEqual([
+ 'Review Notion workspace coverage',
+ ]);
+ });
+
/** @example Repeating the same create request reuses the persisted task mapping. */
it('does not create duplicate tasks when materialization is retried', async () => {
let persisted = structuredClone(session);
diff --git a/apps/server/src/services/taskRecommendation/service.ts b/apps/server/src/services/taskRecommendation/service.ts
index 1d9cfc3af16..5234d8f9389 100644
--- a/apps/server/src/services/taskRecommendation/service.ts
+++ b/apps/server/src/services/taskRecommendation/service.ts
@@ -215,7 +215,7 @@ export class TaskRecommendationService {
responseLanguage: string,
): Promise<TaskRecommendationProviderResult> => {
const provider = this.dependencies.providers.get(providerId);
- if (!provider || (providerId !== 'github' && providerId !== 'gmail')) {
+ if (!provider) {
return {
error: {
code: 'TASK_RECOMMENDATION_PROVIDER_UNAVAILABLE',
@@ -235,17 +235,23 @@ export class TaskRecommendationService {
};
}
+ const effectiveLimit = collected.recommendationLimit
+ ? Math.min(limit, collected.recommendationLimit)
+ : limit;
const output = await this.dependencies.writer.generate({
context: collected.context,
- guide: this.dependencies.configurator.providers[providerId],
- limit,
+ guide: {
+ examples: provider.guide.examples,
+ principles: [...provider.guide.principles, ...(collected.promptPrinciples ?? [])],
+ },
+ limit: effectiveLimit,
providerId,
responseLanguage,
writingGuide: this.dependencies.configurator.writing,
});
const allowedSources = new Map(collected.sources.map((source) => [source.url, source]));
const recommendations = output
- .slice(0, limit)
+ .slice(0, effectiveLimit)
.map((item) => {
const sources = [...new Set(item.sourceUrls)]
.slice(0, this.dependencies.configurator.writing.maxSourcesPerRecommendation)
diff --git a/apps/server/src/services/taskRecommendation/types.ts b/apps/server/src/services/taskRecommendation/types.ts
index 7582ff2c53e..dfa7ebf374b 100644
--- a/apps/server/src/services/taskRecommendation/types.ts
+++ b/apps/server/src/services/taskRecommendation/types.ts
@@ -1,3 +1,4 @@
+import type { OnboardingTaskRecommendationProviderGuide } from '@lobechat/prompts';
import type { CollectionDiagnostics, OnboardingTaskSource } from '@lobechat/types';
import type { ConnectorDataService } from '@/server/services/connectorData';
@@ -8,6 +9,10 @@ export interface CollectedTaskRecommendationContext {
context: string;
/** Partial-failure diagnostics from concurrent connector operations. */
diagnostics: CollectionDiagnostics;
+ /** Trusted provider policy appended outside the untrusted connector evidence boundary. */
+ promptPrinciples?: readonly string[];
+ /** Optional provider-specific cap that narrows the workflow's recommendation budget. */
+ recommendationLimit?: number;
/** Count of usable task signals represented in the context. */
signalCount: number;
/** Trusted connector records allowed to survive structured generation. */
@@ -31,6 +36,8 @@ export interface TaskRecommendationProvider {
collect: (input: {
connectorData: ConnectorDataService;
}) => Promise<CollectedTaskRecommendationContext>;
+ /** Provider-specific safety policy and examples supplied to the isolated writer. */
+ readonly guide: OnboardingTaskRecommendationProviderGuide;
/** Connector identifier represented by this provider. */
- readonly id: 'github' | 'gmail';
+ readonly id: string;
}
diff --git a/apps/server/src/services/taskRecommendation/writer.test.ts b/apps/server/src/services/taskRecommendation/writer.test.ts
index f7249066608..21b4660f59d 100644
--- a/apps/server/src/services/taskRecommendation/writer.test.ts
+++ b/apps/server/src/services/taskRecommendation/writer.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG } from '@lobechat/prompts';
import { RequestTrigger } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
@@ -43,7 +44,7 @@ describe('TaskRecommendationWriter', () => {
const recommendations = await writer.generate({
context: '{"pullRequest":1}',
- guide: defaultTaskRecommendationConfig.providers.github,
+ guide: DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG.providers.github,
limit: 3,
providerId: 'github',
responseLanguage: 'en-US',
diff --git a/apps/server/src/services/understanding/providers/index.ts b/apps/server/src/services/understanding/providers/index.ts
index 060ee28bbc5..1ba7b79716e 100644
--- a/apps/server/src/services/understanding/providers/index.ts
+++ b/apps/server/src/services/understanding/providers/index.ts
@@ -1,14 +1,16 @@
import type { UnderstandingProvider } from '../types';
import { githubUnderstandingProvider } from './github';
import { gmailUnderstandingProvider } from './gmail';
+import { notionUnderstandingProvider } from './notion';
export const understandingProviders = [
githubUnderstandingProvider,
gmailUnderstandingProvider,
+ notionUnderstandingProvider,
] as const satisfies readonly UnderstandingProvider[];
export const understandingProviderMap = new Map<string, UnderstandingProvider>(
understandingProviders.map((provider) => [provider.id, provider]),
);
-export { githubUnderstandingProvider, gmailUnderstandingProvider };
+export { githubUnderstandingProvider, gmailUnderstandingProvider, notionUnderstandingProvider };
diff --git a/apps/server/src/services/understanding/providers/notion.test.ts b/apps/server/src/services/understanding/providers/notion.test.ts
new file mode 100644
index 00000000000..26e83a2cf32
--- /dev/null
+++ b/apps/server/src/services/understanding/providers/notion.test.ts
@@ -0,0 +1,75 @@
+import { ConnectorDataError } from '@lobechat/connector-data';
+import type { NotionItem } from '@lobechat/connector-data/notion';
+import { describe, expect, it, vi } from 'vitest';
+
+import { notionUnderstandingProvider } from './notion';
+
+const items: NotionItem[] = [
+ {
+ id: 'page-1',
+ kind: 'page',
+ lastEditedAt: '2026-08-01T00:00:00.000Z',
+ propertyNames: ['Name', 'Status'],
+ sourceUrl: 'https://www.notion.so/page-1',
+ title: 'Launch plan',
+ },
+ {
+ id: 'database-1',
+ kind: 'database',
+ propertyNames: ['Project', 'Owner'],
+ sourceUrl: 'https://www.notion.so/database-1',
+ title: 'Projects',
+ },
+];
+
+/** @example Notion workspace evidence enriches Understanding without requiring every page fetch. */
+describe('notionUnderstandingProvider', () => {
+ /** @example Directory metadata and successful page Markdown become one bounded source brief. */
+ it('collects workspace structure and recent page content', async () => {
+ const result = await notionUnderstandingProvider.collect({
+ connectorData: {
+ getNotionClient: vi.fn(async () => ({
+ getPageMarkdown: vi.fn(async () => '# Launch plan\n- [ ] Ship'),
+ listItems: vi.fn(async () => items),
+ })),
+ } as never,
+ userId: 'user-1',
+ });
+
+ expect(result).toMatchObject({
+ diagnostics: { evidenceCount: 3, failedCount: 0, succeededCount: 2 },
+ sourceCount: 3,
+ });
+ expect(result.context).toContain('Launch plan');
+ expect(result.context).toContain('- [ ] Ship');
+ });
+
+ /** @example A failed page enrichment remains partial while directory evidence stays usable. */
+ it('retains workspace metadata when page content enrichment fails', async () => {
+ const result = await notionUnderstandingProvider.collect({
+ connectorData: {
+ getNotionClient: vi.fn(async () => ({
+ getPageMarkdown: vi.fn(async () => {
+ throw new ConnectorDataError({
+ code: 'notion_page_failed',
+ operation: 'getPageMarkdown',
+ provider: 'notion',
+ retryable: true,
+ });
+ }),
+ listItems: vi.fn(async () => items),
+ })),
+ } as never,
+ userId: 'user-1',
+ });
+
+ expect(result).toMatchObject({
+ diagnostics: {
+ errors: [{ code: 'NOTION_PAGE_CONTENT_FAILED', retryable: true }],
+ evidenceCount: 2,
+ failedCount: 1,
+ },
+ sourceCount: 2,
+ });
+ });
+});
diff --git a/apps/server/src/services/understanding/providers/notion.ts b/apps/server/src/services/understanding/providers/notion.ts
new file mode 100644
index 00000000000..701a004848f
--- /dev/null
+++ b/apps/server/src/services/understanding/providers/notion.ts
@@ -0,0 +1,102 @@
+import { ConnectorDataError } from '@lobechat/connector-data';
+import type { NotionItem, NotionItemContent } from '@lobechat/connector-data/notion';
+
+import type { UnderstandingProvider } from '../types';
+
+const MAX_CONTENT_PAGES = 8;
+const MAX_CONTENT_PER_PAGE = 6000;
+const MAX_WORKSPACE_ITEMS = 40;
+
+const editTime = ({ lastEditedAt }: NotionItem): number => {
+ if (!lastEditedAt) return 0;
+ const milliseconds = new Date(lastEditedAt).getTime();
+ return Number.isFinite(milliseconds) ? milliseconds : 0;
+};
+
+const serializeContext = (items: NotionItemContent[]): string =>
+ JSON.stringify(
+ {
+ items: items.map(({ item, markdown }) => ({
+ ...item,
+ ...(markdown ? { markdown: markdown.slice(0, MAX_CONTENT_PER_PAGE) } : {}),
+ })),
+ provider: 'notion',
+ },
+ null,
+ 2,
+ );
+
+/**
+ * Collects workspace structure and recent page content for onboarding Understanding.
+ *
+ * Use when:
+ * - A connected Notion workspace participates in the onboarding Understanding session
+ *
+ * Expects:
+ * - Connector Data has resolved a read-only Notion account for the current user
+ *
+ * Returns:
+ * - A bounded source brief that remains usable when individual page reads fail
+ */
+export const notionUnderstandingProvider: UnderstandingProvider = {
+ id: 'notion',
+ collect: async ({ connectorData }) => {
+ const client = await connectorData.getNotionClient();
+ const items = await client.listItems({ maxResults: MAX_WORKSPACE_ITEMS });
+ if (items.length === 0) {
+ return {
+ context: '',
+ diagnostics: { errors: [], evidenceCount: 0, failedCount: 0, succeededCount: 1 },
+ sourceCount: 0,
+ };
+ }
+
+ const contentCandidates = items
+ .filter(({ kind }) => kind === 'page')
+ .toSorted((left, right) => editTime(right) - editTime(left) || left.id.localeCompare(right.id))
+ .slice(0, MAX_CONTENT_PAGES);
+ const settledContent = await Promise.allSettled(
+ contentCandidates.map(({ id }) => client.getPageMarkdown(id)),
+ );
+ const contentById = new Map<string, string>();
+ const errors = settledContent.flatMap((result, index) => {
+ if (result.status === 'fulfilled') {
+ if (result.value) contentById.set(contentCandidates[index].id, result.value);
+ return [];
+ }
+ return [
+ {
+ code: 'NOTION_PAGE_CONTENT_FAILED',
+ message: 'Notion page content enrichment failed',
+ operation: 'page_content',
+ provider: 'notion',
+ retryable:
+ result.reason instanceof ConnectorDataError ? result.reason.retryable : true,
+ },
+ ];
+ });
+ const enrichedItems = items.map((item) => ({ item, markdown: contentById.get(item.id) }));
+ const contentCount = contentById.size;
+ const sourceCount = items.length + contentCount;
+
+ return {
+ context: [
+ 'Provider: notion',
+ '# Source Brief',
+ 'Notion evidence policy:',
+ '- Page and database titles describe accessible workspace structure, not necessarily the user’s ownership or authorship.',
+ '- Unchecked boxes, TODO markers, and planning notes are evidence of candidate work, not proof of commitment or urgency.',
+ '- Preserve page-level uncertainty and do not infer private organizational roles from a single document.',
+ serializeContext(enrichedItems),
+ ].join('\n\n'),
+ diagnostics: {
+ errors,
+ evidenceCount: sourceCount,
+ failedCount: errors.length,
+ succeededCount:
+ 1 + settledContent.filter(({ status }) => status === 'fulfilled').length,
+ },
+ sourceCount,
+ };
+ },
+};
diff --git a/apps/server/src/services/understanding/sanitizer.ts b/apps/server/src/services/understanding/sanitizer.ts
index b667c28f6b8..896a2a25aac 100644
--- a/apps/server/src/services/understanding/sanitizer.ts
+++ b/apps/server/src/services/understanding/sanitizer.ts
@@ -51,6 +51,10 @@ const canonicalErrors: Record<string, { code: string; operation: string }> = {
operation: 'recent_repositories',
},
GMAIL_SEARCH_FAILED: { code: 'GMAIL_SEARCH_FAILED', operation: 'search' },
+ NOTION_PAGE_CONTENT_FAILED: {
+ code: 'NOTION_PAGE_CONTENT_FAILED',
+ operation: 'page_content',
+ },
UNDERSTANDING_PROVIDER_AUTHORIZATION_FAILED: {
code: 'UNDERSTANDING_PROVIDER_AUTHORIZATION_FAILED',
operation: 'authorize',
diff --git a/packages/builtin-agents/src/agents/onboarding-task-recommender/systemRole.ts b/packages/builtin-agents/src/agents/onboarding-task-recommender/systemRole.ts
index 2a4b12a01cd..c0452a4b1d0 100644
--- a/packages/builtin-agents/src/agents/onboarding-task-recommender/systemRole.ts
+++ b/packages/builtin-agents/src/agents/onboarding-task-recommender/systemRole.ts
@@ -6,7 +6,7 @@ Use only the structured connector evidence and provider guide supplied by the ru
Recommend concrete, useful tasks the user's Inbox agent can execute autonomously in the background. Prefer read, inspect, compare, summarize, prioritize, and prepare work that ends in a private deliverable such as a report, checklist, draft, or patch plan. Minimize interruptions: make conservative assumptions and record them, asking the user only when a consequential decision or new authorization is required.
-Do not recommend external side effects as part of the default execution. Sending, deleting, unsubscribing, archiving, changing mail labels, commenting on GitHub, submitting reviews, approving, merging, closing, labeling, or pushing require a later explicit user-approved action. GitHub evidence may identify the user as author, reviewer, owner, or participant; tailor the analysis to that relationship and never invent one.
+Do not recommend external side effects as part of the default execution. Sending, deleting, unsubscribing, archiving, changing mail labels, commenting on GitHub, submitting reviews, approving, merging, closing, labeling, pushing, or editing Notion pages and properties require a later explicit user-approved action. GitHub evidence may identify the user as author, reviewer, owner, or participant; tailor the analysis to that relationship and never invent one. Notion page access does not establish authorship, ownership, or responsibility.
Make every title distinguishable in a large cross-project task list by naming the relevant project, person, account, or business topic instead of repeating source-local feature shorthand. Write instructions with enough outcome, steps, private deliverable, and completion criteria to execute the task without reopening the source merely to understand the ask.
diff --git a/packages/connector-data/package.json b/packages/connector-data/package.json
index 4512ba6229a..c2d221dbc4e 100644
--- a/packages/connector-data/package.json
+++ b/packages/connector-data/package.json
@@ -15,6 +15,10 @@
"./gmail": {
"types": "./src/gmail/index.ts",
"default": "./src/gmail/index.ts"
+ },
+ "./notion": {
+ "types": "./src/notion/index.ts",
+ "default": "./src/notion/index.ts"
}
},
"main": "./src/index.ts",
diff --git a/packages/connector-data/src/errors.ts b/packages/connector-data/src/errors.ts
index b38b8b2c93a..dd3279e8c1e 100644
--- a/packages/connector-data/src/errors.ts
+++ b/packages/connector-data/src/errors.ts
@@ -1,5 +1,6 @@
-export type ConnectorDataProvider = 'github' | 'gmail';
+import type { ConnectorDataProvider } from './providers';
+/** Options used to create a sanitized Connector Data boundary error. */
export interface ConnectorDataErrorOptions {
code: string;
operation: string;
@@ -7,6 +8,7 @@ export interface ConnectorDataErrorOptions {
retryable: boolean;
}
+/** Sanitized provider error safe to propagate across connector collection boundaries. */
export class ConnectorDataError extends Error {
readonly code: string;
readonly operation: string;
diff --git a/packages/connector-data/src/index.ts b/packages/connector-data/src/index.ts
index 155d99c1a15..6508e8140fc 100644
--- a/packages/connector-data/src/index.ts
+++ b/packages/connector-data/src/index.ts
@@ -1,2 +1,3 @@
export * from './errors';
+export * from './providers';
export * from './retry';
diff --git a/packages/connector-data/src/notion/client.test.ts b/packages/connector-data/src/notion/client.test.ts
new file mode 100644
index 00000000000..21d55887729
--- /dev/null
+++ b/packages/connector-data/src/notion/client.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { ConnectorDataError } from '../errors';
+import { createNotionConnectorClient } from './client';
+
+const createClient = (
+ execute: ReturnType<typeof vi.fn>,
+ resolveVersion: ReturnType<typeof vi.fn> = vi.fn(async () => ({ version: '20260730_00' })),
+) =>
+ createNotionConnectorClient({
+ composio: { tools: { execute, getRawComposioToolBySlug: resolveVersion } },
+ connectedAccountId: 'notion-account',
+ userId: 'notion-owner',
+ });
+
+/** @example The Notion connector executes only bounded, version-pinned read operations. */
+describe('createNotionConnectorClient', () => {
+ /** @example Workspace directory and page Markdown calls use their documented Composio inputs. */
+ it('lists workspace items and reads page Markdown', async () => {
+ const execute = vi
+ .fn()
+ .mockResolvedValueOnce({
+ data: {
+ results: [
+ {
+ id: 'page-1',
+ object: 'page',
+ properties: { Name: { title: [{ plain_text: 'Roadmap' }] } },
+ },
+ ],
+ },
+ successful: true,
+ })
+ .mockResolvedValueOnce({ data: { markdown: '# Roadmap' }, successful: true });
+ const client = createClient(execute);
+
+ await expect(client.listItems({ maxResults: 500 })).resolves.toHaveLength(1);
+ await expect(client.getPageMarkdown('page-1')).resolves.toBe('# Roadmap');
+ expect(execute).toHaveBeenNthCalledWith(1, 'NOTION_FETCH_DATA', {
+ arguments: {
+ get_all: true,
+ get_databases: true,
+ get_pages: true,
+ page_size: 50,
+ },
+ connectedAccountId: 'notion-account',
+ userId: 'notion-owner',
+ version: '20260730_00',
+ });
+ expect(execute).toHaveBeenNthCalledWith(2, 'NOTION_GET_PAGE_MARKDOWN', {
+ arguments: { page_id: 'page-1' },
+ connectedAccountId: 'notion-account',
+ userId: 'notion-owner',
+ version: '20260730_00',
+ });
+ });
+
+ /** @example Each Notion tool resolves and caches its own explicit version. */
+ it('caches tool versions independently by slug', async () => {
+ const resolveVersion = vi.fn(async () => ({ version: '20260730_00' }));
+ const execute = vi.fn(async (toolSlug: string) =>
+ toolSlug === 'NOTION_FETCH_DATA'
+ ? { data: { results: [] }, successful: true }
+ : { data: { markdown: '# Page' }, successful: true },
+ );
+ const client = createClient(execute, resolveVersion);
+
+ await client.listItems();
+ await client.listItems();
+ await client.getPageMarkdown('page-1');
+ await client.getPageMarkdown('page-2');
+
+ expect(resolveVersion.mock.calls).toEqual([
+ ['NOTION_FETCH_DATA'],
+ ['NOTION_GET_PAGE_MARKDOWN'],
+ ]);
+ });
+
+ /** @example Failed tool executions expose sanitized connector errors without account details. */
+ it('sanitizes Composio execution failures', async () => {
+ const client = createClient(
+ vi.fn(async () => ({ error: 'token=secret notion-account', successful: false })),
+ );
+
+ const error = await client.listItems().catch((reason) => reason);
+ expect(error).toBeInstanceOf(ConnectorDataError);
+ expect(error).toMatchObject({ operation: 'listItems', provider: 'notion', retryable: false });
+ expect(error.message).not.toMatch(/secret|notion-account/);
+ });
+});
diff --git a/packages/connector-data/src/notion/client.ts b/packages/connector-data/src/notion/client.ts
new file mode 100644
index 00000000000..34b44c6c6c5
--- /dev/null
+++ b/packages/connector-data/src/notion/client.ts
@@ -0,0 +1,163 @@
+import { ConnectorDataError } from '../errors';
+import { createRecoverableMemo } from '../memo';
+import { withConnectorRetry } from '../retry';
+import { parseNotionItems, parseNotionPageMarkdown } from './parser';
+import type { NotionConnectorClient } from './types';
+
+const DEFAULT_MAX_RESULTS = 50;
+const MAX_QUERY_LENGTH = 500;
+const MAX_TOOL_VERSION_LENGTH = 64;
+const SAFE_TOOL_VERSION = /^[a-z0-9][\w.-]*$/i;
+const FETCH_DATA_TOOL_SLUG = 'NOTION_FETCH_DATA';
+const GET_PAGE_MARKDOWN_TOOL_SLUG = 'NOTION_GET_PAGE_MARKDOWN';
+
+/** Minimal Composio tools client needed by the read-only Notion connector. */
+export interface NotionComposioTools {
+ /** Executes a version-pinned Composio tool for one connected account. */
+ execute: (
+ toolSlug: string,
+ input: {
+ arguments: Record<string, unknown>;
+ connectedAccountId: string;
+ userId: string;
+ version: string;
+ },
+ ) => Promise<unknown>;
+ /** Resolves raw tool metadata when no explicit version was injected. */
+ getRawComposioToolBySlug?: (toolSlug: string) => Promise<unknown>;
+}
+
+/** Minimal Composio client accepted by {@link createNotionConnectorClient}. */
+export interface NotionComposioClient {
+ tools: NotionComposioTools;
+}
+
+/** Options for creating a user-scoped Notion connector client. */
+export interface CreateNotionConnectorClientOptions {
+ /** Composio SDK client used for version discovery and tool execution. */
+ composio: NotionComposioClient;
+ /** Connected account authorized for the target Notion workspace. */
+ connectedAccountId: string;
+ /** Optional pinned toolkit version, primarily useful in deterministic tests. */
+ toolVersion?: string;
+ /** Composio entity that owns the connected account. */
+ userId: string;
+}
+
+const readToolVersion = (value: unknown): string | undefined => {
+ if (typeof value !== 'string') return;
+ if (
+ value.length > MAX_TOOL_VERSION_LENGTH ||
+ !SAFE_TOOL_VERSION.test(value) ||
+ value.toLowerCase() === 'latest'
+ ) {
+ return;
+ }
+ return value;
+};
+
+/**
+ * Creates a bounded, read-only Notion client over Composio tools.
+ *
+ * Use when:
+ * - Understanding needs workspace structure and selected page content
+ * - Task recommendation needs trusted Notion page evidence
+ *
+ * Expects:
+ * - An ACTIVE connected account owned by `userId`
+ * - Composio tool metadata exposes explicit versions when `toolVersion` is omitted
+ *
+ * Returns:
+ * - A client that normalizes SDK response variants and sanitizes failures
+ */
+export const createNotionConnectorClient = ({
+ composio,
+ connectedAccountId,
+ toolVersion,
+ userId,
+}: CreateNotionConnectorClientOptions): NotionConnectorClient => {
+ const toolVersions = new Map<string, () => Promise<string>>();
+ const getToolVersion = (toolSlug: string) => {
+ const existing = toolVersions.get(toolSlug);
+ if (existing) return existing();
+ const resolver = createRecoverableMemo(async () => {
+ const configured = readToolVersion(toolVersion);
+ if (configured) return configured;
+ const tool = await composio.tools.getRawComposioToolBySlug?.(toolSlug);
+ const discovered =
+ typeof tool === 'object' && tool !== null && 'version' in tool
+ ? readToolVersion(tool.version)
+ : undefined;
+ if (discovered) return discovered;
+ throw new ConnectorDataError({
+ code: 'notion_tool_version_unavailable',
+ operation: 'resolveToolVersion',
+ provider: 'notion',
+ retryable: false,
+ });
+ });
+ toolVersions.set(toolSlug, resolver);
+ return resolver();
+ };
+
+ const execute = async (toolSlug: string, operation: string, arguments_: Record<string, unknown>) =>
+ withConnectorRetry(
+ async () => {
+ const response = await composio.tools.execute(toolSlug, {
+ arguments: arguments_,
+ connectedAccountId,
+ userId,
+ version: await getToolVersion(toolSlug),
+ });
+ if (
+ typeof response !== 'object' ||
+ response === null ||
+ !('successful' in response) ||
+ response.successful !== true
+ ) {
+ throw new ConnectorDataError({
+ code: `notion_${operation}_failed`,
+ operation,
+ provider: 'notion',
+ retryable: false,
+ });
+ }
+ return response;
+ },
+ { code: `notion_${operation}_failed`, operation, provider: 'notion' },
+ );
+
+ return {
+ getPageMarkdown: async (pageId) => {
+ const response = await execute(GET_PAGE_MARKDOWN_TOOL_SLUG, 'getPageMarkdown', {
+ page_id: pageId.slice(0, 128),
+ });
+ return parseNotionPageMarkdown(response);
+ },
+ listItems: async ({ maxResults = DEFAULT_MAX_RESULTS, query } = {}) => {
+ const finiteMaxResults = Number.isFinite(maxResults) ? maxResults : DEFAULT_MAX_RESULTS;
+ const boundedMaxResults = Math.min(
+ Math.max(1, Math.floor(finiteMaxResults)),
+ DEFAULT_MAX_RESULTS,
+ );
+ const normalizedQuery = query?.trim().slice(0, MAX_QUERY_LENGTH);
+ const response = await execute(FETCH_DATA_TOOL_SLUG, 'listItems', {
+ get_all: true,
+ get_databases: true,
+ get_pages: true,
+ page_size: boundedMaxResults,
+ ...(normalizedQuery ? { query: normalizedQuery } : {}),
+ });
+ const items = parseNotionItems(response, boundedMaxResults);
+ if (!items) {
+ throw new ConnectorDataError({
+ code: 'notion_response_invalid',
+ operation: 'listItems',
+ provider: 'notion',
+ retryable: false,
+ });
+ }
+ return items;
+ },
+ };
+};
diff --git a/packages/connector-data/src/notion/index.ts b/packages/connector-data/src/notion/index.ts
new file mode 100644
index 00000000000..14a3e3404f8
--- /dev/null
+++ b/packages/connector-data/src/notion/index.ts
@@ -0,0 +1,3 @@
+export * from './client';
+export * from './parser';
+export * from './types';
diff --git a/packages/connector-data/src/notion/parser.test.ts b/packages/connector-data/src/notion/parser.test.ts
new file mode 100644
index 00000000000..d36dc4872f3
--- /dev/null
+++ b/packages/connector-data/src/notion/parser.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseNotionItems, parseNotionPageMarkdown } from './parser';
+
+/** @example Composio Notion responses become bounded, source-addressable evidence. */
+describe('Notion response parsers', () => {
+ /** @example Native page and database records retain titles, properties, edit times, and URLs. */
+ it('normalizes wrapped Notion directory records', () => {
+ expect(
+ parseNotionItems(
+ {
+ data: {
+ results: [
+ {
+ id: '12345678-1234-1234-1234-123456789abc',
+ last_edited_time: '2026-08-01T00:00:00.000Z',
+ object: 'page',
+ properties: {
+ Name: { title: [{ plain_text: 'Launch plan' }], type: 'title' },
+ Status: { type: 'status' },
+ },
+ },
+ {
+ id: 'database-1',
+ object: 'database',
+ properties: {},
+ title: [{ plain_text: 'Projects' }],
+ url: 'https://www.notion.so/database-1',
+ },
+ ],
+ },
+ successful: true,
+ },
+ 10,
+ ),
+ ).toEqual([
+ {
+ id: '12345678-1234-1234-1234-123456789abc',
+ kind: 'page',
+ lastEditedAt: '2026-08-01T00:00:00.000Z',
+ propertyNames: ['Name', 'Status'],
+ sourceUrl: 'https://www.notion.so/12345678123412341234123456789abc',
+ title: 'Launch plan',
+ },
+ {
+ id: 'database-1',
+ kind: 'database',
+ propertyNames: [],
+ sourceUrl: 'https://www.notion.so/database-1',
+ title: 'Projects',
+ },
+ ]);
+ });
+
+ /** @example A non-empty malformed collection is rejected instead of becoming empty evidence. */
+ it('rejects a collection whose records cannot be normalized', () => {
+ expect(parseNotionItems({ data: { results: [{ unexpected: true }] } }, 10)).toBeUndefined();
+ });
+
+ /** @example Nested page Markdown is extracted without exposing execution wrapper fields. */
+ it('extracts nested Notion page Markdown', () => {
+ expect(
+ parseNotionPageMarkdown({ result: { data: { markdown: '# Launch\n- [ ] Ship' } } }),
+ ).toBe('# Launch\n- [ ] Ship');
+ });
+});
diff --git a/packages/connector-data/src/notion/parser.ts b/packages/connector-data/src/notion/parser.ts
new file mode 100644
index 00000000000..1443e5950d5
--- /dev/null
+++ b/packages/connector-data/src/notion/parser.ts
@@ -0,0 +1,158 @@
+import { toRecord } from '@lobechat/utils/object';
+
+import type { NotionItem } from './types';
+
+const MAX_ITEM_ID_LENGTH = 128;
+const MAX_MARKDOWN_LENGTH = 32_000;
+const MAX_PROPERTY_COUNT = 32;
+const MAX_PROPERTY_NAME_LENGTH = 160;
+const MAX_TITLE_LENGTH = 500;
+const MAX_URL_LENGTH = 2048;
+
+const executionWrappers = ['data', 'result', 'response'] as const;
+const collectionKeys = ['results', 'items', 'pages', 'databases'] as const;
+
+const boundedString = (value: unknown, limit: number): string | undefined => {
+ if (typeof value !== 'string') return;
+ const normalized = value.trim().slice(0, limit);
+ return normalized || undefined;
+};
+
+const readRichText = (value: unknown): string | undefined => {
+ if (!Array.isArray(value)) return;
+ const text = value
+ .slice(0, 32)
+ .flatMap((entry) => {
+ const record = toRecord(entry);
+ const nestedText = toRecord(record?.text);
+ const content = record?.plain_text ?? nestedText?.content;
+ return typeof content === 'string' ? [content] : [];
+ })
+ .join(' ');
+ return boundedString(text, MAX_TITLE_LENGTH);
+};
+
+const readTitle = (record: Record<string, unknown>): string => {
+ const direct = boundedString(record.title ?? record.name, MAX_TITLE_LENGTH);
+ if (direct) return direct;
+
+ const databaseTitle = readRichText(record.title);
+ if (databaseTitle) return databaseTitle;
+
+ const properties = toRecord(record.properties);
+ if (properties) {
+ for (const [propertyName, value] of Object.entries(properties).slice(0, MAX_PROPERTY_COUNT)) {
+ const property = toRecord(value);
+ const richTitle = readRichText(property?.title);
+ if (richTitle) return richTitle;
+ if (property?.type === 'title') {
+ const fallback = boundedString(propertyName, MAX_TITLE_LENGTH);
+ if (fallback) return fallback;
+ }
+ }
+ }
+ return 'Untitled';
+};
+
+const readCollection = (value: unknown): unknown[] | undefined => {
+ const queue: Array<{ depth: number; value: unknown }> = [{ depth: 0, value }];
+
+ // Composio SDK versions wrap tool data differently. Traverse only known execution wrappers and
+ // stop at a shallow depth so an untrusted page property named `results` cannot become a response.
+ while (queue.length > 0) {
+ const current = queue.shift()!;
+ const record = toRecord(current.value);
+ if (!record) continue;
+ for (const key of collectionKeys) {
+ if (Array.isArray(record[key])) return record[key] as unknown[];
+ }
+ if (Array.isArray(record.data)) return record.data;
+ if (current.depth >= 3) continue;
+ for (const key of executionWrappers) {
+ if (record[key] !== undefined) queue.push({ depth: current.depth + 1, value: record[key] });
+ }
+ }
+};
+
+/**
+ * Normalizes a Notion UUID for stable browser URLs.
+ *
+ * Before:
+ * - `12345678-1234-1234-1234-123456789abc`
+ *
+ * After:
+ * - `12345678123412341234123456789abc`
+ */
+const normalizeNotionIdForUrl = (id: string): string => id.replaceAll('-', '');
+
+/**
+ * Normalizes Composio Notion directory output into bounded connector records.
+ *
+ * Before:
+ * - `{ data: { results: [{ object: "page", id: "...", properties: { Name: { title: [...] } } }] } }`
+ *
+ * After:
+ * - `[{ kind: "page", id: "...", title: "...", sourceUrl: "https://www.notion.so/..." }]`
+ */
+export const parseNotionItems = (value: unknown, maxCandidates: number): NotionItem[] | undefined => {
+ const collection = readCollection(value);
+ if (!collection) return;
+ const finiteLimit = Number.isFinite(maxCandidates) ? Math.floor(maxCandidates) : 0;
+ const limit = Math.min(Math.max(0, finiteLimit), 100);
+ const items = new Map<string, NotionItem>();
+
+ for (const candidate of collection.slice(0, limit)) {
+ const record = toRecord(candidate);
+ const id = boundedString(record?.id, MAX_ITEM_ID_LENGTH);
+ if (!record || !id || items.has(id)) continue;
+ const rawKind = record.object ?? record.type;
+ const kind = rawKind === 'database' ? 'database' : rawKind === 'page' ? 'page' : undefined;
+ if (!kind) continue;
+ const properties = toRecord(record.properties);
+ const rawUrl = boundedString(record.url, MAX_URL_LENGTH);
+ const lastEditedAt = boundedString(
+ record.last_edited_time ?? record.lastEditedAt,
+ 64,
+ );
+ items.set(id, {
+ id,
+ kind,
+ ...(lastEditedAt ? { lastEditedAt } : {}),
+ propertyNames: properties
+ ? Object.keys(properties)
+ .slice(0, MAX_PROPERTY_COUNT)
+ .map((name) => name.trim().slice(0, MAX_PROPERTY_NAME_LENGTH))
+ .filter(Boolean)
+ : [],
+ sourceUrl: rawUrl ?? `https://www.notion.so/${normalizeNotionIdForUrl(id)}`,
+ title: readTitle(record),
+ });
+ }
+
+ if (collection.length > 0 && limit > 0 && items.size === 0) return;
+ return [...items.values()];
+};
+
+/**
+ * Normalizes Composio Notion page content into bounded Markdown.
+ *
+ * Before:
+ * - `{ data: { markdown: "# Project\n- [ ] Ship" } }`
+ *
+ * After:
+ * - `"# Project\n- [ ] Ship"`
+ */
+export const parseNotionPageMarkdown = (value: unknown): string | undefined => {
+ const queue: Array<{ depth: number; value: unknown }> = [{ depth: 0, value }];
+ while (queue.length > 0) {
+ const current = queue.shift()!;
+ const record = toRecord(current.value);
+ if (!record) continue;
+ const markdown = boundedString(record.markdown ?? record.content, MAX_MARKDOWN_LENGTH);
+ if (markdown) return markdown;
+ if (current.depth >= 3) continue;
+ for (const key of executionWrappers) {
+ if (record[key] !== undefined) queue.push({ depth: current.depth + 1, value: record[key] });
+ }
+ }
+};
diff --git a/packages/connector-data/src/notion/types.ts b/packages/connector-data/src/notion/types.ts
new file mode 100644
index 00000000000..283989a31cc
--- /dev/null
+++ b/packages/connector-data/src/notion/types.ts
@@ -0,0 +1,39 @@
+/** Minimal Notion page or database metadata retained as connector evidence. */
+export interface NotionItem {
+ /** Stable Notion object identifier. */
+ id: string;
+ /** Whether this object is a content page or database. */
+ kind: 'database' | 'page';
+ /** ISO timestamp of the latest known edit, when supplied by Notion. */
+ lastEditedAt?: string;
+ /** Bounded database/page property names that describe its structure. */
+ propertyNames: string[];
+ /** Stable Notion URL used to ground generated recommendations. */
+ sourceUrl: string;
+ /** Human-readable title derived from Notion rich text properties. */
+ title: string;
+}
+
+/** One Notion item enriched with bounded page Markdown when available. */
+export interface NotionItemContent {
+ /** Directory metadata returned by workspace search. */
+ item: NotionItem;
+ /** Bounded Notion-flavored Markdown for content analysis. */
+ markdown?: string;
+}
+
+/** Input for listing accessible Notion pages and databases. */
+export interface NotionListItemsInput {
+ /** Maximum normalized objects returned to the caller. */
+ maxResults?: number;
+ /** Optional title query accepted by Composio's Notion fetch tool. */
+ query?: string;
+}
+
+/** Read-only Notion client used by onboarding source collectors. */
+export interface NotionConnectorClient {
+ /** Fetches bounded page Markdown for one accessible page. */
+ getPageMarkdown: (pageId: string) => Promise<string | undefined>;
+ /** Lists bounded metadata for accessible workspace pages and databases. */
+ listItems: (input?: NotionListItemsInput) => Promise<NotionItem[]>;
+}
diff --git a/packages/connector-data/src/providers.ts b/packages/connector-data/src/providers.ts
new file mode 100644
index 00000000000..4482dba8cf2
--- /dev/null
+++ b/packages/connector-data/src/providers.ts
@@ -0,0 +1,24 @@
+/** Provider identifiers with a first-party Connector Data client. */
+export const CONNECTOR_DATA_PROVIDER_IDS = ['github', 'gmail', 'notion'] as const;
+
+/** Provider identifier accepted by Connector Data errors and client resolution. */
+export type ConnectorDataProvider = (typeof CONNECTOR_DATA_PROVIDER_IDS)[number];
+
+/** String-keyed lookup that lets external identifiers be checked without unsafe casts. */
+const connectorDataProviderIdSet: ReadonlySet<string> = new Set(CONNECTOR_DATA_PROVIDER_IDS);
+
+/**
+ * Checks whether an arbitrary identifier has a first-party Connector Data client.
+ *
+ * Use when:
+ * - A caller receives provider identifiers from a registry or persisted session
+ * - Unsupported connector identifiers must be ignored without casting
+ *
+ * Expects:
+ * - A normalized connector identifier
+ *
+ * Returns:
+ * - Whether the identifier is a supported {@link ConnectorDataProvider}
+ */
+export const isConnectorDataProvider = (value: string): value is ConnectorDataProvider =>
+ connectorDataProviderIdSet.has(value);
diff --git a/packages/connector-data/src/retry.ts b/packages/connector-data/src/retry.ts
index 578c2a37315..a9cbb543b48 100644
--- a/packages/connector-data/src/retry.ts
+++ b/packages/connector-data/src/retry.ts
@@ -1,5 +1,6 @@
-import type { ConnectorDataErrorOptions, ConnectorDataProvider } from './errors';
+import type { ConnectorDataErrorOptions } from './errors';
import { ConnectorDataError } from './errors';
+import type { ConnectorDataProvider } from './providers';
const DEFAULT_ATTEMPTS = 3;
const FIRST_RETRY_DELAY_MS = 250;
diff --git a/packages/prompts/src/chains/onboardingTaskRecommendation.test.ts b/packages/prompts/src/chains/onboardingTaskRecommendation.test.ts
index 5be6f66a9bc..ccd4285e718 100644
--- a/packages/prompts/src/chains/onboardingTaskRecommendation.test.ts
+++ b/packages/prompts/src/chains/onboardingTaskRecommendation.test.ts
@@ -44,4 +44,19 @@ describe('chainOnboardingTaskRecommendation', () => {
'require a later explicit user-approved action',
);
});
+
+ /** @example Notion guidance treats page access as evidence rather than edit authorization. */
+ it('keeps Notion recommendations read-only by default', () => {
+ const notion = DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG.providers.notion;
+ const principles = notion.principles.join('\n');
+
+ expect(principles).toContain('does not establish that the user authored');
+ expect(principles).toContain('Never edit pages');
+ expect(notion.staleWorkspacePrinciples.join('\n')).toContain(
+ 'centered on coverage and freshness',
+ );
+ expect(notion.staleWorkspacePrinciples.join('\n')).toContain(
+ 'Never claim that newer or unauthorized pages exist',
+ );
+ });
});
diff --git a/packages/prompts/src/chains/onboardingTaskRecommendation.ts b/packages/prompts/src/chains/onboardingTaskRecommendation.ts
index 89c632ebd76..806063034a6 100644
--- a/packages/prompts/src/chains/onboardingTaskRecommendation.ts
+++ b/packages/prompts/src/chains/onboardingTaskRecommendation.ts
@@ -1,4 +1,5 @@
-export type OnboardingTaskRecommendationProviderId = 'github' | 'gmail';
+/** Connector identifier supplied by a registered task recommendation provider. */
+export type OnboardingTaskRecommendationProviderId = string;
/** Provider-specific examples and safety rules used to recommend onboarding tasks. */
export interface OnboardingTaskRecommendationProviderGuide {
@@ -18,6 +19,12 @@ export interface OnboardingTaskRecommendationWritingGuide {
titlePrinciples: readonly string[];
}
+/** Provider prompt configuration with optional policies activated by trusted runtime conditions. */
+interface OnboardingTaskRecommendationProviderPromptConfig extends OnboardingTaskRecommendationProviderGuide {
+ /** Writing policy used when a Notion collector establishes a stale-dominant bounded scan. */
+ staleWorkspacePrinciples?: readonly string[];
+}
+
interface OnboardingTaskRecommendationPromptInput {
context: string;
guide: OnboardingTaskRecommendationProviderGuide;
@@ -94,6 +101,26 @@ export const DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG = {
'Prefer direct and important mail over promotions, except for an explicit subscription-cleanup task.',
],
},
+ notion: {
+ examples: [
+ 'Title: Prepare the next launch checklist from the Product Launch page. Instruction: Read the linked Notion page in the background, group its unchecked items by dependency and owner evidence, and return a private prioritized checklist with ambiguous ownership called out. Do not edit the page, check boxes, assign people, or post comments.',
+ 'Title: Review unresolved decisions in the API redesign notes. Instruction: Inspect the linked planning page, extract TODO, TBD, and decision markers with their surrounding context, and return a private decision brief that separates confirmed choices from open questions. Do not modify the document or notify collaborators.',
+ 'Title: Assess whether the dormant onboarding runbook needs refresh. Instruction: Compare the linked page’s last-edit date, structure, and visible content, then return a private maintenance assessment with stale sections and a proposed review plan. Treat age as a review signal rather than proof that the page is obsolete, and do not edit or archive it.',
+ ],
+ principles: [
+ 'Prefer pages with explicit unchecked tasks, TODO or TBD markers, decision notes, or concrete maintenance signals over generic recently edited documents.',
+ 'A page being accessible does not establish that the user authored, owns, or is responsible for it.',
+ 'Treat old pages as review opportunities, not proof that content is obsolete or work is overdue.',
+ 'Default to read-only work that returns a private checklist, decision brief, synthesis, or maintenance plan. Never edit pages, check tasks, change properties, comment, mention collaborators, move, duplicate, or archive content without later explicit user approval.',
+ ],
+ staleWorkspacePrinciples: [
+ 'The runtime has established that the bounded accessible Notion scan is dominated by items older than the configured freshness threshold. Return exactly one recommendation, centered on coverage and freshness rather than the subject matter of the old pages.',
+ 'A small minority of recently edited items does not by itself prove that the old subject matter is current. A recent item may be a hub, index, or access-related page; treat current work as unknown unless the supplied evidence explicitly establishes it.',
+ 'Do not turn old TODOs, unchecked boxes, decisions, or technical topics into current execution work. Their age makes current ownership, priority, and validity unknown until the user reviews them.',
+ 'The recommendation must produce a private coverage summary and a short user-facing checklist to verify the Notion workspace, account, integration, page, and Teamspace access; look for or authorize more recent pages; and only then decide which old pages to refresh, retain, or archive.',
+ 'Describe incomplete authorization only as a possibility. Never claim that newer or unauthorized pages exist, and never ask the agent to bypass Notion access controls.',
+ ],
+ },
},
writing: {
instructionPrinciples: [
@@ -114,10 +141,7 @@ export const DEFAULT_ONBOARDING_TASK_RECOMMENDATION_PROMPT_CONFIG = {
],
},
} as const satisfies {
- providers: Record<
- OnboardingTaskRecommendationProviderId,
- OnboardingTaskRecommendationProviderGuide
- >;
+ providers: Record<string, OnboardingTaskRecommendationProviderPromptConfig>;
writing: OnboardingTaskRecommendationWritingGuide;
};
diff --git a/packages/types/src/user/onboardingTasks.ts b/packages/types/src/user/onboardingTasks.ts
index ccf8f22ef8b..4099382f2a0 100644
--- a/packages/types/src/user/onboardingTasks.ts
+++ b/packages/types/src/user/onboardingTasks.ts
@@ -4,6 +4,8 @@ import { z } from 'zod';
export interface OnboardingTaskSource {
/** Email subject retained from trusted connector evidence when the source is Gmail. */
subject?: string;
+ /** Human-readable source title retained from trusted connector evidence. */
+ title?: string;
/** Connector kind used by the client to render provider-specific source metadata. */
type: string;
/** Exact connector URL retained from collected evidence. */
@@ -93,6 +95,7 @@ const recommendationSchema = z
z
.object({
subject: z.string().trim().min(1).max(500).optional(),
+ title: z.string().trim().min(1).max(500).optional(),
type: z.string().trim().min(1).max(128),
url: z.string().trim().min(1).max(2048),
})