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(cli): add migrate openclaw command (#13566)

Arvin Xu14cd81b6242d
diff --git a/apps/cli/man/man1/lh.1 b/apps/cli/man/man1/lh.1
index a91439fdd26..16bc61cf299 100644
--- a/apps/cli/man/man1/lh.1
+++ b/apps/cli/man/man1/lh.1
@@ -1,6 +1,6 @@
.\" Code generated by `npm run man:generate`; DO NOT EDIT.
.\" Manual command details come from the Commander command tree.
-.TH LH 1 "" "@lobehub/cli 0.0.1\-canary.15" "User Commands"
+.TH LH 1 "" "@lobehub/cli 0.0.3" "User Commands"
.SH NAME
lh \- LobeHub CLI \- manage and connect to LobeHub services
.SH SYNOPSIS
@@ -115,6 +115,9 @@ View usage statistics
.TP
.B eval
Manage evaluation workflows
+.TP
+.B migrate
+Migrate data from external tools (OpenClaw, ChatGPT, Claude, etc.)
.SH OPTIONS
.TP
.B \-V, \-\-version
diff --git a/apps/cli/package.json b/apps/cli/package.json
index 8f754b13e4f..fb74908b4cc 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@lobehub/cli",
- "version": "0.0.1-canary.15",
+ "version": "0.0.3",
"type": "module",
"bin": {
"lh": "./dist/index.js",
@@ -27,6 +27,9 @@
"test:coverage": "bunx vitest run --config vitest.config.mts --coverage",
"type-check": "tsc --noEmit"
},
+ "dependencies": {
+ "ignore": "^7.0.5"
+ },
"devDependencies": {
"@lobechat/device-gateway-client": "workspace:*",
"@lobechat/local-file-shell": "workspace:*",
diff --git a/apps/cli/src/api/client.ts b/apps/cli/src/api/client.ts
index c54c15302d4..8e21cd8eef2 100644
--- a/apps/cli/src/api/client.ts
+++ b/apps/cli/src/api/client.ts
@@ -39,7 +39,9 @@ async function getAuthAndServer() {
const result = await getValidToken();
if (!result) {
- log.error(`No authentication found. Run 'lh login' first, or set ${CLI_API_KEY_ENV}.`);
+ log.error(
+ `No authentication found. Run 'lh login' (or 'npx -y @lobehub/cli login') first, or set ${CLI_API_KEY_ENV}.`,
+ );
process.exit(1);
}
diff --git a/apps/cli/src/commands/migrate/index.ts b/apps/cli/src/commands/migrate/index.ts
new file mode 100644
index 00000000000..981bfabbbf9
--- /dev/null
+++ b/apps/cli/src/commands/migrate/index.ts
@@ -0,0 +1,11 @@
+import type { Command } from 'commander';
+
+import { registerOpenClawMigration } from './openclaw';
+
+export function registerMigrateCommand(program: Command) {
+ const migrate = program
+ .command('migrate')
+ .description('Migrate data from external tools (OpenClaw, ChatGPT, Claude, etc.)');
+
+ registerOpenClawMigration(migrate);
+}
diff --git a/apps/cli/src/commands/migrate/openclaw.test.ts b/apps/cli/src/commands/migrate/openclaw.test.ts
new file mode 100644
index 00000000000..14c382a9bab
--- /dev/null
+++ b/apps/cli/src/commands/migrate/openclaw.test.ts
@@ -0,0 +1,588 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+// โ”€โ”€ Mocks โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+const { mockTrpcClient } = vi.hoisted(() => ({
+ mockTrpcClient: {
+ agent: {
+ createAgent: { mutate: vi.fn() },
+ getBuiltinAgent: { query: vi.fn() },
+ },
+ agentDocument: {
+ upsertDocument: { mutate: vi.fn() },
+ },
+ },
+}));
+
+const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({
+ getTrpcClient: vi.fn(),
+}));
+
+const { mockConfirm } = vi.hoisted(() => ({
+ mockConfirm: vi.fn(),
+}));
+
+vi.mock('../../api/client', () => ({
+ getTrpcClient: mockGetTrpcClient,
+}));
+
+vi.mock('../../settings', () => ({
+ resolveServerUrl: () => 'https://app.lobehub.com',
+}));
+
+vi.mock('../../utils/format', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ return { ...actual, confirm: mockConfirm };
+});
+
+vi.mock('../../utils/logger', () => ({
+ log: {
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ },
+ setVerbose: vi.fn(),
+}));
+
+// eslint-disable-next-line import-x/first
+import { log } from '../../utils/logger';
+// eslint-disable-next-line import-x/first
+import { registerOpenClawMigration } from './openclaw';
+
+// โ”€โ”€ Helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+let tmpDir: string;
+
+function createProgram() {
+ const program = new Command();
+ program.exitOverride();
+ const migrate = program.command('migrate');
+ registerOpenClawMigration(migrate);
+ return program;
+}
+
+function writeFile(relativePath: string, content: string) {
+ const fullPath = path.join(tmpDir, relativePath);
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true });
+ fs.writeFileSync(fullPath, content);
+}
+
+// โ”€โ”€ Setup / teardown โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+let exitSpy: ReturnType<typeof vi.spyOn>;
+let consoleSpy: ReturnType<typeof vi.spyOn>;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'openclaw-test-'));
+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {
+ throw new Error('process.exit');
+ }) as any);
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
+ mockConfirm.mockResolvedValue(true);
+});
+
+afterEach(() => {
+ exitSpy.mockRestore();
+ consoleSpy.mockRestore();
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+// โ”€โ”€ Tests โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+describe('migrate openclaw', () => {
+ // โ”€โ”€ Profile parsing โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ describe('agent profile from workspace', () => {
+ it('should read name, description, and emoji from IDENTITY.md', async () => {
+ writeFile(
+ 'IDENTITY.md',
+ ['# IDENTITY.md', '- **Name:** ้พ™่™พ', '- **Creature:** AI ๅŠฉๆ‰‹', '- **Emoji:** ๐Ÿฆž'].join(
+ '\n',
+ ),
+ );
+ writeFile('hello.md', 'hello');
+
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
+ mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--yes',
+ ]);
+
+ expect(mockTrpcClient.agent.createAgent.mutate).toHaveBeenCalledWith({
+ config: {
+ avatar: '๐Ÿฆž',
+ description: 'AI ๅŠฉๆ‰‹',
+ title: '้พ™่™พ',
+ },
+ });
+ });
+
+ it('should filter out placeholder emoji like ๏ผˆๅพ…ๅฎš๏ผ‰', async () => {
+ writeFile(
+ 'IDENTITY.md',
+ ['# IDENTITY.md', '- **Name:** TestBot', '- **Emoji:**', ' _(ๅพ…ๅฎš)_'].join('\n'),
+ );
+ writeFile('hello.md', 'hello');
+
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
+ mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--yes',
+ ]);
+
+ expect(mockTrpcClient.agent.createAgent.mutate).toHaveBeenCalledWith({
+ config: {
+ avatar: undefined,
+ description: undefined,
+ title: 'TestBot',
+ },
+ });
+ });
+
+ it('should fall back to "OpenClaw" when no identity files exist', async () => {
+ writeFile('doc.md', 'content');
+
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
+ mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--yes',
+ ]);
+
+ expect(mockTrpcClient.agent.createAgent.mutate).toHaveBeenCalledWith({
+ config: {
+ avatar: undefined,
+ description: undefined,
+ title: 'OpenClaw',
+ },
+ });
+ });
+ });
+
+ // โ”€โ”€ File filtering โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ describe('file collection and filtering', () => {
+ it('should exclude common directories like node_modules and .git', async () => {
+ writeFile('README.md', 'readme');
+ writeFile('node_modules/pkg/index.js', 'module');
+ writeFile('.git/config', 'git');
+ writeFile('.idea/workspace.xml', 'ide');
+
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
+ mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--yes',
+ ]);
+
+ expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledTimes(1);
+ expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ filename: 'README.md' }),
+ );
+ });
+
+ it('should exclude files matching glob patterns like *.pyc and *.log', async () => {
+ writeFile('main.py', 'print("hi")');
+ writeFile('main.pyc', 'bytecode');
+ writeFile('app.log', 'log data');
+
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
+ mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--yes',
+ ]);
+
+ expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledTimes(1);
+ expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ filename: 'main.py' }),
+ );
+ });
+
+ it('should respect workspace .gitignore', async () => {
+ writeFile('.gitignore', 'secret.txt\ndata/\n');
+ writeFile('README.md', 'readme');
+ writeFile('secret.txt', 'password');
+ writeFile('data/dump.sql', 'sql');
+
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
+ mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--yes',
+ ]);
+
+ const filenames = mockTrpcClient.agentDocument.upsertDocument.mutate.mock.calls.map(
+ (c: any[]) => c[0].filename,
+ );
+ expect(filenames).toContain('README.md');
+ expect(filenames).not.toContain('secret.txt');
+ expect(filenames).not.toContain('data/dump.sql');
+ });
+
+ it('should skip binary files during import', async () => {
+ writeFile('readme.md', 'text content');
+ // Write a file with null bytes (binary)
+ const binPath = path.join(tmpDir, 'image.dat');
+ fs.writeFileSync(binPath, Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00, 0x00, 0x01]));
+
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
+ mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--yes',
+ ]);
+
+ // Only the text file should be upserted
+ expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledTimes(1);
+ expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ filename: 'readme.md' }),
+ );
+ // Binary file should show as skipped in output
+ const allOutput = consoleSpy.mock.calls.map((c: any[]) => c[0]).join('\n');
+ expect(allOutput).toContain('skipped');
+ });
+
+ it('should exclude database files by extension', async () => {
+ writeFile('data.md', 'notes');
+ writeFile('local.sqlite', 'fake-sqlite');
+ writeFile('app.db', 'fake-db');
+
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
+ mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--yes',
+ ]);
+
+ expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledTimes(1);
+ expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ filename: 'data.md' }),
+ );
+ });
+
+ it('should collect files in subdirectories', async () => {
+ writeFile('docs/guide.md', 'guide');
+ writeFile('docs/api.md', 'api');
+
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
+ mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--yes',
+ ]);
+
+ const filenames = mockTrpcClient.agentDocument.upsertDocument.mutate.mock.calls
+ .map((c: any[]) => c[0].filename)
+ .sort();
+ expect(filenames).toEqual(['docs/api.md', 'docs/guide.md']);
+ });
+ });
+
+ // โ”€โ”€ Dry run โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ describe('--dry-run', () => {
+ it('should list files without calling API', async () => {
+ writeFile('file.md', 'content');
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--dry-run',
+ ]);
+
+ expect(mockGetTrpcClient).not.toHaveBeenCalled();
+ expect(mockTrpcClient.agent.createAgent.mutate).not.toHaveBeenCalled();
+ expect(mockTrpcClient.agentDocument.upsertDocument.mutate).not.toHaveBeenCalled();
+ expect(log.info).toHaveBeenCalledWith(expect.stringContaining('Dry run'));
+ });
+ });
+
+ // โ”€โ”€ Agent resolution โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ describe('agent resolution', () => {
+ it('should use --agent-id directly when provided', async () => {
+ writeFile('file.md', 'content');
+ mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--agent-id',
+ 'agt_existing',
+ '--yes',
+ ]);
+
+ expect(mockTrpcClient.agent.createAgent.mutate).not.toHaveBeenCalled();
+ expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agt_existing' }),
+ );
+ });
+
+ it('should resolve agent by --slug', async () => {
+ writeFile('file.md', 'content');
+ mockTrpcClient.agent.getBuiltinAgent.query.mockResolvedValue({ id: 'agt_inbox' });
+ mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--slug',
+ 'inbox',
+ '--yes',
+ ]);
+
+ expect(mockTrpcClient.agent.getBuiltinAgent.query).toHaveBeenCalledWith({ slug: 'inbox' });
+ expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agt_inbox' }),
+ );
+ });
+
+ it('should create a new agent by default', async () => {
+ writeFile('file.md', 'content');
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_new' });
+ mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--yes',
+ ]);
+
+ expect(mockTrpcClient.agent.createAgent.mutate).toHaveBeenCalledTimes(1);
+ expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'agt_new' }),
+ );
+ });
+ });
+
+ // โ”€โ”€ Confirmation โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ describe('confirmation', () => {
+ it('should cancel when user declines', async () => {
+ writeFile('file.md', 'content');
+ mockConfirm.mockResolvedValue(false);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'migrate', 'openclaw', '--source', tmpDir]);
+
+ expect(mockTrpcClient.agent.createAgent.mutate).not.toHaveBeenCalled();
+ expect(consoleSpy).toHaveBeenCalledWith('Cancelled.');
+ });
+
+ it('should skip confirmation with --yes', async () => {
+ writeFile('file.md', 'content');
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
+ mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--yes',
+ ]);
+
+ expect(mockConfirm).not.toHaveBeenCalled();
+ });
+ });
+
+ // โ”€โ”€ Error handling โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ describe('error handling', () => {
+ it('should exit when source path does not exist', async () => {
+ const program = createProgram();
+ await program
+ .parseAsync(['node', 'test', 'migrate', 'openclaw', '--source', '/nonexistent/path'])
+ .catch(() => {}); // process.exit throws
+
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('not found'));
+ });
+
+ it('should report failed files without aborting', async () => {
+ writeFile('a.md', 'ok');
+ writeFile('b.md', 'fail');
+
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
+ // Files are iterated in readdir order; mock first success then failure
+ mockTrpcClient.agentDocument.upsertDocument.mutate
+ .mockResolvedValueOnce({})
+ .mockRejectedValueOnce(new Error('upload error'));
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--yes',
+ ]);
+
+ expect(mockTrpcClient.agentDocument.upsertDocument.mutate).toHaveBeenCalledTimes(2);
+ const allOutput = consoleSpy.mock.calls.map((c: any[]) => c[0]).join('\n');
+ expect(allOutput).toContain('1 imported');
+ expect(allOutput).toContain('1 failed');
+ });
+
+ it('should show no files message for empty workspace', async () => {
+ // Only excluded items
+ writeFile('.git/config', 'git');
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--dry-run',
+ ]);
+
+ expect(log.info).toHaveBeenCalledWith('No files found in workspace.');
+ });
+ });
+
+ // โ”€โ”€ Output โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+
+ describe('output', () => {
+ it('should print agent URL on completion', async () => {
+ writeFile('file.md', 'content');
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_abc123' });
+ mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--yes',
+ ]);
+
+ const allOutput = consoleSpy.mock.calls.map((c: any[]) => c[0]).join('\n');
+ expect(allOutput).toContain('https://app.lobehub.com/agent/agt_abc123');
+ });
+
+ it('should show friendly completion message on success', async () => {
+ writeFile('file.md', 'content');
+ mockTrpcClient.agent.createAgent.mutate.mockResolvedValue({ agentId: 'agt_test' });
+ mockTrpcClient.agentDocument.upsertDocument.mutate.mockResolvedValue({});
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'migrate',
+ 'openclaw',
+ '--source',
+ tmpDir,
+ '--yes',
+ ]);
+
+ const allOutput = consoleSpy.mock.calls.map((c: any[]) => c[0]).join('\n');
+ expect(allOutput).toContain('Migration complete');
+ });
+ });
+});
diff --git a/apps/cli/src/commands/migrate/openclaw.ts b/apps/cli/src/commands/migrate/openclaw.ts
new file mode 100644
index 00000000000..182b75bf9d1
--- /dev/null
+++ b/apps/cli/src/commands/migrate/openclaw.ts
@@ -0,0 +1,466 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import type { Command } from 'commander';
+import ignore from 'ignore';
+import pc from 'picocolors';
+
+import type { TrpcClient } from '../../api/client';
+import { getTrpcClient } from '../../api/client';
+import { resolveServerUrl } from '../../settings';
+import { confirm } from '../../utils/format';
+import { log } from '../../utils/logger';
+
+const DEFAULT_AGENT_NAME = 'OpenClaw';
+
+// Files to look for agent identity (tried in order)
+const IDENTITY_FILES = ['IDENTITY.md', 'SOUL.md'];
+
+// Default ignore rules (gitignore syntax) applied when no .gitignore is found
+const DEFAULT_IGNORE_RULES = [
+ // VCS
+ '.git',
+ '.svn',
+ '.hg',
+
+ // OpenClaw internal
+ '.openclaw',
+
+ // OS artifacts
+ '.DS_Store',
+ 'Thumbs.db',
+ 'desktop.ini',
+
+ // IDE / editor
+ '.idea',
+ '.vscode',
+ '.fleet',
+ '.cursor',
+ '.zed',
+ '*.swp',
+ '*.swo',
+ '*~',
+
+ // Dependencies
+ 'node_modules',
+ '.pnp',
+ '.yarn',
+ 'bower_components',
+ 'vendor',
+ 'jspm_packages',
+
+ // Python
+ '.venv',
+ 'venv',
+ 'env',
+ '__pycache__',
+ '*.pyc',
+ '*.pyo',
+ '.mypy_cache',
+ '.ruff_cache',
+ '.pytest_cache',
+ '.tox',
+ '.eggs',
+ '*.egg-info',
+
+ // Ruby
+ '.bundle',
+
+ // Rust
+ 'target',
+
+ // Go
+ 'go.sum',
+
+ // Java / JVM
+ '.gradle',
+ '.m2',
+
+ // .NET
+ 'bin',
+ 'obj',
+ 'packages',
+
+ // Build / cache / output
+ '.cache',
+ '.parcel-cache',
+ '.next',
+ '.nuxt',
+ '.turbo',
+ '.output',
+ 'dist',
+ 'build',
+ 'out',
+ '.sass-cache',
+
+ // Env / secrets
+ '.env',
+ '.env.*',
+
+ // Test / coverage
+ 'coverage',
+ '.nyc_output',
+
+ // Infra
+ '.terraform',
+
+ // Temp
+ 'tmp',
+ '.tmp',
+
+ // Logs
+ '*.log',
+ 'logs',
+
+ // Databases
+ '*.sqlite',
+ '*.sqlite3',
+ '*.db',
+ '*.db-shm',
+ '*.db-wal',
+ '*.ldb',
+ '*.mdb',
+ '*.accdb',
+
+ // Archives / binaries
+ '*.zip',
+ '*.tar',
+ '*.tar.gz',
+ '*.tgz',
+ '*.gz',
+ '*.bz2',
+ '*.xz',
+ '*.rar',
+ '*.7z',
+ '*.jar',
+ '*.war',
+ '*.dll',
+ '*.so',
+ '*.dylib',
+ '*.exe',
+ '*.bin',
+ '*.o',
+ '*.a',
+ '*.lib',
+ '*.class',
+
+ // Images / media / fonts
+ '*.png',
+ '*.jpg',
+ '*.jpeg',
+ '*.gif',
+ '*.bmp',
+ '*.ico',
+ '*.webp',
+ '*.svg',
+ '*.mp3',
+ '*.mp4',
+ '*.wav',
+ '*.avi',
+ '*.mov',
+ '*.mkv',
+ '*.flac',
+ '*.ogg',
+ '*.pdf',
+ '*.woff',
+ '*.woff2',
+ '*.ttf',
+ '*.otf',
+ '*.eot',
+
+ // Lock files
+ 'package-lock.json',
+ 'yarn.lock',
+ 'pnpm-lock.yaml',
+ 'Gemfile.lock',
+ 'Cargo.lock',
+ 'poetry.lock',
+ 'composer.lock',
+];
+
+interface AgentProfile {
+ avatar?: string;
+ description?: string;
+ title: string;
+}
+
+/**
+ * Try to extract the agent name, description, and avatar emoji from
+ * IDENTITY.md or SOUL.md. Falls back to "OpenClaw" if neither file
+ * exists or parsing fails.
+ */
+function readAgentProfile(workspacePath: string): AgentProfile {
+ for (const filename of IDENTITY_FILES) {
+ const filePath = path.join(workspacePath, filename);
+ if (!fs.existsSync(filePath)) continue;
+
+ const content = fs.readFileSync(filePath, 'utf8');
+
+ // Try to extract **Name:** value
+ const nameMatch = content.match(/\*{0,2}Name:?\*{0,2}\s*(.+)/i);
+ const title = nameMatch ? nameMatch[1].trim() : DEFAULT_AGENT_NAME;
+
+ // Try to extract **Creature:** or **Vibe:** or **Description:** as description
+ const descMatch = content.match(/\*{0,2}(?:Creature|Vibe|Description):?\*{0,2}\s*(.+)/i);
+ const description = descMatch ? descMatch[1].trim() : undefined;
+
+ // Try to extract **Emoji:** value (single emoji)
+ const emojiMatch = content.match(/\*{0,2}Emoji:?\*{0,2}\s*(.+)/i);
+ const rawAvatar = emojiMatch ? emojiMatch[1].trim() : undefined;
+ // Filter out placeholder text like ๏ผˆๅพ…ๅฎš๏ผ‰, _(ๅพ…ๅฎš)_, (TBD), N/A, etc.
+ const isPlaceholder =
+ rawAvatar && /^[_*๏ผˆ(].*[)๏ผ‰_*]$|^(?:tbd|todo|n\/?a|none|ๅพ…ๅฎš|ๆœชๅฎš)$/i.test(rawAvatar);
+ const avatar = rawAvatar && !isPlaceholder ? rawAvatar : undefined;
+
+ return { avatar, description, title };
+ }
+
+ return { title: DEFAULT_AGENT_NAME };
+}
+
+/**
+ * Build an ignore filter for the workspace. Uses .gitignore if present,
+ * otherwise falls back to a comprehensive default rule set.
+ */
+function buildIgnoreFilter(workspacePath: string) {
+ const ig = ignore();
+
+ const gitignorePath = path.join(workspacePath, '.gitignore');
+ if (fs.existsSync(gitignorePath)) {
+ ig.add(fs.readFileSync(gitignorePath, 'utf8'));
+ }
+
+ // Always apply default rules on top
+ ig.add(DEFAULT_IGNORE_RULES);
+
+ return ig;
+}
+
+/**
+ * Recursively collect all files under `dir`, filtered by ignore rules.
+ * Returns paths relative to `baseDir`.
+ */
+function collectFiles(dir: string, baseDir: string, ig: ReturnType<typeof ignore>): string[] {
+ const results: string[] = [];
+
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const relativePath = path.relative(baseDir, path.join(dir, entry.name));
+
+ // Directories need a trailing slash for ignore to match correctly
+ const testPath = entry.isDirectory() ? `${relativePath}/` : relativePath;
+ if (ig.ignores(testPath)) continue;
+
+ const fullPath = path.join(dir, entry.name);
+
+ if (entry.isDirectory()) {
+ results.push(...collectFiles(fullPath, baseDir, ig));
+ } else if (entry.isFile()) {
+ results.push(relativePath);
+ }
+ }
+
+ return results;
+}
+
+/**
+ * Quick check: read the first 8KB and look for null bytes.
+ * If found, the file is likely binary and should be skipped.
+ */
+function isBinaryFile(filePath: string): boolean {
+ const fd = fs.openSync(filePath, 'r');
+ try {
+ const buf = Buffer.alloc(8192);
+ const bytesRead = fs.readSync(fd, buf, 0, 8192, 0);
+ for (let i = 0; i < bytesRead; i++) {
+ if (buf[i] === 0) return true;
+ }
+ return false;
+ } finally {
+ fs.closeSync(fd);
+ }
+}
+
+function formatAgentLabel(profile: AgentProfile): string {
+ return profile.avatar ? `${profile.avatar} ${profile.title}` : profile.title;
+}
+
+/**
+ * Resolve the target agent ID.
+ * Priority: --agent-id > --slug > create new agent from workspace profile.
+ */
+async function resolveAgentId(
+ client: TrpcClient,
+ opts: { agentId?: string; slug?: string },
+ profile: AgentProfile,
+): Promise<string> {
+ if (opts.agentId) return opts.agentId;
+
+ if (opts.slug) {
+ const agent = await client.agent.getBuiltinAgent.query({ slug: opts.slug });
+ if (!agent) {
+ log.error(`Agent not found for slug: ${opts.slug}`);
+ process.exit(1);
+ }
+ return agent.id;
+ }
+
+ const label = formatAgentLabel(profile);
+ log.info(`Creating new agent ${pc.bold(label)}...`);
+ const result = await client.agent.createAgent.mutate({
+ config: {
+ avatar: profile.avatar,
+ description: profile.description,
+ title: profile.title,
+ },
+ });
+
+ const id = result.agentId;
+ if (!id) {
+ log.error('Failed to create agent โ€” no agentId returned.');
+ process.exit(1);
+ }
+
+ console.log(`${pc.green('โœ“')} Agent created: ${pc.bold(label)}`);
+ return id;
+}
+
+export function registerOpenClawMigration(migrate: Command) {
+ migrate
+ .command('openclaw')
+ .description('Import OpenClaw workspace files as agent documents')
+ .option(
+ '--source <path>',
+ 'Path to OpenClaw workspace',
+ path.join(os.homedir(), '.openclaw', 'workspace'),
+ )
+ .option('--agent-id <id>', 'Import into an existing agent by ID')
+ .option('--slug <slug>', 'Import into an existing agent by slug (e.g. "inbox")')
+ .option('--dry-run', 'Preview files without importing')
+ .option('--yes', 'Skip confirmation prompt')
+ .action(
+ async (options: {
+ agentId?: string;
+ dryRun?: boolean;
+ slug?: string;
+ source: string;
+ yes?: boolean;
+ }) => {
+ // Check auth early so users don't scan files only to find out they're not logged in
+ if (!options.dryRun) {
+ await getTrpcClient();
+ }
+
+ const workspacePath = path.resolve(options.source);
+
+ // Validate source directory
+ if (!fs.existsSync(workspacePath)) {
+ log.error(`OpenClaw workspace not found: ${workspacePath}`);
+ process.exit(1);
+ }
+
+ if (!fs.statSync(workspacePath).isDirectory()) {
+ log.error(`Not a directory: ${workspacePath}`);
+ process.exit(1);
+ }
+
+ // Read agent profile from workspace identity files
+ const profile = readAgentProfile(workspacePath);
+ const label = formatAgentLabel(profile);
+
+ // Collect files (respects .gitignore + default rules)
+ const ig = buildIgnoreFilter(workspacePath);
+ const files = collectFiles(workspacePath, workspacePath, ig);
+
+ if (files.length === 0) {
+ log.info('No files found in workspace.');
+ return;
+ }
+
+ console.log(
+ `Found ${pc.bold(String(files.length))} file(s) in ${pc.dim(workspacePath)}:\n`,
+ );
+ for (const f of files) {
+ console.log(` ${pc.dim('โ€ข')} ${f}`);
+ }
+ console.log();
+
+ if (options.dryRun) {
+ log.info('Dry run โ€” no changes made.');
+ return;
+ }
+
+ // Confirm
+ if (!options.yes) {
+ const target = options.agentId
+ ? `agent ${pc.bold(options.agentId)}`
+ : options.slug
+ ? `agent slug "${pc.bold(options.slug)}"`
+ : `a new ${pc.bold(label)} agent`;
+ const confirmed = await confirm(
+ `Import ${files.length} file(s) as agent documents into ${target}?`,
+ );
+ if (!confirmed) {
+ console.log('Cancelled.');
+ return;
+ }
+ }
+
+ const client = await getTrpcClient();
+
+ // Create or reuse agent
+ const agentId = await resolveAgentId(client, options, profile);
+
+ console.log(`\nImporting to ${pc.bold(label)}...\n`);
+
+ let success = 0;
+ let failed = 0;
+
+ let skipped = 0;
+
+ for (const relativePath of files) {
+ const fullPath = path.join(workspacePath, relativePath);
+
+ try {
+ // Skip binary files that slipped through the extension filter
+ if (isBinaryFile(fullPath)) {
+ console.log(` ${pc.dim('โ—‹')} ${relativePath} ${pc.dim('(binary, skipped)')}`);
+ skipped++;
+ continue;
+ }
+
+ const content = fs.readFileSync(fullPath, 'utf8');
+ const stat = fs.statSync(fullPath);
+
+ await client.agentDocument.upsertDocument.mutate({
+ agentId,
+ content,
+ createdAt: stat.birthtime,
+ filename: relativePath,
+ updatedAt: stat.mtime,
+ });
+ console.log(` ${pc.green('โœ“')} ${relativePath}`);
+ success++;
+ } catch (err: any) {
+ console.log(` ${pc.red('โœ—')} ${relativePath} โ€” ${err.message || err}`);
+ failed++;
+ }
+ }
+
+ const agentUrl = `${resolveServerUrl()}/agent/${agentId}`;
+ const skippedInfo = skipped > 0 ? `, ${skipped} skipped` : '';
+ console.log();
+ if (failed === 0) {
+ console.log(
+ `${pc.green('โœ“')} Migration complete! ${pc.bold(String(success))} file(s) imported to ${pc.bold(label)}.${skippedInfo}`,
+ );
+ } else {
+ console.log(
+ `${pc.yellow('โš ')} Migration finished with issues: ${pc.bold(String(success))} imported, ${pc.red(String(failed))} failed${skippedInfo}.`,
+ );
+ }
+ console.log(`\n ${pc.dim('โ†’')} ${pc.underline(agentUrl)}`);
+ console.log();
+ },
+ );
+}
diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.ts
index 004ca90dd9c..721294b51e5 100644
--- a/apps/cli/src/program.ts
+++ b/apps/cli/src/program.ts
@@ -20,6 +20,7 @@ import { registerLogoutCommand } from './commands/logout';
import { registerManCommand } from './commands/man';
import { registerMemoryCommand } from './commands/memory';
import { registerMessageCommand } from './commands/message';
+import { registerMigrateCommand } from './commands/migrate';
import { registerModelCommand } from './commands/model';
import { registerPluginCommand } from './commands/plugin';
import { registerProviderCommand } from './commands/provider';
@@ -72,6 +73,7 @@ export function createProgram() {
registerUserCommand(program);
registerConfigCommand(program);
registerEvalCommand(program);
+ registerMigrateCommand(program);
return program;
}
diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.ts
index 1334dd2b597..aea5abfda42 100644
--- a/packages/database/src/models/agentDocuments/agentDocument.ts
+++ b/packages/database/src/models/agentDocuments/agentDocument.ts
@@ -94,6 +94,8 @@ export class AgentDocumentModel {
templateId?: string,
metadata?: Record<string, any>,
policy?: AgentDocumentPolicy,
+ createdAt?: Date,
+ updatedAt?: Date,
): Promise<AgentDocument> {
const title = filename.replace(/\.[^.]+$/, '');
const stats = this.getDocumentStats(content);
@@ -102,6 +104,7 @@ export class AgentDocumentModel {
return this.db.transaction(async (trx) => {
const documentPayload: NewDocument = {
content,
+ createdAt,
description: metadata?.description,
fileType: 'agent/document',
filename,
@@ -111,6 +114,7 @@ export class AgentDocumentModel {
title,
totalCharCount: stats.totalCharCount,
totalLineCount: stats.totalLineCount,
+ updatedAt: updatedAt ?? createdAt,
userId: this.userId,
};
@@ -126,6 +130,7 @@ export class AgentDocumentModel {
AgentAccess.DELETE,
accessShared: 0,
agentId,
+ createdAt,
policyLoad: PolicyLoad.ALWAYS,
deleteReason: null,
deletedAt: null,
@@ -138,6 +143,7 @@ export class AgentDocumentModel {
normalizedPolicy.context?.position || DocumentLoadPosition.BEFORE_FIRST_USER,
policyLoadRule: normalizedPolicy.context?.rule || DocumentLoadRule.ALWAYS,
templateId,
+ updatedAt: updatedAt ?? createdAt,
userId: this.userId,
};
@@ -315,6 +321,8 @@ export class AgentDocumentModel {
templateId?: string,
metadata?: Record<string, any>,
policy?: AgentDocumentPolicy,
+ createdAt?: Date,
+ updatedAt?: Date,
): Promise<AgentDocument> {
const existing = await this.findByFilename(agentId, filename);
@@ -339,6 +347,8 @@ export class AgentDocumentModel {
templateId,
metadata,
policy,
+ createdAt,
+ updatedAt,
);
}
diff --git a/src/server/routers/lambda/agentDocument.ts b/src/server/routers/lambda/agentDocument.ts
index 4f185c40874..f253867521c 100644
--- a/src/server/routers/lambda/agentDocument.ts
+++ b/src/server/routers/lambda/agentDocument.ts
@@ -85,16 +85,20 @@ export const agentDocumentRouter = router({
z.object({
agentId: z.string(),
content: z.string(),
+ createdAt: z.date().optional(),
filename: z.string(),
metadata: metadataSchema.optional(),
+ updatedAt: z.date().optional(),
}),
)
.mutation(async ({ ctx, input }) => {
return ctx.agentDocumentService.upsertDocument({
agentId: input.agentId,
content: input.content,
+ createdAt: input.createdAt,
filename: input.filename,
metadata: input.metadata,
+ updatedAt: input.updatedAt,
});
}),
diff --git a/src/server/services/agentDocuments.ts b/src/server/services/agentDocuments.ts
index d7efd8fb11c..5e18b584caa 100644
--- a/src/server/services/agentDocuments.ts
+++ b/src/server/services/agentDocuments.ts
@@ -20,12 +20,14 @@ const MAX_UNIQUE_FILENAME_ATTEMPTS = 1000;
interface UpsertDocumentParams {
agentId: string;
content: string;
+ createdAt?: Date;
filename: string;
loadPosition?: DocumentLoadPosition;
loadRules?: DocumentLoadRules;
metadata?: Record<string, any>;
policy?: AgentDocumentPolicy;
templateId?: string;
+ updatedAt?: Date;
}
/**
@@ -207,6 +209,8 @@ export class AgentDocumentsService {
templateId,
metadata,
policy,
+ createdAt,
+ updatedAt,
}: UpsertDocumentParams) {
return this.agentDocumentModel.upsert(
agentId,
@@ -217,6 +221,8 @@ export class AgentDocumentsService {
templateId,
metadata,
policy,
+ createdAt,
+ updatedAt,
);
}