Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(companions): preserve all native import definitions and resources
Chrisd379556ac287
diff --git a/apps/desktop/src/main/bot-import/README.md b/apps/desktop/src/main/bot-import/README.mdindex 2f3b826408..c011e12e24 100644--- a/apps/desktop/src/main/bot-import/README.md+++ b/apps/desktop/src/main/bot-import/README.md@@ -337,9 +337,11 @@ show saved/selected counts and distinguish partial imports from setup-only checkAn expandable, paginated detail list shows filenames, safe reasons and partialprogress. Chat remains available alongside retry. Idempotent chat notices distinguishpartial saves, pending setup and eventual completion without exposing raw exceptions.-An invalid automation definition reports the conversion failure before setup warnings;-valid definitions are saved disabled even when tool/model mapping is still pending. Native Heartbeat is omitted;-ordinary cron jobs named heartbeat are still imported.+Every source automation is preserved, including native Heartbeat and unsupported definitions.+Unconvertible schedules become disabled drafts with no trigger; unresolved issues+block both activation and manual execution. Full original definitions remain encrypted.+Empty memory markers and Heartbeat instructions are retained as well. Completeness+is audited against the source inventory, not just the converted selection count.The owner-scoped `companion_connections.import_setup` tool lists remaining checksin pages, retries from the encrypted checkpoint, and permits explicit adoption of@@ -471,7 +473,8 @@ saved disabled and execute as literal subprocess argv only after the existingverification and handover gates. They never start a model turn or inherit model/toolpolicy requirements. Read-only verification must verify their actual dependencies;it cannot accept a command as a simple local reminder. Native `heartbeat` payloads-are excluded, while ordinary jobs named heartbeat remain importable.+are preserved disabled with their schedule and original definition; native context+semantics remain explicitly pending, rather than being silently reduced to a reminder.Ordinary content/routine progress uses indexed checks and at most about 100 fullreceipt snapshots per pass, sized from the selected input. An interrupted batch@@ -498,3 +501,13 @@ old checkpoints that only contained a boolean link exception. Native commandargv, cwd and stdin are now opaque to the read planner, even when a literal secretis absent from every configured credential map; the original payload remains inlocal encrypted storage for authorized execution.++Full preservation also includes unused Hermes scripts, disabled MCP definitions,+empty marker bytes and UTF-8 text documents containing terminal control characters.+Native Python virtualenv interpreter aliases retain their original runtime targets only when `pyvenv.cfg`+declares their exact runtime home and the resolved target is a native executable.+Their captured bytes remain in the import checkpoint; native links preserve dynamic+library resolution when the skill is saved or temporarily materialized.+This grants no access to neighboring credentials or external directories. The+original virtualenv configuration and resource files stay intact; cross-machine+runtime availability is not implied by saving their definitions.diff --git a/apps/desktop/src/main/bot-import/__tests__/automationRuntime.test.ts b/apps/desktop/src/main/bot-import/__tests__/automationRuntime.test.tsindex 576ea554e8..334221176e 100644--- a/apps/desktop/src/main/bot-import/__tests__/automationRuntime.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/automationRuntime.test.ts@@ -42,8 +42,9 @@ it.skipIf(process.platform === 'win32')('executes the default imported script anconst selected = validateImportSelection({ requestId: 'script-subtree-fixture', previewId: 'preview', name: 'Ada', takeover: true, entryIds: snapshot.items.filter(item => item.view.selected).map(item => item.view.id) }, snapshot);const task = selected.find(item => item.automation)!;const assets = Object.fromEntries(selected.flatMap(item => item.asset ? [[item.asset.name, item.asset.bytes.toString('base64')]] : []));- expect(Object.keys(assets)).toHaveLength(6);- expect(assets['scripts/unrelated/unused.sh']).toBeUndefined();+ expect(Object.keys(assets)).toHaveLength(7);+ expect(assets['scripts/unrelated/unused.sh']).toBe(Buffer.from('exit 99').toString('base64'));+ expect(task.view.dependsOn).not.toContain(snapshot.items.find(item => item.asset?.name === 'scripts/unrelated/unused.sh')!.view.id);await shared.store.write(root, 'bot', { version: 1, env: {}, mcp: [], credentials: [], files: assets, automations: {routine: { kind: 'hermes', handover: 'ready', original: task.automation!.original, sourceRoot, deliveries: [] },} }, () => {});diff --git a/apps/desktop/src/main/bot-import/__tests__/files.test.ts b/apps/desktop/src/main/bot-import/__tests__/files.test.tsindex afdaee937c..02c1787514 100644--- a/apps/desktop/src/main/bot-import/__tests__/files.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/files.test.ts@@ -1,5 +1,6 @@import { expect, it, vi } from 'vitest';import { createImportBudget, deserializeImportSnapshot, readImportFile, readImportTree, serializeImportSnapshot, snapshotFingerprint } from '../files.js';+import { readImportSkillTree } from '../skills.js';import type { ImportSnapshot } from '../types.js';import { promises as fs } from 'node:fs';import os from 'node:os';@@ -115,3 +116,28 @@ it('retries a selected subtree inside its original root and still rejects escapeexpect(files.map(file => [file.name, file.bytes.toString()])).toEqual([['broken/note.md', 'Repaired']]);} finally { await fs.rm(root, { recursive: true, force: true }); }});++it('copies native venv interpreter aliases while keeping unrelated external links rejected', async ctx => {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-import-venv-'));+ try {+ const skill = path.join(root, 'skill'), runtime = path.join(root, 'runtime');+ const bin = path.join(skill, '.venv', 'bin');+ await fs.mkdir(bin, { recursive: true }); await fs.mkdir(runtime);+ await fs.writeFile(path.join(skill, 'SKILL.md'), '# Fixture');+ await fs.writeFile(path.join(skill, '.venv/pyvenv.cfg'), `home = ${runtime}\n`);+ const executable = Buffer.from('7f454c460102030405060708', 'hex');+ await fs.writeFile(path.join(runtime, 'python3.12'), executable, { mode: 0o700 });+ try { await fs.symlink(path.join(runtime, 'python3.12'), path.join(bin, 'python')); }+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'EPERM') { ctx.skip(); return; } throw error; }+ await fs.symlink('python', path.join(bin, 'python3'));+ const files = await readImportSkillTree(skill, undefined, createImportBudget());+ for (const name of ['.venv/bin/python', '.venv/bin/python3']) expect(files.find(file => file.name === name)).toMatchObject({ bytes: executable, interpreterLink: await fs.realpath(path.join(runtime, 'python3.12')) });+ expect(files.find(file => file.name === '.venv/pyvenv.cfg')?.bytes.toString()).toContain(runtime);+ await fs.writeFile(path.join(runtime, 'private.txt'), 'fixture-private-token');+ await fs.symlink(path.join(runtime, 'private.txt'), path.join(skill, 'credentials.txt'));+ await expect(readImportSkillTree(skill)).rejects.toThrow('SOURCE_LINK_OUTSIDE_FOLDER');+ await fs.unlink(path.join(skill, 'credentials.txt'));+ await fs.writeFile(path.join(runtime, 'python3.12'), 'fixture-private-token');+ await expect(readImportSkillTree(skill)).rejects.toThrow('SOURCE_LINK_OUTSIDE_FOLDER');+ } finally { await fs.rm(root, { recursive: true, force: true }); }+});diff --git a/apps/desktop/src/main/bot-import/__tests__/host.test.ts b/apps/desktop/src/main/bot-import/__tests__/host.test.tsindex 04a1529606..1583ddcd76 100644--- a/apps/desktop/src/main/bot-import/__tests__/host.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/host.test.ts@@ -75,6 +75,7 @@ import { decodeBotAvatarImage } from '../../localDb/ipc/botAvatarSelection.js';import { createCompanionConnectionsProvider } from '../connectionProvider.js';import { createImportSourceReader, discoverImportSources, inspectImportSource } from '../sources.js';import { verifyImportedAutomation } from '../verification.js';+import { normalizeAutomation } from '../sourceAutomations.js';beforeEach(async () => {h.root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-import-host-test-'));@@ -1189,6 +1190,7 @@ it('retries legacy text and empty memory assets without passing them to the mediexpect(result).toMatchObject({ status: 'complete', savedEntryIds: ['old-json', 'old-marker'] });expect(h.importDocument).toHaveBeenCalledOnce();expect(h.importDocument).toHaveBeenCalledWith(first.botId, expect.stringMatching(/^memory-[a-f0-9]{32}$/), 'memory/state.json', '{"cursor":7}\n', 'reference');+ expect((await h.store.read(h.root, first.botId, () => {}))?.files?.['memory/.report.sent']).toBe('');await startCompanionImport(selection, 'phone');expect(h.importDocument).toHaveBeenCalledOnce();});@@ -1220,3 +1222,28 @@ it('receives sparse selection chunks idempotently and starts only after the compexpect(createBotProfile).toHaveBeenCalledTimes(1);expect(h.importDocument).toHaveBeenCalledTimes(chosen.length);});++it('archives unsupported automation definitions and blocks both management and runtime execution', async () => {+ const original = { id: 'native', schedule: { kind: 'source-specific' }, payload: { kind: 'heartbeat' }, delivery: { channel: 'missing-channel', to: 'original-recipient' } };+ h.snapshot.source.kind = 'openclaw';+ const item = normalizeAutomation(h.snapshot.source, original, [], 'UTC');+ h.snapshot.items = [item];+ const [source] = await listCompanionImportSources('fixture');+ const preview = await previewCompanionImport(source!.id, 'fixture');+ const selection = { requestId: 'unsupported-original-task', previewId: preview.id, name: 'Ada', entryIds: [item.view.id], takeover: false, deferSetup: true };+ const accepted = await startCompanionImport(selection, 'fixture');+ const result = await withBotProfileLocks([accepted.botId], () => getCompanionImportResult(selection.requestId));+ expect(result).toMatchObject({ savedEntryIds: [item.view.id], status: 'needs-attention' });+ const env = await h.store.read(h.root, accepted.botId, () => {});+ expect(env?.sourceAutomations?.[0]?.original).toEqual(original);+ const routine = h.routines[0]!;+ expect(routine).toMatchObject({ enabled: false, triggers: [] });+ expect(env?.automations?.[routine.id]?.original).toEqual(original);+ await expect(assertImportedAutomationReady(h.root, accepted.botId, routine.id, () => {})).rejects.toThrow('AUTOMATION_TRIGGER_NEEDS_ADAPTER');+ await expect(prepareImportedAutomation(h.root, routine, 'run', new AbortController().signal, () => {})).rejects.toThrow('AUTOMATION_TRIGGER_NEEDS_ADAPTER');+ expect(h.pause).not.toHaveBeenCalled();+ expect(verifyImportedAutomation).not.toHaveBeenCalled();+ await startCompanionImport(selection, 'fixture');+ await withBotProfileLocks([accepted.botId], () => getCompanionImportResult(selection.requestId));+ expect(h.routines).toHaveLength(1);+});diff --git a/apps/desktop/src/main/bot-import/__tests__/process.test.ts b/apps/desktop/src/main/bot-import/__tests__/process.test.tsindex 7f7e859d95..0c4d455e8d 100644--- a/apps/desktop/src/main/bot-import/__tests__/process.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/process.test.ts@@ -4,10 +4,10 @@ import { previewImportRedactions } from '../environmentSelection.js';import { connectionRedactions, importedContentRedactions, redactImportedResult } from '../connectionCatalog.js';it('preserves native boolean switches, local bind addresses and transport/policy enums without exempting credentials', () => {- const env = { AWS_BEDROCK_FORCE_HTTP1: '1', BROWSERBASE_PROXIES: 'true', BROWSERBASE_ADVANCED_STEALTH: 'false',+ const env = { BLUEBUBBLES_SEND_READ_RECEIPTS: 'false', BLUEBUBBLES_WEBHOOK_HOST: '192.168.10.100', AWS_BEDROCK_FORCE_HTTP1: '1', BROWSERBASE_PROXIES: 'true', BROWSERBASE_ADVANCED_STEALTH: 'false',TELEGRAM_REQUIRE_MENTION: 'true', TELEGRAM_OBSERVE_UNMENTIONED_GROUP_MESSAGES: 'true', FEISHU_ALLOW_ALL_USERS: 'false',WEB_TOOLS_DEBUG: 'false', API_SERVER_HOST: '127.0.0.1', API_SERVER_PORT: '8080', FEISHU_CONNECTION_MODE: 'websocket', FEISHU_GROUP_POLICY: 'allowlist', FEISHU_BOT_NAME: 'Fixture', FEISHU_DOMAIN: 'feishu' };- const text = 'sys.exit(1) action="store_true" <path d="M1 1"/> false 127.0.0.1 8080 websocket allowlist Fixture feishu';+ const text = '192.168.10.100 sys.exit(1) action="store_true" <path d="M1 1"/> false 127.0.0.1 8080 websocket allowlist Fixture feishu';expect(redactEnvironmentValues(text, env)).toBe(text);expect(redactEnvironmentValues('1 true websocket', { ...env, API_KEY: '1', AUTH_ALLOW_DEBUG: 'true', SECRET_MODE: 'websocket' })).toBe('[API_KEY] [AUTH_ALLOW_DEBUG] [SECRET_MODE]');const secrets = importedContentRedactions({ env, mcp: [{ name: 'fixture', headers: { Authorization: 'Bearer true' } }], credentials: [] });@@ -62,7 +62,7 @@ it('preserves bounded ordinary settings even when deselected, while explicit samit('does not turn ordinary scalar settings or MCP endpoint names into content credentials', () => {const env = { SOME_FEATURE_ENABLED: 'true', RETRY_COUNT: '1', TEMPERATURE: '0.5' };const secrets = importedContentRedactions({ env, mcp: [{ name: 'native-mcp', url: 'http://localhost:9000/native-mcp?enabled=true&retry=1' }, { name: 'touchdesigner-mcp', url: 'http://localhost:9001/touchdesigner-mcp' }], credentials: [] });- const text = 'sys.exit(1) action="store_true" <path d="M1 0.5"/> native-mcp touchdesigner-mcp';+ const text = '192.168.10.100 sys.exit(1) action="store_true" <path d="M1 0.5"/> native-mcp touchdesigner-mcp';expect(redactEnvironmentValues(text, secrets)).toBe(text);expect(redactEnvironmentValues('secret=1', { API_KEY: '1' })).toBe('secret=[API_KEY]');});diff --git a/apps/desktop/src/main/bot-import/__tests__/skillResources.test.ts b/apps/desktop/src/main/bot-import/__tests__/skillResources.test.tsindex 8cc3b0e4a2..e3d86a76a7 100644--- a/apps/desktop/src/main/bot-import/__tests__/skillResources.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/skillResources.test.ts@@ -47,3 +47,16 @@ it('executes the preserved resource with credentials while keeping ordinary code}));expect(result).toEqual({ stdout: 'store_true\n', exitCode: 0 });});++it.skipIf(process.platform === 'win32')('retains and materializes native interpreter aliases without copying them into broken standalone executables', async () => {+ const files = [+ { name: 'SKILL.md', bytes: Buffer.from('# Native'), executable: false },+ { name: '.venv/bin/python', bytes: Buffer.from('native fixture'), executable: true, interpreterLink: '/fixture/native/python3' },+ ];+ const projected = projectImportedSkill(files, 'native', {});+ expect(projected.files).toEqual(files);+ expect(projected.originals?.[1]?.interpreterLink).toBe('/fixture/native/python3');+ await withImportedSkillResources({ version: 1, env: {}, mcp: [], credentials: [], skillFiles: { native: projected.originals! } }, () => {}, async env => {+ expect(await fs.readlink(path.join(env.CINDY_IMPORTED_SKILLS!, 'native/.venv/bin/python'))).toBe('/fixture/native/python3');+ });+});diff --git a/apps/desktop/src/main/bot-import/__tests__/sources.test.ts b/apps/desktop/src/main/bot-import/__tests__/sources.test.tsindex 8a5ee5d95d..71d73f4c45 100644--- a/apps/desktop/src/main/bot-import/__tests__/sources.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/sources.test.ts@@ -218,7 +218,7 @@ it('imports Hermes context without turning unrelated repository instructions intexpect((await inspectImportSource(source!, reader)).items.find(item => item.role === 'instructions')?.text).toBe('Speak gently and briefly.');});-it('selects entry and monitor subtrees, including sibling code, resources and their environment dependencies', async () => {+it('preserves every script while tracking only actual entry and monitor dependencies', async () => {await write('.hermes/config.yaml', 'name: Ada\n');await write('.hermes/.env', 'DATA_URL=https://example.invalid\nDATA_TOKEN=fixture-token');await write('.hermes/scripts/reports/daily.sh', '. ./helper.sh');@@ -234,9 +234,9 @@ it('selects entry and monitor subtrees, including sibling code, resources and thexpect(automation.view.issues).toBeUndefined();const files = snapshot.items.filter(item => item.asset);expect(files.filter(item => item.view.selected).map(item => item.asset!.name).sort()).toEqual([- 'scripts/monitor/check.sh', 'scripts/monitor/data/value.txt', 'scripts/reports/daily.sh', 'scripts/reports/data/template.txt', 'scripts/reports/helper.sh',- ]);- expect(automation.view.dependsOn?.toSorted()).toEqual(snapshot.items.filter(item => item.view.selected && (item.asset || item.env)).map(item => item.view.id).sort());+ 'scripts/monitor/check.sh', 'scripts/monitor/data/value.txt', 'scripts/reports/daily.sh', 'scripts/reports/data/template.txt', 'scripts/reports/helper.sh', 'scripts/reports-unused/other.sh',+ ].sort());+ expect(automation.view.dependsOn?.toSorted()).toEqual(snapshot.items.filter(item => item.view.selected && (item.asset || item.env) && !item.asset?.name.includes('reports-unused')).map(item => item.view.id).sort());// A surviving sibling must not hide a missing entrypoint.await fs.unlink(path.join(home, '.hermes/scripts/reports/daily.sh'));expect((await inspectImportSource(source!, reader)).items.find(item => item.automation)?.view.issues).toContain('AUTOMATION_SCRIPT_MISSING');@@ -557,17 +557,20 @@ it.each(['hermes', 'openclaw'] as const)('discovers %s custom archives, hidden Tit.each(['hermes', 'openclaw'] as const)('imports %s textual state and backups without treating empty markers as attachments', async kind => {await write(`.${kind}/${kind === 'hermes' ? 'config.yaml' : 'openclaw.json'}`, '{}');const folder = `.${kind}/${kind === 'hermes' ? 'memories' : 'workspace/memory'}`;- const documents = { 'state.json': '{"lastRun":"fixture"}\n', 'MEMORY.md.bak-20260101': '# Old note\n', 'extensionless': 'A note\n' };+ const documents = { 'state.json': '{"lastRun":"fixture"}\n', 'MEMORY.md.bak-20260101': '# Old note\n', 'extensionless': 'A note\n', 'terminal.txt': 'A log with \u0015 control bytes\n' };for (const [name, text] of Object.entries(documents)) await write(`${folder}/${name}`, text);for (const name of ['.morning-report.sent', 'MEMORY.md.lock', 'empty.md']) await write(`${folder}/${name}`, '');const reader = deps(); const [source] = await discoverImportSources(reader);const memory = (await inspectImportSource(source!, reader)).items.filter(item => item.view.category === 'memory');- expect(memory.map(item => [item.view.name, item.text]).sort()).toEqual(Object.entries(documents).sort());- expect(memory.every(item => !item.asset && !item.captureIssue)).toBe(true);+ expect(memory.filter(item => item.text).map(item => [item.view.name, item.text]).sort()).toEqual(Object.entries(documents).sort());+ expect(memory.filter(item => item.asset)).toHaveLength(3);+ expect(memory.filter(item => item.asset).every(item => item.asset!.bytes.length === 0)).toBe(true);+ expect(memory.every(item => !item.captureIssue)).toBe(true);});-it('saves native command jobs as disabled routines and excludes only native heartbeats', async () => {+it('preserves native commands, heartbeat jobs and their instruction document', async () => {await write('.openclaw/openclaw.json', JSON.stringify({ agents: { defaults: { model: 'source-model' } }, tools: { profile: 'restricted' } }));+ await write('.openclaw/workspace/HEARTBEAT.md', 'Check the original checklist');const command = { kind: 'command', argv: ['node', 'report.js', 'argument with spaces'], cwd: home, timeoutSeconds: 90, noOutputTimeoutSeconds: 10, outputMaxBytes: 4096 };await write('.openclaw/cron/jobs.json', JSON.stringify({ jobs: [{ id: 'command', name: 'Command report', payload: command, schedule: { kind: 'every', everyMs: 60000 } },@@ -575,12 +578,17 @@ it('saves native command jobs as disabled routines and excludes only native hear{ id: 'ordinary-heartbeat', name: 'heartbeat-main', payload: { kind: 'agentTurn', message: 'A normal reminder' }, schedule: { kind: 'every', everyMs: 60000 } },] }));const reader = deps(); const [source] = await discoverImportSources(reader);- const tasks = (await inspectImportSource(source!, reader)).items.filter(item => item.automation);- expect(tasks).toHaveLength(2);+ const inspected = await inspectImportSource(source!, reader);+ expect(inspected.items.find(item => item.view.name === 'HEARTBEAT.md')?.text).toBe('Check the original checklist');+ const tasks = inspected.items.filter(item => item.automation);+ expect(tasks).toHaveLength(3);expect(tasks[0]?.automation?.input).toMatchObject({ name: 'Command report', enabled: false });expect(tasks[0]?.automation?.original.payload).toEqual(command);expect(tasks[0]?.view.issues).toBeUndefined();- expect(tasks[1]?.view.name).toBe('heartbeat-main');+ expect(tasks[1]?.automation?.input).toMatchObject({ enabled: false, triggers: [{ kind: 'interval', intervalMs: 60000 }] });+ expect(tasks[1]?.automation?.original.payload).toEqual({ kind: 'heartbeat' });+ expect(tasks[1]?.view.issues).toContain('AUTOMATION_CONTEXT_NEEDS_MAPPING');+ expect(tasks[2]?.view.name).toBe('heartbeat-main');});for (const kind of ['hermes', 'openclaw'] as const) it(`imports ${kind} memory links only from its declared document vault`, async ctx => {@@ -604,3 +612,16 @@ for (const kind of ['hermes', 'openclaw'] as const) it(`imports ${kind} memory lconst withoutDeclaration = await inspectImportSource(source!, { ...reader, env: { ...reader.env, OBSIDIAN_VAULT_PATH: vault } });expect(withoutDeclaration.items.find(item => item.view.name === 'state.json')).toMatchObject({ captureIssue: 'SOURCE_LINK_OUTSIDE_FOLDER' });});++it('keeps distinct source records even when unsupported jobs lack usable identities', async () => {+ await write('.hermes/config.yaml', '{}');+ await write('.hermes/cron/jobs.json', JSON.stringify([+ { name: ' ', prompt: ' ', schedule: { kind: 'unknown' } },+ { name: ' ', prompt: ' ', schedule: { kind: 'unknown' } },+ ]));+ const reader = deps(); const [source] = await discoverImportSources(reader);+ const tasks = (await inspectImportSource(source!, reader)).items.filter(item => item.automation);+ expect(tasks).toHaveLength(2);+ expect(new Set(tasks.map(item => item.view.id)).size).toBe(2);+ expect(tasks.every(item => item.automation?.input?.enabled === false)).toBe(true);+});diff --git a/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts b/apps/desktop/src/main/bot-import/__tests__/transfer.test.tsindex 2edd1d1b1a..4914465321 100644--- a/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts@@ -367,15 +367,41 @@ it('returns a completed legacy deferred receipt even after its checkpoint was reexpect(deps.pauseSource).not.toHaveBeenCalled();});-it('reports the creation error instead of a setup mapping warning when an automation has no usable input', async () => {- const { deps } = harness();+it.each([+ { schedule: { kind: 'native-event', event: 'inbox' }, payload: { kind: 'agentTurn', message: 'Read' } },+ { schedule: { kind: 'every', everyMs: 1000 }, payload: { kind: 'agentTurn', message: 'Read' } },+ { schedule: { kind: 'every', everyMs: 60_000 }, payload: { kind: 'heartbeat' } },+ { schedule: { kind: 'every', everyMs: 60_000 }, payload: { kind: 'future-native-task', message: 'Read' } },+ { schedule: { kind: 'every', everyMs: 60_000 }, payload: {} },+])('preserves unsupported automation $payload.kind without changing the source or enabling it', async job => {+ const { deps, receipt } = harness();const source = { ...snapshot.source, kind: 'openclaw' as const };- const item = normalizeAutomation(source, { id: 'invalid', tools: { allow: ['read'] }, schedule: { kind: 'every', everyMs: 60_000 }, payload: {} }, [], 'UTC');- expect(item.view.issues).toEqual(['SOURCE_TOOL_POLICY_NEEDS_MAPPING', 'SOURCE_AUTOMATION_INVALID']);- const result = await transferCompanion({ ...snapshot, source, items: [item] }, { ...selection, entryIds: [item.view.id], deferSetup: true }, deps);- expect(result.checks).toContainEqual({ entryId: item.view.id, status: 'needs-attention', message: 'SOURCE_AUTOMATION_INVALID' });- expect(result.savedEntryIds).not.toContain(item.view.id);- expect(deps.createRoutine).not.toHaveBeenCalled();+ const original = { id: 'unsupported', ...job, delivery: { channel: 'unavailable-channel', to: 'original-target' } };+ const item = normalizeAutomation(source, original, [], 'UTC');+ expect(item.automation?.input).toMatchObject({ enabled: false });+ expect(item.view.issues?.length).toBeGreaterThan(0);+ const input = { ...selection, entryIds: [item.view.id], deferSetup: true, takeover: false };+ const content = { ...snapshot, source, items: [item] };+ const result = await transferCompanion(content, input, deps);+ expect(result.savedEntryIds).toContain(item.view.id);+ expect(result.checks).toContainEqual({ entryId: item.view.id, status: 'needs-attention', message: item.view.issues![0] });+ expect(deps.createRoutine).toHaveBeenCalledWith(expect.any(String), item.automation!.input, expect.any(String), item);+ expect(vi.mocked(deps.saveEnvironment).mock.calls[0]![1][0]!.automation?.original).toEqual(original);+ expect(receipt()?.routines[item.view.id]?.phase).toBe('created');+ await transferCompanion(content, input, deps);+ expect(deps.createRoutine).toHaveBeenCalledOnce();+ expect(deps.pauseSource).not.toHaveBeenCalled();+ expect(deps.enableRoutine).not.toHaveBeenCalled();+ expect(deps.verifyAutomation).not.toHaveBeenCalled();+});++it('recovers legacy checkpoints that had no converted routine input', async () => {+ const { deps } = harness();+ const item = normalizeAutomation(snapshot.source, { id: 'legacy', schedule: { kind: 'unknown' } }, [], 'UTC');+ delete item.automation!.input;+ const result = await transferCompanion({ ...snapshot, items: [item] }, { ...selection, entryIds: [item.view.id], deferSetup: true }, deps);+ expect(result.savedEntryIds).toContain(item.view.id);+ expect(deps.createRoutine).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ enabled: false, triggers: [] }), expect.any(String), item);expect(deps.pauseSource).not.toHaveBeenCalled();});diff --git a/apps/desktop/src/main/bot-import/environment.ts b/apps/desktop/src/main/bot-import/environment.tsindex 1dafb46c2c..7dcabfcbbb 100644--- a/apps/desktop/src/main/bot-import/environment.ts+++ b/apps/desktop/src/main/bot-import/environment.ts@@ -15,7 +15,7 @@ export interface CompanionEnvironment {credentials: Array<{ id: string; format: string; value: unknown }>;files?: Record<string, string>;/** Originals behind redacted skill projections; only materialized for authorized host commands. */- skillFiles?: Record<string, Array<{ name: string; bytes: string; executable: boolean }>>;+ skillFiles?: Record<string, Array<{ name: string; bytes: string; executable: boolean; interpreterLink?: string }>>;/** Original selected documents; model-readable profile/memory copies redact known credentials. */documents?: Record<string, string>;/** Redaction only: known values embedded in selected originals, never injected into processes. */diff --git a/apps/desktop/src/main/bot-import/files.ts b/apps/desktop/src/main/bot-import/files.tsindex 233bd6ae4c..ad8975e3f5 100644--- a/apps/desktop/src/main/bot-import/files.ts+++ b/apps/desktop/src/main/bot-import/files.ts@@ -106,8 +106,8 @@ export async function readImportFile(root: string, file: string, budget?: Importconst realRoot = await fs.realpath(root);const realFile = await fs.realpath(file);if (!inside(realRoot, realFile)) {- // Native memory entries may explicitly link a shared document. Trust only- // that file entry inside a declared document vault, never an arbitrary+ // Native entries may explicitly link a shared document or interpreter.+ // Trust only declared vaults / exact interpreter targets, never an arbitrary// external file/directory or a path supplied by IPC.if (!sharedDocumentRoots.some(directory => inside(directory, realFile)) || !inside(path.resolve(root), path.resolve(file))|| !inside(realRoot, await fs.realpath(path.dirname(file)))@@ -190,6 +190,13 @@ export async function writeImportFiles(root: string, files: readonly ImportFile[const target = path.resolve(root, file.name);if (!inside(root, target) || target === root) throw new CompanionImportError('INVALID_TARGET');await fs.mkdir(path.dirname(target), { recursive: true, mode: 0o700 });+ // The importer validates these exact native interpreter targets; preserve+ // their location so dynamic libraries and pyvenv.cfg still resolve normally.+ if (file.interpreterLink) {+ if (!/(?:^|\/)(?:\.venv|venv)\/(?:bin|Scripts)\/python(?:[23](?:\.\d+)?)?(?:\.exe)?$/.test(file.name) || !path.isAbsolute(file.interpreterLink)) throw new CompanionImportError('INVALID_TARGET');+ await fs.symlink(file.interpreterLink, target, 'file');+ continue;+ }// Imports write into newly allocated directories; never follow a pre-existing entry.const handle = await fs.open(target, 'wx', file.executable ? 0o700 : 0o600);try { await handle.writeFile(file.bytes); } finally { await handle.close(); }diff --git a/apps/desktop/src/main/bot-import/host.ts b/apps/desktop/src/main/bot-import/host.tsindex 01cb72e660..2c6a92747e 100644--- a/apps/desktop/src/main/bot-import/host.ts+++ b/apps/desktop/src/main/bot-import/host.ts@@ -544,6 +544,8 @@ export async function startCompanionImport(selection: CompanionImportSelection,if (prior?.environmentSaved) await companionEnvironmentStore.update(scope.root, botId, scope.assert, environment => {// A formerly unreadable manifest may only now supply its own settings.if (item.env) environment.env = { ...environment.env, ...item.env };+ const attachments = [...(item.asset ? [item.asset] : []), ...(['memory', 'personality'].includes(item.view.category) ? item.files ?? [] : [])];+ if (attachments.length) environment.files = { ...environment.files, ...Object.fromEntries(attachments.map(file => [file.name, file.bytes.toString('base64')])) };if (item.credential) environment.credentials = [...environment.credentials.filter(value => value.id !== item.view.id), { id: item.view.id, ...item.credential }];for (const [id, text] of documentEntries(item)) { environment.documents ??= {}; environment.documents[id] = text; }if (item.view.category === 'skills') {@@ -582,7 +584,10 @@ export async function startCompanionImport(selection: CompanionImportSelection,return [server];}),credentials: items.flatMap(item => item.credential && !item.view.dependsOn?.some(id => !chosen.has(id)) && (!item.view.issues?.length || item.credential.format !== 'telegram') ? [{ id: item.view.id, ...item.credential, ...(item.credential.format === 'telegram' ? { value: resolveReferences(item.credential.value) } : {}) }] : []),- files: Object.fromEntries(items.flatMap(item => item.asset ? [[item.asset.name, item.asset.bytes.toString('base64')]] : [])),+ files: Object.fromEntries(items.flatMap(item => [+ ...(item.asset ? [[item.asset.name, item.asset.bytes.toString('base64')]] : []),+ ...(['memory', 'personality'].includes(item.view.category) ? (item.files ?? []).map(file => [file.name, file.bytes.toString('base64')]) : []),+ ])),skillFiles,documents: Object.fromEntries(items.flatMap(documentEntries)),contentRedactions: publicationRedactions(items),diff --git a/apps/desktop/src/main/bot-import/memoryFiles.ts b/apps/desktop/src/main/bot-import/memoryFiles.tsindex bc4e2918d6..86383eda53 100644--- a/apps/desktop/src/main/bot-import/memoryFiles.ts+++ b/apps/desktop/src/main/bot-import/memoryFiles.ts@@ -3,13 +3,14 @@ import type { ImportFile } from './types.js';import { sniffMediaMime } from '../cindy-media/sniffMediaMime.js';/** Memory trees also contain JSON, backups and extensionless notes. Classify- * their bytes, not their suffix; empty delivery/lock markers carry no memory. */+ * their bytes, not their suffix; empty delivery/lock markers are archived without creating searchable memory text. */export function memoryFileContent(file: ImportFile): { kind: 'empty' } | { kind: 'text'; text: string } | { kind: 'attachment' } {if (!file.bytes.length) return { kind: 'empty' };if (sniffMediaMime(file.bytes)) return { kind: 'attachment' };- // Control bytes distinguish binary formats even when all bytes happen to be- // valid UTF-8. Keep original whitespace/BOM in the persisted text.- if (isUtf8(file.bytes) && !file.bytes.some(byte => byte < 32 && ![9, 10, 13].includes(byte))) {+ // Native text logs may contain terminal/control characters. Preserve them+ // verbatim; NUL bytes or non-UTF-8 still require attachment handling.+ const textDocument = /\.(?:md|txt|json|jsonl|yaml|yml|toml|csv|log)$/i.test(file.name);+ if (isUtf8(file.bytes) && !file.bytes.includes(0) && (textDocument || !file.bytes.some(byte => byte < 32 && ![9, 10, 13].includes(byte)))) {const text = file.bytes.toString('utf8');return text.trim() ? { kind: 'text', text } : { kind: 'empty' };}diff --git a/apps/desktop/src/main/bot-import/process.ts b/apps/desktop/src/main/bot-import/process.tsindex dbf278367e..3a7b6f98c6 100644--- a/apps/desktop/src/main/bot-import/process.ts+++ b/apps/desktop/src/main/bot-import/process.ts@@ -1,4 +1,5 @@import { spawn } from 'node:child_process';+import { isIP } from 'node:net';import { killProcessTree } from '../scheduler-host/proc-util.js';import { CompanionImportError } from './types.js';@@ -72,9 +73,9 @@ export function isPublicImportSetting(name: string, value: string): boolean {if (/(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|AUTH|CREDENTIAL|COOKIE)/i.test(name)) return false;return (/(?:^|_)(?:ENABLED|DISABLED|COUNT|RETRIES|RETRY|LIMIT|TIMEOUT|INTERVAL|SIZE|TEMPERATURE|TOP_P|HEADLESS|UNBUFFERED)(?:_|$)|^(?:MAX_|MIN_|PYTHONUNBUFFERED$)/i.test(name)&& /^(?:true|false|[+-]?\d+(?:\.\d+)?)$/i.test(value))- || (/(?:^|_)(?:FORCE|REQUIRE|OBSERVE|ALLOW|USE|ENABLE|DISABLE)_|(?:^|_)(?:DEBUG|VERBOSE|PROXIES|STEALTH)$/i.test(name)+ || (/(?:^|_)(?:FORCE|REQUIRE|OBSERVE|ALLOW|USE|ENABLE|DISABLE)_|(?:^|_)(?:DEBUG|VERBOSE|PROXIES|STEALTH|SEND_READ_RECEIPTS)$/i.test(name)&& /^(?:true|false|0|1)$/i.test(value))- || /(?:^|_)(?:HOST|BIND|ADDRESS)$/i.test(name) && /^(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[?::1?\]?)$/i.test(value)+ || /(?:^|_)(?:HOST|BIND|ADDRESS)$/i.test(name) && (/^(?:localhost|\[?::1?\]?)$/i.test(value) || isIP(value) !== 0)|| /(?:^|_)(?:MODE|TRANSPORT)$/i.test(name) && /^(?:websocket|polling|long_polling|webhook|http|https|stdio|sse)$/i.test(value)|| /(?:^|_)POLICY$/i.test(name) && /^(?:allowlist|denylist|open|closed|disabled)$/i.test(value)|| /(?:^|_)BOT_NAME$/i.test(name)diff --git a/apps/desktop/src/main/bot-import/skillResources.ts b/apps/desktop/src/main/bot-import/skillResources.tsindex 8168886180..c5480f705f 100644--- a/apps/desktop/src/main/bot-import/skillResources.ts+++ b/apps/desktop/src/main/bot-import/skillResources.ts@@ -23,7 +23,7 @@ export function projectImportedSkill(files: readonly ImportFile[], slug: string,const bytes = Buffer.from(redacted, encoding);return { ...file, bytes: bigEndian ? bytes.swap16() : bytes };});- if (!changed) return { files: projected };+ if (!changed) return { files: projected, ...(files.some(file => file.interpreterLink) ? { originals: files.map(file => ({ ...file, bytes: file.bytes.toString('base64') })) } : {}) };const guidance = `\n\nImported credentials are masked in these readable files. Execute this skill's commands with companion_connections.run_command, using the original resources at "$CINDY_IMPORTED_SKILLS/${slug}" (Windows cmd: "%CINDY_IMPORTED_SKILLS%\\${slug}") instead of this readable skill directory. Preserve relative resource paths within that directory. Write generated outputs to the current companion workspace.\n`;return {files: projected.map(file => {diff --git a/apps/desktop/src/main/bot-import/skills.ts b/apps/desktop/src/main/bot-import/skills.tsindex 22c3b7239b..4b6e984c6a 100644--- a/apps/desktop/src/main/bot-import/skills.ts+++ b/apps/desktop/src/main/bot-import/skills.ts@@ -1,4 +1,4 @@-import { promises as fs, type Dirent } from 'node:fs';+import { constants, promises as fs, type Dirent } from 'node:fs';import path from 'node:path';import yaml from 'js-yaml';import { fingerprint, inside, readImportFile, readImportTree, type ImportReadBudget } from './files.js';@@ -89,6 +89,49 @@ async function rootsFor(source: ImportSource, values: Record<string, unknown>, hreturn roots;}+/** A native venv declares its Python home. Preserve interpreter aliases and captured+ * executable bytes, without granting access to other files beside that interpreter. */+export async function readImportSkillTree(root: string, include?: (name: string) => boolean, budget?: ImportReadBudget) {+ const interpreters: string[] = [];+ for (const folder of ['.venv', 'venv']) {+ let config: string;+ try { config = (await readImportFile(root, path.join(root, folder, 'pyvenv.cfg'), budget)).bytes.toString('utf8'); }+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue; throw error; }+ const home = /^home\s*=\s*(.+)$/m.exec(config)?.[1]?.trim();+ if (!home || !path.isAbsolute(home)) continue;+ const realHome = await fs.realpath(home).catch(() => undefined);+ if (!realHome) continue;+ const bin = path.join(root, folder, process.platform === 'win32' ? 'Scripts' : 'bin');+ let entries: Dirent[];+ try { entries = await fs.readdir(bin, { withFileTypes: true }); }+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue; throw error; }+ for (const entry of entries) {+ if (!entry.isSymbolicLink() || !/^python(?:[23](?:\.\d+)?)?(?:\.exe)?$/.test(entry.name)) continue;+ const real = await fs.realpath(path.join(bin, entry.name));+ if (path.dirname(real) !== realHome || !/^python(?:[23](?:\.\d+)?)?(?:\.exe)?$/.test(path.basename(real))) continue;+ // Check only a bounded native executable header. Text credentials are+ // never made importable by renaming their link or forging pyvenv.cfg.+ const handle = await fs.open(real, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));+ try {+ const stat = await handle.stat();+ if (!stat.isFile() || process.platform !== 'win32' && !(stat.mode & 0o111)) continue;+ const header = Buffer.alloc(4);+ if ((await handle.read(header, 0, 4, 0)).bytesRead !== 4) continue;+ if (['7f454c46', 'feedface', 'cefaedfe', 'feedfacf', 'cffaedfe', 'cafebabe', 'bebafeca'].includes(header.toString('hex')) || header.subarray(0, 2).toString() === 'MZ') interpreters.push(real);+ } finally { await handle.close(); }+ }+ }+ const files = await readImportTree(root, include, budget, undefined, root, interpreters);+ for (const file of files) {+ if (!/^(?:\.venv|venv)\/(?:bin|Scripts)\/python(?:[23](?:\.\d+)?)?(?:\.exe)?$/.test(file.name)) continue;+ const entry = path.join(root, file.name);+ if (!(await fs.lstat(entry)).isSymbolicLink()) continue;+ const target = await fs.realpath(entry);+ if (interpreters.includes(target)) file.interpreterLink = target;+ }+ return files;+}+/** Discovery and repaired manifests must apply exactly the same native settings. */export function normalizeImportSkill(kind: ImportSource['kind'], alias: string, text: string, config: Record<string, unknown>, disabled = disabledSkills(config)): Pick<ImportItem, 'view' | 'sourceAlias' | 'env' | 'credential'> {const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);@@ -147,7 +190,7 @@ export async function discoverImportSkills(source: ImportSource, values: Record<const item: ImportItem = { ...metadata, sourceDirectory: real, files: [manifest], filesComplete: false };if (used.has(name) || used.has(path.basename(directory))) {try {- item.files = [manifest, ...await readImportTree(real, name => name !== 'SKILL.md', budget)];+ item.files = [manifest, ...await readImportSkillTree(real, name => name !== 'SKILL.md', budget)];item.filesComplete = true;} catch (error) { item.captureIssue = error instanceof CompanionImportError ? error.code : 'IMPORT_ITEM_FAILED'; }}diff --git a/apps/desktop/src/main/bot-import/sourceAutomations.ts b/apps/desktop/src/main/bot-import/sourceAutomations.tsindex 0a2b236d39..443319479e 100644--- a/apps/desktop/src/main/bot-import/sourceAutomations.ts+++ b/apps/desktop/src/main/bot-import/sourceAutomations.ts@@ -11,11 +11,11 @@ export function automationFingerprint(job: Record<string, unknown>): string {!['state', 'last_run_at', 'last_status', 'last_error', 'last_delivery_error', 'last_delivery_unverified', 'failure_streak', 'next_run_at', 'monitor_state', 'updatedAtMs'].includes(key))));}-export function normalizeAutomation(source: ImportSource, job: Record<string, unknown>, items: ImportItem[], timezone: string): ImportItem {+export function normalizeAutomation(source: ImportSource, job: Record<string, unknown>, items: ImportItem[], timezone: string, occurrence = 0): ImportItem {const sourceId = string(job.id) || string(job.jobId);const schedule = object(job.schedule);const payload = object(job.payload);- const name = string(job.name) || sourceId;+ const name = string(job.name).trim() || sourceId.trim() || `${source.kind} ${occurrence + 1}`;const enabled = job.enabled !== false && job.state !== 'paused';const prompt = source.kind === 'hermes' ? string(job.prompt) : string(payload.message) || string(payload.text);const issues: string[] = [];@@ -54,18 +54,28 @@ export function normalizeAutomation(source: ImportSource, job: Record<string, unif (!command && (job.model || job.provider || job.base_url || payload.model || job.reasoning_effort || payload.thinking|| items.some(item => item.credential?.format === 'source-model'))) issues.push('AUTOMATION_MODEL_NEEDS_MAPPING');if (job.workdir && path.resolve(string(job.workdir)) !== path.resolve(source.workspace)) issues.push('AUTOMATION_WORKDIR_NEEDS_MAPPING');- if (!sourceId || !name) issues.push('SOURCE_AUTOMATION_INVALID');+ if (!sourceId.trim()) issues.push('SOURCE_AUTOMATION_INVALID');// These are explicit source features, not guessed equivalent prompt instructions.if (Number(schedule.staggerMs) > 0) issues.push('AUTOMATION_STAGGER_NEEDS_ADAPTER');+ // Preserve unsupported native behavior without pretending a prompt is equivalent.+ if (source.kind === 'openclaw' && payload.kind === 'heartbeat') issues.push('AUTOMATION_CONTEXT_NEEDS_MAPPING');+ else if (source.kind === 'openclaw' && payload.kind && !['command', 'agentTurn', 'systemEvent'].includes(string(payload.kind))) issues.push('SOURCE_AUTOMATION_INVALID');+ const taskPrompt = command ? name : prompt || string(job.script) || [...selectedSkills].filter(Boolean).join('\n');+ if ((!taskPrompt.trim() && payload.kind !== 'heartbeat') || name.length > 200 || taskPrompt.length > 100_000) issues.push('SOURCE_AUTOMATION_INVALID');+ const draft = { name: name.slice(0, 200), prompt: (taskPrompt.trim() ? taskPrompt : name).slice(0, 100_000), enabled: false, silentWhenIdle: false };let input;- if (trigger) {- try { input = parseRoutineInput({ name, prompt: command ? name : prompt || string(job.script) || [...selectedSkills].filter(Boolean).join('\n'), enabled: false, triggers: [trigger], silentWhenIdle: false }); }- catch { issues.push('SOURCE_AUTOMATION_INVALID'); }+ try { input = parseRoutineInput({ ...draft, triggers: trigger ? [trigger] : [] }); }+ catch {+ issues.push('AUTOMATION_TRIGGER_NEEDS_ADAPTER');+ input = parseRoutineInput({ ...draft, triggers: [] });}+ // A disabled draft can have no converted trigger. The entire original remains+ // encrypted, and the existing execution guard rejects its unresolved issues.+return {- view: { id: `automation-${fingerprint(sourceId).slice(0, 20)}`, category: 'automations', name, enabled, selected: true,+ view: { id: `automation-${fingerprint(sourceId || [job, occurrence]).slice(0, 20)}`, category: 'automations', name, enabled, selected: true,description: string(job.schedule_display) || string(schedule.expr) || (trigger?.kind === 'once' && Number.isFinite(trigger.at) ? new Date(trigger.at).toISOString() : ''),- dependsOn, ...(issues.length ? { issues } : {}) },+ dependsOn, ...(issues.length ? { issues: [...new Set(issues)] } : {}) },envDependencies: { names: environmentNames, entries: dependsOn },automation: { sourceId, input, original: job, deliveries: [], fingerprint: automationFingerprint(job) },};diff --git a/apps/desktop/src/main/bot-import/sources.ts b/apps/desktop/src/main/bot-import/sources.tsindex 8942d494e4..d433102d05 100644--- a/apps/desktop/src/main/bot-import/sources.ts+++ b/apps/desktop/src/main/bot-import/sources.ts@@ -1,7 +1,6 @@import { markImportEnvironmentChoices, previewImportRedactions, resolveImportEnvironmentDependencies } from './environmentSelection.js';import { promises as fs } from 'node:fs';import path from 'node:path';-import { importedScriptName, isImportedScriptDependency } from './scripts.js';import JSON5 from 'json5';import { redactEnvironmentValues } from './process.js';import yaml from 'js-yaml';@@ -114,7 +113,11 @@ function entryId(prefix: string, name: string): string { return `${prefix}-${finasync function document(items: ImportItem[], root: string, name: string, role: ImportItem['role'], category: 'personality' | 'memory', budget: ImportReadBudget) {try {const text = await optionalText(root, path.join(root, name), budget);- if (!text?.trim()) return;+ if (text === undefined) return;+ if (!text.trim()) {+ items.push({ view: { id: entryId(category, name), category, name, selected: true }, asset: { name, bytes: Buffer.from(text) } });+ return;+ }items.push({ view: { id: entryId(category, name), category, name, selected: true }, text, role });} catch (error) {items.push({ view: { id: entryId(category, name), category, name, selected: true }, role,@@ -132,8 +135,7 @@ async function memoryDocuments(items: ImportItem[], root: string, prefix: stringcatch (error) { failed('', error, 'directory'); return; }for (const file of files) {const content = memoryFileContent(file);- if (content.kind === 'empty') continue;- if (content.kind === 'attachment') {+ if (content.kind !== 'text') {items.push({ view: { id: entryId('memory', `${prefix}/${file.name}`), category: 'memory', name: `${prefix}/${file.name}`, selected: true }, asset: { name: `${prefix}/${file.name}`, bytes: file.bytes } });continue;}@@ -175,7 +177,7 @@ async function connections(items: ImportItem[], source: ImportSource, values: Re? rawCwd.startsWith('~/') ? path.join(deps.home, rawCwd.slice(2)) : rawCwd: sourcePath(deps.home, rawCwd, source.workspace);}- items.push({ view: { id: entryId('mcp', name), category: 'connections', name, selected: enabled, enabled, dependsOn: [...references].map(key => entryId('env', key)) },+ items.push({ view: { id: entryId('mcp', name), category: 'connections', name, selected: true, enabled, dependsOn: [...references].map(key => entryId('env', key)) },envDependencies: { names: [...references], entries: [] },mcp: { name, enabled, ...(command ? { command, args: Array.isArray(record.args) ? record.args.map(string) : [], cwd, transport: 'stdio' as const } : { url, transport: record.transport === 'sse' ? 'sse' as const : 'http' as const }),env: scalarEnv(record.env), headers: scalarEnvHeaders(record.headers) } });@@ -300,7 +302,7 @@ export async function inspectImportSource(source: ImportSource, deps: SourceReadawait document(items, workspace, 'USER.md', 'user', 'memory', budget);await document(items, workspace, 'MEMORY.md', undefined, 'memory', budget);await memoryDocuments(items, workspace, 'memory', budget, sharedDocumentRoots);- await document(items, workspace, 'DREAMS.md', undefined, 'memory', budget);+ for (const file of ['DREAMS.md', 'HEARTBEAT.md']) await document(items, workspace, file, undefined, 'memory', budget);const rows = agentRows(values);const defaultAgent = (rows.find(row => row.default === true) ?? rows[0])?.id === source.agentId;const storeKey = sourcePath(deps.home, string(object(values.cron).store) || path.join(source.root, 'cron', 'jobs.json'), source.root);@@ -328,18 +330,12 @@ export async function inspectImportSource(source: ImportSource, deps: SourceRead}await connections(items, source, values, deps, budget);if (source.kind === 'hermes' && (await directories(source.root)).includes('scripts')) {- const usedScripts = jobs.flatMap(job => [string(job.script), string(job.monitor_script)]).filter(Boolean).flatMap(file => {- try { return [importedScriptName(source.root, sourcePath(deps.home, file, path.join(source.root, 'scripts')))]; }- catch { return []; }- });- for (const file of await readImportTree(path.join(source.root, 'scripts'), undefined, budget)) items.push({ view: { id: entryId('script', file.name), category: 'connections', name: `scripts/${file.name}`, selected: isImportedScriptDependency(`scripts/${file.name}`, usedScripts) }, asset: { name: `scripts/${file.name}`, bytes: file.bytes } });+ for (const file of await readImportTree(path.join(source.root, 'scripts'), undefined, budget)) items.push({ view: { id: entryId('script', file.name), category: 'connections', name: `scripts/${file.name}`, selected: true }, asset: { name: `scripts/${file.name}`, bytes: file.bytes } });}const row = source.kind === 'openclaw' ? agentRows(values).find(row => row.id === source.agentId) ?? {} : values;sourceConfiguration(items, source, values);- // Native heartbeat is not a portable scheduled job. Ordinary jobs named heartbeat remain below.- for (const job of jobs) {- if (source.kind === 'openclaw' && object(job.payload).kind === 'heartbeat') continue;- items.push(normalizeAutomation(source, job, items, string(values.timezone) || deps.env.TZ || Intl.DateTimeFormat().resolvedOptions().timeZone));+ for (const [index, job] of jobs.entries()) {+ items.push(normalizeAutomation(source, job, items, string(values.timezone) || deps.env.TZ || Intl.DateTimeFormat().resolvedOptions().timeZone, index));}const identity = items.find(item => item.view.name === 'IDENTITY.md')?.text ?? '';const avatar = string(object(row.identity).avatar) || string(row.avatar) || /^\s*[-*]?\s*\*{0,2}Avatar\*{0,2}:\s*(.+)$/im.exec(identity)?.[1]?.trim() || '';diff --git a/apps/desktop/src/main/bot-import/transfer.ts b/apps/desktop/src/main/bot-import/transfer.tsindex f20d1b8443..1f4cffd6c0 100644--- a/apps/desktop/src/main/bot-import/transfer.ts+++ b/apps/desktop/src/main/bot-import/transfer.ts@@ -3,7 +3,8 @@ import type { CompanionImportResult, CompanionImportSelection } from '@cindy/makimport type { RoutineInput } from '@cindy/maker-scheduler';import { createImportBudget, fingerprint, readImportFile, readImportTree, reserveSnapshotItems, type ImportReadBudget } from './files.js';import { CompanionImportError, importFailureCode, object, type ImportItem, type ImportSnapshot, type ImportSource } from './types.js';-import { normalizeImportSkill } from './skills.js';+import { normalizeImportSkill, readImportSkillTree } from './skills.js';+import { normalizeAutomation } from './sourceAutomations.js';import { memoryFileContent } from './memoryFiles.js';import { resolveImportEnvironmentDependencies, selectedImportEnvironment } from './environmentSelection.js';@@ -163,7 +164,7 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Comitem.files = []; item.documents = [];for (const file of files) {const content = memoryFileContent(file);- if (content.kind === 'attachment') item.files.push(file);+ if (content.kind !== 'text') item.files.push(file);else if (content.kind === 'text') item.documents.push({id: recoveredDocumentId(`${item.view.id}-${fingerprint(file.name).slice(0, 20)}`), name: file.name, text: content.text,...(/(^|\/)USER\.md$/i.test(file.name) ? { role: 'user' as const } : {}),@@ -173,7 +174,7 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Comconst file = await readImportFile(source.root, source.file, budget, sharedDocumentRoots);const content = memoryFileContent(file);if (content.kind === 'text') item.text = content.text;- else if (content.kind === 'attachment') item.asset = { name: file.name, bytes: file.bytes };+ else item.asset = { name: file.name, bytes: file.bytes };}delete item.captureIssue;} catch (error) { item.captureIssue = importFailureCode(error); }@@ -187,7 +188,7 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Comconst captured = item.files ?? [];const names = new Set(captured.map(file => file.name));try {- item.files = [...captured, ...await readImportTree(item.sourceDirectory, name => !names.has(name), budget)];+ item.files = [...captured, ...await readImportSkillTree(item.sourceDirectory, name => !names.has(name), budget)];if (metadataPending) {const manifest = item.files.find(file => file.name === 'SKILL.md')?.bytes.toString('utf8');if (!manifest?.trim() || !deps.readSkillConfig) throw new CompanionImportError('SOURCE_CONFIG_INVALID');@@ -264,13 +265,15 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com&& prior?.phase !== 'pausing-source' && prior?.phase !== 'source-paused') continue;const automation = item.automation!;if (!automation.input) {- check(item.view.id, 'needs-attention', item.view.issues?.find(issue => !['SOURCE_TOOL_POLICY_NEEDS_MAPPING', 'AUTOMATION_MODEL_NEEDS_MAPPING'].includes(issue)) ?? 'SOURCE_AUTOMATION_INVALID');- await saveProgress(); continue;+ // Retry checkpoints created before unsupported tasks had visible drafts.+ const restored = normalizeAutomation(snapshot.source, automation.original, items, 'UTC');+ automation.input = restored.automation!.input;+ item.view.issues = [...new Set([...(item.view.issues ?? []), ...(restored.view.issues ?? []), 'SOURCE_AUTOMATION_INVALID'])];}let record = receipt.routines[item.view.id];if (!record) {try {- const id = await deps.createRoutine(botId, { ...automation.input, enabled: false }, fingerprint([selection.requestId, item.view.id]), item);+ const id = await deps.createRoutine(botId, { ...automation.input!, enabled: false }, fingerprint([selection.requestId, item.view.id]), item);deps.assertOwner();record = receipt.routines[item.view.id] = { id, phase: 'created' };// createOnce is idempotent if this progress batch is interrupted.@@ -281,12 +284,12 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com}}if (record.phase === 'complete') { check(item.view.id, item.view.enabled && selection.takeover ? 'taken-over' : 'paused'); continue; }- if (!item.view.enabled || !selection.takeover) {- record.phase = 'complete'; check(item.view.id, 'paused'); await saveProgress(); continue;- }if (item.view.issues?.length) {check(item.view.id, 'needs-attention', item.view.issues[0]); await saveProgress(); continue;}+ if (!item.view.enabled || !selection.takeover) {+ record.phase = 'complete'; check(item.view.id, 'paused'); await saveProgress(); continue;+ }if (selection.deferSetup && !resumeSetup && record.phase === 'created') {check(item.view.id, 'needs-attention', 'IMPORT_SETUP_DEFERRED'); await saveProgress(); continue;}diff --git a/apps/desktop/src/main/bot-import/types.ts b/apps/desktop/src/main/bot-import/types.tsindex 4298618291..b14b87530d 100644--- a/apps/desktop/src/main/bot-import/types.ts+++ b/apps/desktop/src/main/bot-import/types.ts@@ -18,6 +18,8 @@ export interface ImportFile {name: string;bytes: Buffer;executable: boolean;+ /** Host-validated native Python interpreter; retain its runtime/library location. */+ interpreterLink?: string;}export interface ImportedMcpServer {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botSkillStore.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botSkillStore.test.tsindex 6c7f79c61d..81de1ce13b 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botSkillStore.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botSkillStore.test.ts@@ -334,3 +334,20 @@ it('deletes only the read/edit target if older data contains duplicate enabled aexpect(await fs.readFile(path.join(disabled, 'SKILL.md'), 'utf8')).toBe('# Retain disabled copy');expect(await readBotSkill(userDataDir, 'bot-1', 'report')).toMatchObject({ enabled: false, body: '# Retain disabled copy' });});++it.skipIf(process.platform === 'win32')('preserves native interpreter links across save/retry and rejects a changed alias', async () => {+ const runtime = path.join(userDataDir, 'runtime-python');+ await fs.writeFile(runtime, 'fixture-runtime');+ const files = [+ { name: 'SKILL.md', bytes: Buffer.from('# Imported'), executable: false },+ { name: '.venv/bin/python', bytes: Buffer.from('fixture-runtime'), executable: true, interpreterLink: runtime },+ ];+ await importBotSkillFiles(userDataDir, 'bot', 'native', files, () => {});+ const alias = path.join(botSkillsDir(userDataDir, 'bot'), 'native/.venv/bin/python');+ expect(await fs.readlink(alias)).toBe(runtime);+ await importBotSkillFiles(userDataDir, 'bot', 'native', files, () => {});+ await fs.unlink(alias); await fs.symlink(path.join(userDataDir, 'other-python'), alias);+ await expect(importBotSkillFiles(userDataDir, 'bot', 'native', files, () => {})).rejects.toThrow('Imported interpreter was edited');+ expect(await fs.readFile(runtime, 'utf8')).toBe('fixture-runtime');+ await expect(importBotSkillFiles(userDataDir, 'bot', 'unsafe', [{ ...files[0]!, interpreterLink: runtime }], () => {})).rejects.toThrow('Invalid imported interpreter');+});diff --git a/apps/desktop/src/main/maker-ipc/botSkillStore.ts b/apps/desktop/src/main/maker-ipc/botSkillStore.tsindex 5579dfcbf6..705daff1b4 100644--- a/apps/desktop/src/main/maker-ipc/botSkillStore.ts+++ b/apps/desktop/src/main/maker-ipc/botSkillStore.ts@@ -480,7 +480,7 @@ export async function saveBotSkill(/** Shared preflight for imports, before creating a profile or persisting its checkpoint. */export function validateBotSkillFiles(slug: string,- files: readonly { name: string; bytes: Buffer; executable: boolean }[]): void {+ files: readonly { name: string; bytes: Buffer; executable: boolean; interpreterLink?: string }[]): void {if (!normalizeBotSkillSlug(slug) || normalizeBotSkillSlug(slug) !== slug)throw new BotSkillStoreError('INVALID_ARGS', 'Invalid imported skill');const entrypoint = files.find(file => file.name === 'SKILL.md');@@ -489,12 +489,14 @@ export function validateBotSkillFiles(slug: string,for (const file of files) {if (file.name.includes('\\') || file.name.split('/').some(part => !part || part === '.' || part === '..') || path.isAbsolute(file.name))throw new BotSkillStoreError('INVALID_ARGS', 'Invalid skill resource');+ if (file.interpreterLink && (!/^(?:\.venv|venv)\/(?:bin|Scripts)\/python(?:[23](?:\.\d+)?)?(?:\.exe)?$/.test(file.name) || !path.isAbsolute(file.interpreterLink)))+ throw new BotSkillStoreError('INVALID_ARGS', 'Invalid imported interpreter');}}/** Import a selected real skill with its scripts/templates; keep the native SKILL.md bytes. */export async function importBotSkillFiles(userDataDir: string, botId: string, slug: string,- files: readonly { name: string; bytes: Buffer; executable: boolean }[], assertOwner: () => void, enabled = true): Promise<void> {+ files: readonly { name: string; bytes: Buffer; executable: boolean; interpreterLink?: string }[], assertOwner: () => void, enabled = true): Promise<void> {validateBotSkillFiles(slug, files);await ensureLayout(userDataDir, botId);assertOwner();@@ -515,7 +517,8 @@ export async function importBotSkillFiles(userDataDir: string, botId: string, slconst output = path.join(temporary, ...file.name.split('/'));await fs.mkdir(path.dirname(output), { recursive: true, mode: 0o700 });assertOwner();- await fs.writeFile(output, file.bytes, { flag: 'wx', mode: file.executable ? 0o700 : 0o600 });+ if (file.interpreterLink) await fs.symlink(file.interpreterLink, output, 'file');+ else await fs.writeFile(output, file.bytes, { flag: 'wx', mode: file.executable ? 0o700 : 0o600 });}assertOwner();try { await fs.rename(temporary, target); }@@ -525,6 +528,11 @@ export async function importBotSkillFiles(userDataDir: string, botId: string, slif (!(await fs.lstat(target)).isDirectory()) throw new BotSkillStoreError('INVALID_ARGS', 'Invalid imported skill folder');for (const file of files) {const entry = path.join(target, ...file.name.split('/'));+ if (file.interpreterLink) {+ if (!(await fs.lstat(entry)).isSymbolicLink() || await fs.readlink(entry) !== file.interpreterLink)+ throw new BotSkillStoreError('INVALID_ARGS', 'Imported interpreter was edited');+ continue;+ }const resolved = await fs.realpath(entry);const relative = path.relative(await fs.realpath(target), resolved);if (relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) throw new BotSkillStoreError('INVALID_ARGS', 'Invalid imported skill resource');diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex de6449bae1..3d6ac7775b 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -558,6 +558,6 @@ Codex 切模型重建时,线程索引里的路径不等于文件已经落盘- 导入页用分类汇总和可搜索、分页的单层列表;保存完成后直接进入伙伴聊天,不在完成页堆叠逐项待办。- 先保存资料、连接与停用状态的自动化定义,再在聊天中完成登录和验证;用户可以稍后处理,普通聊天始终可用。- 新导入的自动化结果统一进入 Cindy 伙伴聊天,不校验或沿用原发送渠道。存量已导入自动化不自动改渠道。-- 不展示无法接管的原生 Heartbeat;名字包含 heartbeat 的普通定时任务仍保留。+- 全量保留来源资料、技能及自动化(包括原生 Heartbeat、未知触发条件、空标记文件),仅排除用户主动取消的项目。暂不能转换的自动化仍保存为可见的停用任务和加密原始定义,明确提示待适配项;不能因 Cindy 暂缺能力或原投放渠道不可用而过滤。验收对照来源总清单,不以过滤后的已选数量冒充完整。- 单项读取或写入失败保留重试记录,不中止其它内容;导入成功数量与自动化启用状态分别计算。文件字节保护仍适用,不截断文件冒充完整导入。- 原任务在验证及接管完成前保持原状。明确选用 Cindy 模型和工具设置后可解除相应兼容性待办,仍须验证数据并确认原任务已暂停,才能启用 Cindy 任务。diff --git a/packages/maker-scheduler/src/__tests__/routines.test.ts b/packages/maker-scheduler/src/__tests__/routines.test.tsindex a502d86d48..c602aad87f 100644--- a/packages/maker-scheduler/src/__tests__/routines.test.ts+++ b/packages/maker-scheduler/src/__tests__/routines.test.ts@@ -66,6 +66,20 @@ async function fixture(}describe("Routine event admission and execution", () => {+ it('persists a disabled draft without inventing a trigger and rejects premature activation', async () => {+ const f = await fixture();+ const draft = await f.engine.createOnce('bot', { ...input, enabled: false, triggers: [] }, 'imported-draft-fixture');+ await f.engine.stop();+ const restored = await fixture(undefined, f.snapshot());+ try {+ expect(restored.engine.list('bot')).toEqual([draft]);+ restored.advance(3600_000);+ await restored.engine.tick();+ expect(restored.execute).not.toHaveBeenCalled();+ await expect(restored.engine.put('bot', { ...draft, enabled: true }, draft.id)).rejects.toThrow('requires');+ expect(restored.engine.list('bot')).toEqual([draft]);+ } finally { await restored.engine.stop(); }+ });it('deduplicates concurrent creation and a retry after restart without overwriting newer edits', async () => {const f = await fixture();const creationId = 'mobile-request-123456';diff --git a/packages/maker-scheduler/src/routines.ts b/packages/maker-scheduler/src/routines.tsindex 7190a47be4..06f9deb5ee 100644--- a/packages/maker-scheduler/src/routines.ts+++ b/packages/maker-scheduler/src/routines.ts@@ -80,10 +80,10 @@ export function parseRoutineInput(value: unknown): RoutineInput {throw new Error("enabled must be boolean");if (!Array.isArray(input.triggers) ||- input.triggers.length < 1 ||+ (input.enabled && input.triggers.length < 1) ||input.triggers.length > 32) {- throw new Error("A routine requires between 1 and 32 triggers");+ throw new Error("An enabled routine requires between 1 and 32 triggers; disabled drafts allow none");}const triggers = input.triggers.map((raw): RoutineTrigger => {const trigger = record(raw);