Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(companions): index automation dependencies and preserve source content
Chrisddb7b5b5d3b4
diff --git a/apps/desktop/src/main/bot-import/__tests__/automationRuntime.test.ts b/apps/desktop/src/main/bot-import/__tests__/automationRuntime.test.tsindex 1c783cc324..e4f8739083 100644--- a/apps/desktop/src/main/bot-import/__tests__/automationRuntime.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/automationRuntime.test.ts@@ -250,12 +250,13 @@ it.each(['stdin', 'argv', 'assignment'] as const)('masks nested JSON credentialsconst arraySecret = 'fixture-array-secret';const containerSecret = 'fixture-container-secret';const privateKey = 'fixture-private-"quoted"\n-key';+ const passphrase = 'fixture-passphrase';const keyField = source === 'stdin' ? 'private_key' : source === 'argv' ? 'privateKey' : 'signing_key';const input = JSON.stringify({ credentials: [{ token: secret, api_key: [arraySecret] }, containerSecret],- [keyField]: privateKey, city: 'Paris', cities: ['Paris', 'London'], count: 7 });+ [keyField]: privateKey, passphrase, passphrases: [passphrase], city: 'Paris', cities: ['Paris', 'London'], count: 7 });const read = source === 'stdin' ? 'require("node:fs").readFileSync(0,"utf8")': source === 'assignment' ? 'process.argv[1].slice("--config=".length)' : 'process.argv[1]';- const code = `const input=JSON.parse(${read}); process.stdout.write(JSON.stringify({token:input.credentials[0].token,arrayToken:input.credentials[0].api_key[0],containerToken:input.credentials[1],privateKey:input.${keyField},city:input.city,cities:input.cities,count:input.count}));`;+ const code = `const input=JSON.parse(${read}); process.stdout.write(JSON.stringify({token:input.credentials[0].token,arrayToken:input.credentials[0].api_key[0],containerToken:input.credentials[1],privateKey:input.${keyField},passphrase:input.passphrase,city:input.city,cities:input.cities,count:input.count}));`;const original = { payload: { kind: 'command', argv: [process.execPath, '-e', code,...(source === 'stdin' ? [] : ['--', source === 'assignment' ? `--config=${input}` : input])],...(source === 'stdin' ? { input } : {}), cwd: root } };@@ -264,12 +265,12 @@ it.each(['stdin', 'argv', 'assignment'] as const)('masks nested JSON credentials} }, () => {});const signal = new AbortController().signal;const prepared = await prepareImportedAutomation(root, routine, 'structured-run', signal, () => {});- expect(JSON.parse(prepared!.direct!)).toEqual({ token: expect.stringMatching(/^\[command_literal_/), arrayToken: expect.stringMatching(/^\[command_literal_/), containerToken: expect.stringMatching(/^\[command_literal_/), privateKey: expect.stringMatching(/^\[command_literal_/), city: 'Paris', cities: ['Paris', 'London'], count: 7 });+ expect(JSON.parse(prepared!.direct!)).toEqual({ token: expect.stringMatching(/^\[command_literal_/), arrayToken: expect.stringMatching(/^\[command_literal_/), containerToken: expect.stringMatching(/^\[command_literal_/), privateKey: expect.stringMatching(/^\[command_literal_/), passphrase: expect.stringMatching(/^\[command_literal_/), city: 'Paris', cities: ['Paris', 'London'], count: 7 });const saved = (await shared.store.read(root, 'bot', () => {}))!.automations!.routine!;expect(saved.original).toEqual(original);expect(saved.prepared?.direct).toBe(prepared!.direct);// Old private output must be masked even when no process is executed again.- const legacy = JSON.stringify({ token: secret, arrayToken: arraySecret, containerToken: containerSecret, privateKey, city: 'Paris', cities: ['Paris', 'London'], count: 7 });+ const legacy = JSON.stringify({ token: secret, arrayToken: arraySecret, containerToken: containerSecret, privateKey, passphrase, city: 'Paris', cities: ['Paris', 'London'], count: 7 });await shared.store.update(root, 'bot', () => {}, env => {env.automations!.routine!.prepared = { runId: 'structured-run', prompt: '', direct: legacy };});diff --git a/apps/desktop/src/main/bot-import/__tests__/host.test.ts b/apps/desktop/src/main/bot-import/__tests__/host.test.tsindex 22ee15f69f..dd3560d5e1 100644--- a/apps/desktop/src/main/bot-import/__tests__/host.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/host.test.ts@@ -76,7 +76,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';+import { indexAutomationDependencies, normalizeAutomation } from '../sourceAutomations.js';beforeEach(async () => {h.root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-import-host-test-'));@@ -1230,7 +1230,7 @@ it('receives sparse selection chunks idempotently and starts only after the compit('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');+ const item = normalizeAutomation(h.snapshot.source, original, indexAutomationDependencies([]), 'UTC');h.snapshot.items = [item];const [source] = await listCompanionImportSources('fixture');const preview = await previewCompanionImport(source!.id, 'fixture');diff --git a/apps/desktop/src/main/bot-import/__tests__/process.test.ts b/apps/desktop/src/main/bot-import/__tests__/process.test.tsindex 859451080b..414b86ddfb 100644--- a/apps/desktop/src/main/bot-import/__tests__/process.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/process.test.ts@@ -40,10 +40,25 @@ it('keeps credential context through array and object values without masking ordexpect(JSON.stringify(original)).toBe(before);});+it('preserves OAuth token-type metadata in source files while masking credentials in the same container', () => {+ const tokens = { token_type: 'Bearer', access_token: 'fixture-access-secret', nested: { tokenType: 'DPoP', value: 'fixture-nested-secret' },+ unknown: { token_type: 'fixture-unknown-secret' }, structured: { token_type: ['fixture-array-secret'] } };+ const before = JSON.stringify(tokens);+ const environment = { env: {}, mcp: [], credentials: [{ id: 'fixture', format: 'json', value: { tokens } }] };+ const masks = importedContentRedactions(environment);+ const source = 'Use Bearer or DPoP authorization. fixture-access-secret fixture-nested-secret fixture-unknown-secret fixture-array-secret';+ const output = redactEnvironmentValues(source, masks);+ expect(output).toContain('Use Bearer or DPoP authorization.');+ for (const secret of ['fixture-access-secret', 'fixture-nested-secret', 'fixture-unknown-secret', 'fixture-array-secret']) expect(output).not.toContain(secret);+ expect(JSON.stringify(tokens)).toBe(before);+ // Public metadata never exempts the same literal supplied as an actual token.+ expect(redactEnvironmentValues('Bearer', importedContentRedactions({ ...environment, env: { API_TOKEN: 'Bearer' } }))).not.toBe('Bearer');+});+it.each(['credential', 'credentials', 'clientCredentials', 'tokens', 'access_tokens', 'refreshTokens','secrets', 'passwords', 'passwds', 'keys', 'api_keys', 'API-KEYS', 'auth', 'authorization', 'cookies','private_key', 'privateKey', 'privateKeys', 'SSH_PRIVATE_KEY', 'signing_key', 'signing-key', 'signingKey',- 'encryption_key', 'decryptionKey', 'awsSecretAccessKey', 'serviceApiKey'])(+ 'encryption_key', 'decryptionKey', 'awsSecretAccessKey', 'serviceApiKey', 'passphrase', 'passphrases', 'keyPassphrase', 'pass_phrase', 'pass-phrases'])('masks scalar and nested string descendants of the %s credential field', field => {const original = { [field]: ['fixture-container-secret', { nested: ['fixture-nested-secret'] }],scalar: { [field]: 'fixture-scalar-secret' }, cities: ['Paris', 'London'], monkeys: ['capuchin'],diff --git a/apps/desktop/src/main/bot-import/__tests__/sources.test.ts b/apps/desktop/src/main/bot-import/__tests__/sources.test.tsindex 2aa76a9012..4c9fa8b1e3 100644--- a/apps/desktop/src/main/bot-import/__tests__/sources.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/sources.test.ts@@ -7,6 +7,8 @@ import { transferCompanion, validateImportSelection, type TransferDeps } from '.import { resolveImportReferences, selectedImportEnvironment } from '../environmentSelection.js';import { discoverImportSkills, readImportSkillTree } from '../skills.js';import { createImportBudget } from '../files.js';+import { indexAutomationDependencies, normalizeAutomation } from '../sourceAutomations.js';+import type { ImportItem, ImportSource } from '../types.js';let home: string;beforeEach(async () => { home = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-import-source-test-')); });@@ -14,6 +16,50 @@ afterEach(async () => { vi.restoreAllMocks(); await fs.rm(home, { recursive: truasync function write(name: string, text: string) { const file = path.join(home, name); await fs.mkdir(path.dirname(file), { recursive: true }); await fs.writeFile(file, text); }const deps = () => ({ home, env: {}, readCronDatabase: vi.fn(async () => []) });+it.each(['hermes', 'openclaw'] as const)('previews 20,000 %s jobs with complete shared dependencies', async kind => {+ await write(`.${kind}/${kind === 'hermes' ? 'config.yaml' : 'openclaw.json'}`, JSON.stringify({+ mcpServers: { data: { url: 'https://example.invalid/mcp' } },+ }));+ await write(`.${kind}/.env`, 'API_TOKEN=fixture-token');+ const jobs = Array.from({ length: 20_000 }, (_, index) => ({ id: `job-${index}`, agentId: 'main',+ prompt: 'Use data with API_TOKEN', payload: { kind: 'agentTurn', message: 'Use data with API_TOKEN' },+ schedule: { kind: 'interval', minutes: 5 }, enabled: index % 2 === 0 }));+ await write(`.${kind}/cron/jobs.json`, JSON.stringify({ jobs }));+ const reader = deps(); const [source] = await discoverImportSources(reader);+ const snapshot = await inspectImportSource(source!, reader);+ const tasks = snapshot.items.filter(item => item.automation);+ const connection = snapshot.items.find(item => item.mcp?.name === 'data')!;+ const environment = snapshot.items.find(item => item.env?.API_TOKEN)!;+ expect(tasks).toHaveLength(jobs.length);+ expect(new Set(tasks.map(item => item.view.id)).size).toBe(jobs.length);+ expect(tasks.every((item, index) => item.view.enabled === jobs[index]!.enabled+ && item.view.dependsOn?.includes(connection.view.id) && item.view.dependsOn?.includes(environment.view.id)+ && item.automation?.input?.enabled === false)).toBe(true);+ expect(tasks.map(item => item.automation!.original)).toEqual(jobs);+});++it('indexes aliases and script subtrees while preserving dependency order and inherited policies', () => {+ const source: ImportSource = { kind: 'hermes', root: home, workspace: home, configFile: path.join(home, 'config.yaml'), agentId: 'main', name: 'Ada' };+ const view = (id: string, category: ImportItem['view']['category'] = 'connections') => ({ id, name: id, category, selected: true });+ const items: ImportItem[] = [+ { view: view('mcp'), mcp: { name: 'bridge', url: 'https://example.invalid/mcp' } },+ { view: { ...view('skill', 'skills'), name: 'Display name' }, sourceAlias: 'alias', sourceDirectory: path.join(home, 'folder'),+ files: [{ name: 'SKILL.md', bytes: Buffer.from('bridge SKILL_TOKEN'), executable: false }, { name: 'image.png', bytes: Buffer.from('UNUSED_TOKEN'), executable: false }] },+ { view: view('main'), asset: { name: 'scripts/reports/run.py', bytes: Buffer.from('SCRIPT_TOKEN') } },+ { view: view('data'), asset: { name: 'scripts/reports/data/check.py', bytes: Buffer.from('bridge') } },+ { view: view('unrelated'), asset: { name: 'scripts/reports-other/other.py', bytes: Buffer.from('UNUSED_TOKEN') } },+ { view: view('env'), env: { SKILL_TOKEN: 'a', SCRIPT_TOKEN: 'b', UNUSED_TOKEN: 'c' } },+ { view: view('tools'), credential: { format: 'source-tools', value: {} } },+ { view: view('model'), credential: { format: 'source-model', value: {} } },+ ];+ const dependencies = indexAutomationDependencies(items);+ const item = normalizeAutomation(source, { id: 'report', skills: ['folder', 'alias'], script: 'reports/run.py', monitor_script: 'reports/data/check.py', schedule: { kind: 'interval', minutes: 5 } }, dependencies, 'UTC');+ expect(item.view.dependsOn).toEqual(['mcp', 'skill', 'main', 'data']);+ expect(item.envDependencies?.names).toEqual(['SKILL_TOKEN', 'SCRIPT_TOKEN']);+ expect(item.view.issues).toEqual(['SOURCE_TOOL_POLICY_NEEDS_MAPPING', 'AUTOMATION_MODEL_NEEDS_MAPPING']);+ expect(normalizeAutomation(source, { id: 'missing', script: 'reports/missing.py' }, dependencies, 'UTC').view.issues).toContain('AUTOMATION_SCRIPT_MISSING');+});+it.each([{ kind: 'hermes', config: { model: 'source-model' }, blocked: true },{ kind: 'openclaw', config: { agents: { list: [{ id: 'main', model: 'source-model' }] } }, blocked: 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 4914465321..578d043c6a 100644--- a/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts@@ -5,7 +5,7 @@ import { describe, expect, it, vi } from 'vitest';import { validateImportSelection, transferCompanion, type ImportReceipt, type TransferDeps } from '../transfer.js';import { CompanionImportError, type ImportSnapshot } from '../types.js';import type { CompanionImportSelection } from '@cindy/maker-shared/companion-import';-import { normalizeAutomation } from '../sourceAutomations.js';+import { indexAutomationDependencies, normalizeAutomation } from '../sourceAutomations.js';import { fingerprint } from '../files.js';const snapshot: ImportSnapshot = { source: { kind: 'hermes', agentId: 'default', name: 'Ada', root: '/fixture/hermes', workspace: '/fixture/work', configFile: '/fixture/hermes/config.yaml' }, fingerprint: 'fixture', items: [@@ -60,7 +60,7 @@ it('keeps the source running when a script sibling or resource is deselected', aconst items = ['reports/main.py', 'reports/helper.py', 'reports/data/input.json'].map(name => ({view: { id: name, name, category: 'connections' as const, selected: true }, asset: { name: `scripts/${name}`, bytes: Buffer.from('fixture') },}));- const task = normalizeAutomation(snapshot.source, { id: 'report', script: 'reports/main.py', no_agent: true, schedule: { kind: 'interval', minutes: 5 } }, items, 'UTC');+ const task = normalizeAutomation(snapshot.source, { id: 'report', script: 'reports/main.py', no_agent: true, schedule: { kind: 'interval', minutes: 5 } }, indexAutomationDependencies(items), 'UTC');const source = { ...snapshot, items: [...items, task] };for (const omitted of ['reports/helper.py', 'reports/data/input.json']) {const { deps } = harness();@@ -85,7 +85,7 @@ it.each([}));for (const candidates of [accounts, [...accounts].reverse(), [accounts[0]!]]) {const source = { ...snapshot.source, kind };- const task = normalizeAutomation(source, { id: 'reminder', prompt: 'Remember', payload: { message: 'Remember' }, schedule: { kind: 'interval', minutes: 5 }, ...job }, candidates, 'UTC');+ const task = normalizeAutomation(source, { id: 'reminder', prompt: 'Remember', payload: { message: 'Remember' }, schedule: { kind: 'interval', minutes: 5 }, ...job }, indexAutomationDependencies(candidates), 'UTC');const { deps } = harness();const items = [...candidates, task];const result = await transferCompanion({ ...snapshot, source, items }, { ...selection, entryIds: items.map(item => item.view.id) }, deps);@@ -103,7 +103,7 @@ it.each(['personal', 'missing'])('uses local delivery even when the source namesview: { id: account, name: account, category: 'connections' as const, selected: true },credential: { format: 'telegram', value: { account, token: `123:fake-${account}-token` } },}));- const task = normalizeAutomation(source, { id: 'reminder', payload: { message: 'Remember' }, schedule: { kind: 'every', everyMs: 60000 }, delivery: { mode: 'announce', channel: 'telegram', to: '123', accountId } }, accounts, 'UTC');+ const task = normalizeAutomation(source, { id: 'reminder', payload: { message: 'Remember' }, schedule: { kind: 'every', everyMs: 60000 }, delivery: { mode: 'announce', channel: 'telegram', to: '123', accountId } }, indexAutomationDependencies(accounts), 'UTC');const { deps } = harness();const items = [...accounts, task];await transferCompanion({ ...snapshot, source, items }, { ...selection, entryIds: items.map(item => item.view.id) }, deps);@@ -377,7 +377,7 @@ it.each([const { deps, receipt } = harness();const source = { ...snapshot.source, kind: 'openclaw' as const };const original = { id: 'unsupported', ...job, delivery: { channel: 'unavailable-channel', to: 'original-target' } };- const item = normalizeAutomation(source, original, [], 'UTC');+ const item = normalizeAutomation(source, original, indexAutomationDependencies([]), '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 };@@ -397,7 +397,7 @@ it.each([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');+ const item = normalizeAutomation(snapshot.source, { id: 'legacy', schedule: { kind: 'unknown' } }, indexAutomationDependencies([]), '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);diff --git a/apps/desktop/src/main/bot-import/__tests__/verification.test.ts b/apps/desktop/src/main/bot-import/__tests__/verification.test.tsindex 79b81f824b..e9042e8bf1 100644--- a/apps/desktop/src/main/bot-import/__tests__/verification.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/verification.test.ts@@ -8,7 +8,7 @@ import { getMakerIfReady } from '../../maker-host/index.js';import { getBotRemoteResourceSource } from '../../localDb/ipc/bots.js';import { companionEnvironmentStore } from '../runtime.js';import { matchesReadEvidence, readImportHttpEvidence, verifyImportedAutomation } from '../verification.js';-import { normalizeAutomation } from '../sourceAutomations.js';+import { indexAutomationDependencies, normalizeAutomation } from '../sourceAutomations.js';import { resolveImportEnvironmentDependencies } from '../environmentSelection.js';import type { ImportItem, ImportSource } from '../types.js';import * as connectionModule from '../connections.js';@@ -201,7 +201,7 @@ it.each(['hermes', 'openclaw'] as const)('routes a %s reminder locally without pconst reminder = (prompt: string) => resolveImportEnvironmentDependencies([normalizeAutomation(source, {id: 'reminder', name: 'Reminder', prompt, payload: { message: prompt }, schedule: { kind: 'interval', minutes: 5 },deliver: 'telegram:123', delivery: { mode: 'announce', channel: 'telegram', to: '123' },- }, selected, 'UTC')], selected)[0]!;+ }, indexAutomationDependencies(selected), 'UTC')], selected)[0]!;const item = reminder('Remind me to stretch');expect(item.view.dependsOn).toEqual([]);expect((await verifyImportedAutomation('/fixture', 'bot', item, () => {}, selected)).verified).toBe(true);@@ -431,7 +431,7 @@ it('does not verify a native command as a local reminder or expose its inline envi.mocked(getMakerIfReady).mockReturnValue({ oneShot, getSessionMeta: vi.fn().mockResolvedValue({ agentKind: 'pi', model: 'fixture-model' }) } as never);vi.mocked(getBotRemoteResourceSource).mockResolvedValue({ canonicalSessionId: 'fixture-session' } as never);const source: ImportSource = { kind: 'openclaw', agentId: 'main', name: 'Fixture', root: '/fixture', workspace: '/fixture/workspace', configFile: '/fixture/openclaw.json' };- const item = normalizeAutomation(source, { id: 'command', name: 'Report', payload: { kind: 'command', argv: ['report', '--token', secret], env: { API_TOKEN: secret } }, schedule: { kind: 'every', everyMs: 60000 } }, [], 'UTC');+ const item = normalizeAutomation(source, { id: 'command', name: 'Report', payload: { kind: 'command', argv: ['report', '--token', secret], env: { API_TOKEN: secret } }, schedule: { kind: 'every', everyMs: 60000 } }, indexAutomationDependencies([]), 'UTC');expect(await verifyImportedAutomation('/fixture', 'bot', item, () => {})).toMatchObject({ verified: false, reason: 'AUTOMATION_READ_NOT_VERIFIED' });expect(oneShot.mock.calls[0]![1]).toContain('native-command');expect(oneShot.mock.calls[0]![1]).not.toContain(secret);@@ -443,7 +443,7 @@ it('keeps literals that are absent from all credential maps out of the command rvi.mocked(getMakerIfReady).mockReturnValue({ oneShot, getSessionMeta: vi.fn().mockResolvedValue({ agentKind: 'pi', model: 'fixture-model' }) } as never);vi.mocked(getBotRemoteResourceSource).mockResolvedValue({ canonicalSessionId: 'fixture-session' } as never);const source: ImportSource = { kind: 'openclaw', agentId: 'main', name: 'Fixture', root: '/fixture', workspace: '/fixture/workspace', configFile: '/fixture/openclaw.json' };- const item = normalizeAutomation(source, { id: 'command', name: 'Report', payload: { kind: 'command', argv: ['private-executable', '--token', 'argument-only-secret'], cwd: '/private-directory', input: 'stdin-only-secret' }, schedule: { kind: 'every', everyMs: 60000 } }, [], 'UTC');+ const item = normalizeAutomation(source, { id: 'command', name: 'Report', payload: { kind: 'command', argv: ['private-executable', '--token', 'argument-only-secret'], cwd: '/private-directory', input: 'stdin-only-secret' }, schedule: { kind: 'every', everyMs: 60000 } }, indexAutomationDependencies([]), 'UTC');expect((await verifyImportedAutomation('/fixture', 'bot', item, () => {})).verified).toBe(false);const prompt = oneShot.mock.calls[0]![1];for (const literal of ['private-executable', 'argument-only-secret', '/private-directory', 'stdin-only-secret']) expect(prompt).not.toContain(literal);diff --git a/apps/desktop/src/main/bot-import/connectionCatalog.ts b/apps/desktop/src/main/bot-import/connectionCatalog.tsindex f977454c28..fcf082fcab 100644--- a/apps/desktop/src/main/bot-import/connectionCatalog.ts+++ b/apps/desktop/src/main/bot-import/connectionCatalog.ts@@ -9,7 +9,7 @@ const PUBLIC_MCP_ROUTES = new Set(['api', 'v1', 'v2', 'mcp', 'sse', 'messages',const LOCAL_MCP_ENDPOINTS = new Set(['native-mcp', 'touchdesigner-mcp']);const CAPABILITY_PATH_PREFIXES = new Set(['hooks', 'webhooks', 'token', 'secret', 'credential', 'key']);// Credential containers use the same classification as their scalar forms.-const CREDENTIAL_FIELD = /^(?:keys?|.*(?:api|private|signing|encryption|decryption|secret|access)[_-]?keys?|.*(?:tokens?|secrets?|passwords?|passwds?|credentials?)|auth(?:orization)?|access|refresh|cookies?)$/i;+const CREDENTIAL_FIELD = /^(?:keys?|.*(?:api|private|signing|encryption|decryption|secret|access)[_-]?keys?|.*(?:tokens?|secrets?|passwords?|passwds?|pass[_-]?phrases?|credentials?)|auth(?:orization)?|access|refresh|cookies?)$/i;/** Include resolved connection-local values without overwriting same-named imports. */export function connectionRedactions(server: ImportedMcpServer, environment: Record<string, string>): Record<string, string> {@@ -71,6 +71,10 @@ export function importedContentRedactions(environment: Pick<CompanionEnvironment}if (!value || typeof value !== 'object') return;for (const [key, child] of Object.entries(value)) {+ // OAuth token records include public protocol metadata alongside secrets.+ // Do not turn a scheme name into a global mask for imported source files.+ // Unknown values and non-scalar descendants retain the private context.+ if (/^token[_-]?type$/i.test(key) && typeof child === 'string' && /^(?:Bearer|DPoP)$/i.test(child)) continue;// Credential-bearing containers remain private through array indices and// nested objects; unrelated sibling fields keep their own classification.collect(child, credentialValue || CREDENTIAL_FIELD.test(key));diff --git a/apps/desktop/src/main/bot-import/sourceAutomations.ts b/apps/desktop/src/main/bot-import/sourceAutomations.tsindex 443319479e..752966aa97 100644--- a/apps/desktop/src/main/bot-import/sourceAutomations.ts+++ b/apps/desktop/src/main/bot-import/sourceAutomations.ts@@ -2,7 +2,7 @@ import { parseRoutineInput, type RoutineTrigger } from '@cindy/maker-scheduler';import { fingerprint } from './files.js';import { object, string, type ImportItem, type ImportSource } from './types.js';import path from 'node:path';-import { importedScriptName, isImportedScriptDependency } from './scripts.js';+import { importedScriptName } from './scripts.js';import { importedCommand } from './commandAutomation.js';/** Runtime counters are not configuration; changes to them must not invalidate a handover. */@@ -11,7 +11,48 @@ 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, occurrence = 0): ImportItem {+/** Snapshot only dependency providers, never the growing list of normalized jobs. */+export function indexAutomationDependencies(items: readonly ImportItem[]) {+ const skills = new Map<string, ImportItem[]>();+ const scripts = new Map<string, ImportItem[]>();+ const scriptNames = new Set<string>();+ const connections: ImportItem[] = [];+ const environment = new Map<string, RegExp | undefined>();+ const order = new Map<ImportItem, number>();+ const text = new Map<ImportItem, string>();+ let toolPolicy = false, model = false;+ for (const [index, item] of items.entries()) {+ if (item.view.category === 'skills' || item.asset || item.mcp) order.set(item, index);+ if (item.view.category === 'skills') {+ const aliases = new Set([item.view.name, ...(item.sourceAlias ? [item.sourceAlias] : []),+ ...(item.sourceDirectory ? [path.basename(item.sourceDirectory)] : [])]);+ for (const alias of aliases) {+ const group = skills.get(alias) ?? [];+ group.push(item); skills.set(alias, group);+ }+ }+ if (item.asset) {+ scriptNames.add(item.asset.name);+ for (let directory = path.posix.dirname(item.asset.name); directory !== '.' && directory !== '/'; directory = path.posix.dirname(directory)) {+ const group = scripts.get(directory) ?? [];+ group.push(item); scripts.set(directory, group);+ }+ }+ if (item.mcp) connections.push(item);+ for (const name of Object.keys(item.env ?? {})) environment.set(name, undefined);+ toolPolicy ||= item.credential?.format === 'source-tools';+ model ||= item.credential?.format === 'source-model';+ }+ return { skills, scripts, scriptNames, connections, environment, order, toolPolicy, model,+ text(item: ImportItem): string {+ if (!text.has(item)) text.set(item, item.asset ? item.asset.bytes.toString('utf8')+ : (item.files ?? []).filter(file => /\.(md|py|js|mjs|sh|ts|json|yaml|yml|toml)$/i.test(file.name)).map(file => file.bytes.toString('utf8')).join('\n'));+ return text.get(item)!;+ },+ };+}++export function normalizeAutomation(source: ImportSource, job: Record<string, unknown>, dependencies: ReturnType<typeof indexAutomationDependencies>, timezone: string, occurrence = 0): ImportItem {const sourceId = string(job.id) || string(job.jobId);const schedule = object(job.schedule);const payload = object(job.payload);@@ -37,22 +78,25 @@ export function normalizeAutomation(source: ImportSource, job: Record<string, untry { return [importedScriptName(source.root, file)]; }catch { issues.push('AUTOMATION_SCRIPT_MISSING'); return []; }});- const scriptItems = items.filter(item => item.asset && isImportedScriptDependency(item.asset.name, scriptNames));- const skillItems = items.filter(item => item.view.category === 'skills'- && (selectedSkills.has(item.view.name) || !!item.sourceAlias && selectedSkills.has(item.sourceAlias) || !!item.sourceDirectory && selectedSkills.has(path.basename(item.sourceDirectory))));- const searchText = [prompt, ...(command ? [command.command, ...command.args, command.input ?? ''] : []), ...scriptItems.map(item => item.asset!.bytes.toString('utf8')), ...skillItems.flatMap(item => (item.files ?? []).filter(file => /\.(md|py|js|mjs|sh|ts|json|yaml|yml|toml)$/i.test(file.name)).map(file => file.bytes.toString('utf8')))].join('\n');- const dependsOn = items.filter(item =>- skillItems.includes(item) ||- item.mcp && searchText.includes(item.mcp.name) || scriptItems.includes(item)).map(item => item.view.id);- const environmentNames = [...new Set(items.flatMap(item => Object.keys(item.env ?? {})))].filter(key => new RegExp(`\\b${key}\\b`).test(searchText));- if (scriptNames.some(name => !scriptItems.some(item => item.asset!.name === name))) issues.push('AUTOMATION_SCRIPT_MISSING');+ const scriptItems = new Set(scriptNames.flatMap(name => dependencies.scripts.get(path.posix.dirname(name)) ?? []));+ const skillItems = new Set([...selectedSkills].flatMap(name => dependencies.skills.get(name) ?? []));+ const searchText = [prompt, ...(command ? [command.command, ...command.args, command.input ?? ''] : []),+ ...[...scriptItems, ...skillItems].map(item => dependencies.text(item))].join('\n');+ const required = new Set([...scriptItems, ...skillItems,+ ...dependencies.connections.filter(item => searchText.includes(item.mcp!.name))]);+ const dependsOn = [...required].sort((a, b) => dependencies.order.get(a)! - dependencies.order.get(b)!).map(item => item.view.id);+ const environmentNames = [...dependencies.environment].filter(([name, expression]) => {+ if (!expression) { expression = new RegExp(`\\b${name}\\b`); dependencies.environment.set(name, expression); }+ return expression.test(searchText);+ }).map(([name]) => name);+ if (scriptNames.some(name => !dependencies.scriptNames.has(name))) issues.push('AUTOMATION_SCRIPT_MISSING');if (job.no_agent === true && !job.script) issues.push('AUTOMATION_SCRIPT_MISSING');// These source-specific semantics are retained verbatim and require an explicit adapter.// Never start a simpler task while claiming it inherited a stricter tool policy/model/context.- if (!command && (job.enabled_toolsets || Object.keys(object(job.tools)).length || items.some(item => item.credential?.format === 'source-tools'))) issues.push('SOURCE_TOOL_POLICY_NEEDS_MAPPING');+ if (!command && (job.enabled_toolsets || Object.keys(object(job.tools)).length || dependencies.toolPolicy)) issues.push('SOURCE_TOOL_POLICY_NEEDS_MAPPING');if (job.context_from) issues.push('AUTOMATION_CONTEXT_NEEDS_MAPPING');if (!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');+ || dependencies.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.trim()) issues.push('SOURCE_AUTOMATION_INVALID');// These are explicit source features, not guessed equivalent prompt instructions.diff --git a/apps/desktop/src/main/bot-import/sources.ts b/apps/desktop/src/main/bot-import/sources.tsindex d433102d05..c1c6c78f22 100644--- a/apps/desktop/src/main/bot-import/sources.ts+++ b/apps/desktop/src/main/bot-import/sources.ts@@ -7,7 +7,7 @@ import yaml from 'js-yaml';import { parse as parseEnv } from 'dotenv';import { createImportBudget, fingerprint, optionalText, readImportFile, readImportTree, snapshotFingerprint, type ImportReadBudget } from './files.js';import { discoverImportSkills } from './skills.js';-import { normalizeAutomation } from './sourceAutomations.js';+import { indexAutomationDependencies, normalizeAutomation } from './sourceAutomations.js';import { memoryFileContent } from './memoryFiles.js';import { CompanionImportError, object, string, type ImportItem, type ImportSnapshot, type ImportSource } from './types.js';@@ -334,8 +334,10 @@ export async function inspectImportSource(source: ImportSource, deps: SourceRead}const row = source.kind === 'openclaw' ? agentRows(values).find(row => row.id === source.agentId) ?? {} : values;sourceConfiguration(items, source, values);+ const automationDependencies = indexAutomationDependencies(items);+ const timezone = 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));+ items.push(normalizeAutomation(source, job, automationDependencies, 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 414c2db76f..f652682034 100644--- a/apps/desktop/src/main/bot-import/transfer.ts+++ b/apps/desktop/src/main/bot-import/transfer.ts@@ -4,7 +4,7 @@ import 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, readImportSkillTree } from './skills.js';-import { normalizeAutomation } from './sourceAutomations.js';+import { indexAutomationDependencies, normalizeAutomation } from './sourceAutomations.js';import { memoryFileContent } from './memoryFiles.js';import { resolveImportEnvironmentDependencies, selectedImportEnvironment } from './environmentSelection.js';@@ -259,6 +259,7 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Comconst item = byId.get(id);return !!item?.captureIssue || item?.view.enabled === false && (item.view.category === 'skills' || !!item.mcp) || needsAttention(id) || !!item?.view.issues?.length || !!item?.view.dependsOn?.some(child => missingDependency(child, visited));};+ let automationDependencies: ReturnType<typeof indexAutomationDependencies> | undefined;for (const item of items.filter(item => item.automation)) {// Background reconciliation repairs only interrupted work. A definitive// failed verification needs an explicit retry, never another model/Ask call.@@ -268,7 +269,8 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Comconst automation = item.automation!;if (!automation.input) {// Retry checkpoints created before unsupported tasks had visible drafts.- const restored = normalizeAutomation(snapshot.source, automation.original, items, 'UTC');+ automationDependencies ??= indexAutomationDependencies(items);+ const restored = normalizeAutomation(snapshot.source, automation.original, automationDependencies, 'UTC');automation.input = restored.automation!.input;item.view.issues = [...new Set([...(item.view.issues ?? []), ...(restored.view.issues ?? []), 'SOURCE_AUTOMATION_INVALID'])];}diff --git a/apps/desktop/src/main/routines/__tests__/service.test.ts b/apps/desktop/src/main/routines/__tests__/service.test.tsindex 095c5d52d7..61e1f0593c 100644--- a/apps/desktop/src/main/routines/__tests__/service.test.ts+++ b/apps/desktop/src/main/routines/__tests__/service.test.ts@@ -584,7 +584,8 @@ it('passes the saved reminder choice and check into the shared runner and return});it('persists all imported paused routines before tool-policy setup and never dispatches them', async () => {- const { normalizeAutomation } = await import('../../bot-import/sourceAutomations.js');+ const { indexAutomationDependencies, normalizeAutomation } = await import('../../bot-import/sourceAutomations.js');+ const dependencies = indexAutomationDependencies([]);const guard = vi.fn(async () => { throw new Error('SOURCE_TOOL_POLICY_NEEDS_MAPPING'); });configureRoutineHost({ getBot: mock.getBot, getScheduler: () => mock.scheduler, getScheduleStorage: () => mock.storage, assertImportedAutomationReady: guard });for (let index = 0; index < 11; index++) {@@ -592,7 +593,7 @@ it('persists all imported paused routines before tool-policy setup and never disid: `report-${index}`, name: `Report ${index}`, enabled: false,schedule: { kind: 'every', everyMs: 60_000 }, payload: { message: 'Read the report' },...(index < 4 ? { tools: { allow: ['read'] } } : {}),- }, [], 'UTC');+ }, dependencies, 'UTC');expect(item.automation?.input).toBeDefined();if (index < 4) expect(item.view.issues).toContain('SOURCE_TOOL_POLICY_NEEDS_MAPPING');await routineTools.createOnce('bot', item.automation!.input!, `imported-report-${index}`);