Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(companions): preserve repaired memory roles and redact import credentials

Chrisb639582720c7
diff --git a/apps/desktop/src/main/bot-import/README.md b/apps/desktop/src/main/bot-import/README.md
index 1485001d3e..a8e4a9e4de 100644
--- a/apps/desktop/src/main/bot-import/README.md
+++ b/apps/desktop/src/main/bot-import/README.md
@@ -50,8 +50,11 @@ omitting it retains normal companion defaults, and a rejected request can be cor
bindings. Driver, size and database failures retain distinct safe reason codes.
- Memory discovery includes UTF-8 text (including JSON, backups and extensionless notes) and attachments under the memory trees,
including hidden subdirectories. Hermes `memories/` and a user-maintained `memory/`
- archive stay separate; OpenClaw also includes workspace `DREAMS.md`. Supported media
- originals enter the shared media ledger with a companion-owned import reference
+ archive stay separate; OpenClaw also includes workspace `DREAMS.md`.
+ Retry metadata retains each tree's logical prefix; legacy checkpoints infer it
+ only when the original entry ID and physical memory root agree. Repaired files
+ and subtrees therefore keep distinct archive keys even for identical names.
+ Supported media originals enter the shared media ledger with a companion-owned import reference
and a memory document linking the managed URL. Retry reuses that reference;
companion deletion releases only its own refs through recoverable cleanup.
Empty files such as delivery/lock markers do not become attachment failures. Explicit native memory file links into the source-declared document vault retain their logical names and bounded file reads; undeclared external files and external directory links remain rejected. Retry applies the same classification to legacy checkpoints. Unsupported binary attachments remain visible failures, not silently omitted files.
@@ -69,6 +72,12 @@ omitting it retains normal companion defaults, and a rejected request can be cor
through storage reads and subsequent editor/tool writes. A whitespace-only edit
therefore reports `MEMORY_CHANGED` and keeps the checkpoint pending. Legacy parts
without that marker retain their historical trimmed-body comparison.
+ On a repaired subtree retry, successfully saved role documents update the
+ profile and its baseline before a failed sibling is reported. Missing baseline
+ values do not contribute synthetic blank lines; earlier saved role text remains
+ available even if its memory write temporarily fails on a later retry. Unsaved
+ siblings remain in the checkpoint and user profile edits are not overwritten.
+ Individually repaired memory USER.md files also recover their user role.
Env references and original credentials remain
available to host execution; no model call or extra confirmation is added.
Selected skill folders retain their
@@ -552,6 +561,16 @@ argv, cwd and stdin are now opaque to the read planner, even when a literal secr
is absent from every configured credential map; the original payload remains in
local encrypted storage for authorized execution.
+Readable import copies collect credentials from structured argv/stdin as well as
+command env. The same literal/JSON/URL traversal is shared with output masking;
+publication treats stdin and credential-named options as private literals and
+examines other arguments for structured credential fields and capability URLs.
+It does not blanket-mask ordinary positional arguments or command settings:
+doing so corrupts day counts, output formats and subcommands in imported text.
+Unlabelled opaque positional values are not newly classified as credentials by
+this publication pass. Raw commands, source documents and Skill resources remain
+in the encrypted archive; the existing execution-output mask stays conservative.
+
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`
diff --git a/apps/desktop/src/main/bot-import/__tests__/environmentSelection.test.ts b/apps/desktop/src/main/bot-import/__tests__/environmentSelection.test.ts
index a2882e4040..cd9528f2f3 100644
--- a/apps/desktop/src/main/bot-import/__tests__/environmentSelection.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/environmentSelection.test.ts
@@ -1,5 +1,7 @@
import { expect, it } from 'vitest';
-import { resolveImportReferences } from '../environmentSelection.js';
+import { previewImportRedactions, resolveImportReferences, selectedImportRedactions } from '../environmentSelection.js';
+import { redactEnvironmentValues } from '../process.js';
+import type { ImportItem } from '../types.js';
it('resolves mixed-case Windows references throughout selected MCP and delivery settings', () => {
const env = { api_key: 'fixture-key', Empty: '' };
@@ -20,3 +22,28 @@ it.each(['win32', 'darwin'] as const)('does not resolve absent or inherited vari
expect(() => resolveImportReferences('${TOKEN}', env, false, platform)).toThrow('AUTOMATION_DEPENDENCY_NOT_SELECTED');
expect(resolveImportReferences(['${TOKEN}', '${MISSING}', '$(not-executed)'], env, true, platform)).toEqual(['${TOKEN}', '${MISSING}', '$(not-executed)']);
});
+
+it.each(['stdin-object', 'stdin-string', 'argv-json', 'argv-assignment', 'argv-value', 'nested-url'])
+('masks command %s credentials before publication without altering originals or command syntax', kind => {
+ const secret = 'fixture-private-"quoted"\nvalue';
+ const encoded = JSON.stringify(secret).slice(1, -1);
+ const structured = JSON.stringify({ credentials: [{ privateKeyPem: secret }], city: 'Paris', active: true });
+ const payload: Record<string, unknown> = { kind: 'command', argv: ['node', '-e', '--mode', 'markdown', '--days', '7', 'sessions', 'history'] };
+ if (kind === 'stdin-object') payload.input = structured;
+ if (kind === 'stdin-string') payload.input = JSON.stringify(secret);
+ if (kind === 'argv-json') payload.argv = ['node', '--config', structured];
+ if (kind === 'argv-assignment') payload.argv = ['node', `--config=${structured}`];
+ if (kind === 'argv-value') payload.argv = ['node', '--token', secret];
+ if (kind === 'nested-url') payload.input = JSON.stringify({ endpoint: `https://host/hooks/${encodeURIComponent(secret)}` });
+ const items: ImportItem[] = [{ view: { id: 'job', category: 'automations', name: 'Job', selected: true },
+ automation: { sourceId: 'job', fingerprint: 'fixture', original: { payload } } }];
+ const before = structuredClone(items);
+ for (const collect of [previewImportRedactions, selectedImportRedactions]) {
+ const masks = collect(items);
+ const readable = redactEnvironmentValues(`node -e --mode --token Paris true 7 markdown sessions history ${secret} ${encoded}`, masks);
+ expect(readable).not.toContain(secret);
+ expect(readable).not.toContain(encoded);
+ expect(readable).toContain('node -e --mode --token Paris true 7 markdown sessions history');
+ }
+ expect(items).toEqual(before);
+});
diff --git a/apps/desktop/src/main/bot-import/__tests__/host.test.ts b/apps/desktop/src/main/bot-import/__tests__/host.test.ts
index 986047d4fa..55395fbf63 100644
--- a/apps/desktop/src/main/bot-import/__tests__/host.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/host.test.ts
@@ -413,17 +413,18 @@ it.each([false, true])('redacts all known credentials from profile/memory copies
});
});
-it.each([false, true])('publishes structured command env credentials safely (command selected: %s)', async selected => {
+it.each([false, true])('publishes command env/argv/stdin credentials safely (command selected: %s)', async selected => {
const secret = 'fixture-command-json-token';
const nested = 'fixture-command-json-nested';
+ const literalSecrets = ['fixture-argv-token', 'fixture-stdin-token', 'fixture-plain-token'];
const urlSecrets = ['fixture-hook-token', 'fixture-fragment token', 'fixture-fragment%20token',
'fixture-raw token', 'fixture-raw%20token', 'fixture-raw-query', 'fixture-raw-fragment'];
const config = JSON.stringify({ token: secret, credentials: [{ key: nested }],
services: [{ endpoint: 'https://host/hooks/fixture-hook-token#access_token=fixture-fragment%20token' }],
unused: { password: 'fixture-unused-command-secret' }, city: 'Paris', count: 7 });
- const text = `Keep Paris and 7. ${secret} ${nested} ${urlSecrets.join(' ')}`;
+ const text = `Keep node --mode -e, Paris and 7. ${secret} ${nested} ${urlSecrets.join(' ')} ${literalSecrets.join(' ')}`;
const skill = `---\nname: report\ndescription: ${text}\n---\n${text}\n`;
- const original = { enabled: false, payload: { kind: 'command', argv: ['node', '-e', ''], env: { CONFIG: config, WEBHOOK_URL: 'https://host/hooks/fixture-raw%20token?token=fixture-raw-query#access_token=fixture-raw-fragment' } } };
+ const original = { enabled: false, payload: { kind: 'command', argv: ['node', '-e', '', '--config=' + JSON.stringify({ token: literalSecrets[0], city: 'Paris' }), '--token=' + literalSecrets[2]], input: JSON.stringify({ credentials: [{ privateKeyPem: literalSecrets[1] }], count: 7 }), env: { CONFIG: config, WEBHOOK_URL: 'https://host/hooks/fixture-raw%20token?token=fixture-raw-query#access_token=fixture-raw-fragment' } } };
h.sourceEnabled = false;
h.snapshot.items = [
{ view: { id: 'task', name: text, category: 'automations', selected, enabled: false }, automation: { sourceId: 'task', fingerprint: 'fixture', original,
@@ -434,7 +435,7 @@ it.each([false, true])('publishes structured command env credentials safely (com
];
const [source] = await listCompanionImportSources('fixture');
const remote = await readRemoteCompanionImport(`preview:${source!.id}`, 'fixture', false);
- for (const value of [secret, nested, ...urlSecrets]) expect(JSON.stringify(remote)).not.toContain(value);
+ for (const value of [secret, nested, ...urlSecrets, ...literalSecrets]) expect(JSON.stringify(remote)).not.toContain(value);
const preview = await previewCompanionImport(source!.id, 'fixture');
const requestId = 'fixture-json-command-publication';
const result = await startCompanionImport({ requestId, previewId: preview.id, name: 'Ada',
@@ -443,8 +444,8 @@ it.each([false, true])('publishes structured command env credentials safely (com
const published = await fs.readFile(path.join(h.root, 'bots', result.botId, 'skills/report/SKILL.md'), 'utf8');
const receiptText = await fs.readFile(path.join(h.root, 'companion-imports', `${requestId}.json`), 'utf8');
const output = JSON.stringify([published, h.importDocument.mock.calls, h.routines, receiptText]);
- for (const value of [secret, nested, ...urlSecrets]) expect(output).not.toContain(value);
- expect(published).toContain('Keep Paris and 7.');
+ for (const value of [secret, nested, ...urlSecrets, ...literalSecrets]) expect(output).not.toContain(value);
+ expect(published).toContain('Keep node --mode -e, Paris and 7.');
const stored = (await h.store.read(h.root, result.botId, () => {}))!;
expect(stored.documents?.memory).toBe(text);
const savedSkill = stored.skillFiles?.report?.find(file => file.name === 'SKILL.md');
@@ -1361,6 +1362,92 @@ it('continues healthy recovered documents when a sibling attachment fails', asyn
expect(h.importMedia).toHaveBeenLastCalledWith(accepted.botId, 'chat', original.bytes, expect.any(Function));
});
+it('applies healthy recovered role text even while an attachment keeps failing', async () => {
+ const directory = path.join(h.root, 'memories', 'broken');
+ const brokenId = `memory-${fingerprint('memories/broken').slice(0, 20)}`;
+ h.snapshot.items = [{ view: { id: brokenId, name: 'broken', category: 'memory', selected: true },
+ sourceFile: { root: path.dirname(directory), file: directory, kind: 'directory' }, captureIssue: 'IMPORT_PERMISSION_DENIED' }];
+ const [source] = await listCompanionImportSources('fixture');
+ const preview = await previewCompanionImport(source!.id, 'fixture');
+ const selection = { requestId: 'mixed-repaired-role-fixture', previewId: preview.id, name: 'Ada', entryIds: [brokenId], takeover: false, deferSetup: true };
+ const accepted = await startCompanionImport(selection, 'fixture');
+ await withBotProfileLocks([accepted.botId], () => getCompanionImportResult(selection.requestId));
+ await fs.mkdir(directory, { recursive: true });
+ await fs.writeFile(path.join(directory, 'USER.md'), 'Healthy user preferences');
+ await fs.writeFile(path.join(directory, 'bad.bin'), Buffer.from([0, 255, 0, 255]));
+ await fs.mkdir(path.join(directory, 'later'));
+ await fs.writeFile(path.join(directory, 'later/USER.md'), 'Later user preferences');
+ let failRole = true; let failEarlierRole = false;
+ h.importDocument.mockImplementation(async (_bot, _id, name) => {
+ if ((failRole && name.endsWith('later/USER.md')) || (failEarlierRole && !name.endsWith('later/USER.md'))) throw Object.assign(new Error('full'), { code: 'ENOSPC' });
+ });
+ h.importMedia.mockRejectedValue(Object.assign(new Error('unsupported'), { code: 'SOURCE_MEMORY_ATTACHMENT_UNSUPPORTED' }));
+ await startCompanionImport(selection, 'fixture');
+ let result = await withBotProfileLocks([accepted.botId], () => getCompanionImportResult(selection.requestId));
+ expect(h.profile.userContextSource).toBe('Healthy user preferences');
+ expect(result?.status).toBe('needs-attention');
+ expect(result?.savedEntryIds ?? []).not.toContain(brokenId);
+ expect(result?.checks.find(check => check.entryId === brokenId)?.progress).toEqual({ saved: 1, total: 3 });
+ const stored = (await h.store.read(h.root, accepted.botId, () => {}))!;
+ expect(Object.values(stored.documents ?? {})).toContain('Healthy user preferences');
+ expect(stored.pendingImport).toBeDefined();
+ expect(Object.values(stored.documents ?? {})).not.toContain('Later user preferences');
+ failRole = false; failEarlierRole = true;
+ await startCompanionImport(selection, 'fixture');
+ await withBotProfileLocks([accepted.botId], () => getCompanionImportResult(selection.requestId));
+ expect(h.profile.userContextSource).toContain('Healthy user preferences');
+ expect(h.profile.userContextSource).toContain('Later user preferences');
+ failEarlierRole = false;
+ // A later retry of the bad attachment must preserve edits to the applied profile.
+ h.profile.userContextSource = 'User edited preferences';
+ await startCompanionImport(selection, 'fixture');
+ result = await withBotProfileLocks([accepted.botId], () => getCompanionImportResult(selection.requestId));
+ expect(h.profile.userContextSource).toBe('User edited preferences');
+ expect(result?.status).toBe('needs-attention');
+});
+
+it.each([['file', true], ['directory', true], ['file', false], ['directory', false]] as const)('keeps both memory root prefixes when repairing %s entries (legacy=%s)', async (kind, legacy) => {
+ const name = kind === 'directory' ? 'broken' : 'state.lock';
+ h.snapshot.items = ['memories', 'memory'].map(prefix => ({
+ view: { id: `memory-${fingerprint(`${prefix}/${name}`).slice(0, 20)}`, name, category: 'memory', selected: true },
+ sourceFile: { root: path.join(h.root, prefix), file: path.join(h.root, prefix, name), kind, ...(legacy ? {} : { logicalPrefix: prefix }) }, captureIssue: 'IMPORT_PERMISSION_DENIED',
+ }));
+ const [source] = await listCompanionImportSources('fixture');
+ const preview = await previewCompanionImport(source!.id, 'fixture');
+ const selection = { requestId: `memory-prefix-${kind}-fixture`, previewId: preview.id, name: 'Ada', entryIds: h.snapshot.items.map(item => item.view.id), takeover: false, deferSetup: true };
+ const accepted = await startCompanionImport(selection, 'fixture');
+ await withBotProfileLocks([accepted.botId], () => getCompanionImportResult(selection.requestId));
+ const suffix = kind === 'directory' ? 'broken/state.lock' : 'state.lock';
+ const originals = { [`memories/${suffix}`]: Buffer.alloc(0), [`memory/${suffix}`]: Buffer.from(' \n') };
+ for (const [name, bytes] of Object.entries(originals)) {
+ await fs.mkdir(path.dirname(path.join(h.root, name)), { recursive: true });
+ await fs.writeFile(path.join(h.root, name), bytes);
+ }
+ await startCompanionImport(selection, 'after-restart');
+ const result = await withBotProfileLocks([accepted.botId], () => getCompanionImportResult(selection.requestId));
+ expect(result?.status).toBe('complete');
+ expect((await h.store.read(h.root, accepted.botId, () => {}))?.memoryFiles)
+ .toEqual(Object.fromEntries(Object.entries(originals).map(([name, bytes]) => [name, bytes.toString('base64')])));
+});
+
+it('recovers the user role of an individually failed memory USER.md', async () => {
+ const file = path.join(h.root, 'memories/USER.md');
+ const id = `memory-${fingerprint('memories/USER.md').slice(0, 20)}`;
+ h.snapshot.items = [{ view: { id, name: 'USER.md', category: 'memory', selected: true },
+ sourceFile: { root: path.dirname(file), file, kind: 'file', logicalPrefix: 'memories' }, captureIssue: 'IMPORT_PERMISSION_DENIED' }];
+ const [source] = await listCompanionImportSources('fixture');
+ const preview = await previewCompanionImport(source!.id, 'fixture');
+ const selection = { requestId: 'memory-user-role-recovery', previewId: preview.id, name: 'Ada', entryIds: [id], takeover: false, deferSetup: true };
+ const accepted = await startCompanionImport(selection, 'fixture');
+ await withBotProfileLocks([accepted.botId], () => getCompanionImportResult(selection.requestId));
+ await fs.mkdir(path.dirname(file), { recursive: true });
+ await fs.writeFile(file, 'User preferences');
+ await startCompanionImport(selection, 'after-restart');
+ await withBotProfileLocks([accepted.botId], () => getCompanionImportResult(selection.requestId));
+ expect(h.profile.userContextSource).toBe('User preferences');
+ expect(h.importDocument).toHaveBeenCalledWith(accepted.botId, id, 'USER.md', 'User preferences', 'user');
+});
+
it('retains managed media by ledger reference without copying its bytes into execution assets', async () => {
const image = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
const script = Buffer.from('print("fixture")');
diff --git a/apps/desktop/src/main/bot-import/__tests__/sources.test.ts b/apps/desktop/src/main/bot-import/__tests__/sources.test.ts
index b2de781992..01711a270b 100644
--- a/apps/desktop/src/main/bot-import/__tests__/sources.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/sources.test.ts
@@ -538,7 +538,7 @@ it.each(['hermes', 'openclaw'] as const)('records a failed %s memory subtree sep
}) as typeof fs.open);
const reader = deps(); const [source] = await discoverImportSources(reader);
const snapshot = await inspectImportSource(source!, reader);
- expect(snapshot.items.find(item => item.view.name === 'broken')?.sourceFile).toMatchObject({ root: path.join(home, folder), file: path.join(home, folder, 'broken'), kind: 'directory' });
+ expect(snapshot.items.find(item => item.view.name === 'broken')?.sourceFile).toMatchObject({ root: path.join(home, folder), file: path.join(home, folder, 'broken'), kind: 'directory', logicalPrefix: kind === 'hermes' ? 'memories' : 'memory' });
expect(snapshot.items.find(item => item.view.name === 'bad.md')?.sourceFile?.kind).toBe('file');
expect(snapshot.items.find(item => item.view.name === 'healthy.md')?.text).toBe('Keep healthy');
});
diff --git a/apps/desktop/src/main/bot-import/automationRuntime.ts b/apps/desktop/src/main/bot-import/automationRuntime.ts
index c22ff66e36..fe3fdddd7e 100644
--- a/apps/desktop/src/main/bot-import/automationRuntime.ts
+++ b/apps/desktop/src/main/bot-import/automationRuntime.ts
@@ -10,9 +10,10 @@ import { writeImportFiles } from './files.js';
import { importedProcessEnvironment, redactEnvironmentValues, runImportedProcess } from './process.js';
import { sendImportedDelivery } from './delivery.js';
import { importedScriptName, importedScriptInterpreter } from './scripts.js';
-import { importedContentRedactions, urlCredentialValues } from './connectionCatalog.js';
+import { importedContentRedactions } from './connectionCatalog.js';
import type { CompanionEnvironment } from './environment.js';
import { importedCommand } from './commandAutomation.js';
+import { commandLiteralRedactions } from './commandRedactions.js';
/** Command literals are private too, including values supplied without env names. */
async function outputSecrets(environment: CompanionEnvironment, job: Record<string, unknown>, command: ReturnType<typeof importedCommand>) {
@@ -21,37 +22,10 @@ async function outputSecrets(environment: CompanionEnvironment, job: Record<stri
}, job.monitor_url ? [string(job.monitor_url)] : []);
if (!command) return secrets;
const cwd = command.cwd ? await fs.realpath(command.cwd).catch(() => undefined) : undefined;
- const values = [command.command, command.cwd, cwd, command.input,
- ...command.args.flatMap(arg => [arg, /^--?[\w-]+=(.+)$/s.exec(arg)?.[1]])].filter((value): value is string => !!value);
- const structured: CompanionEnvironment['credentials'] = [];
- const urlValues: string[] = [];
- const collectUrls = (value: unknown): void => {
- if (typeof value === 'string') {
- if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) urlValues.push(...urlCredentialValues(value, true));
- } else if (value && typeof value === 'object') Object.values(value).forEach(collectUrls);
- };
- // A URL can carry credentials even in a field named "endpoint". Apply the
- // existing URL policy only to runtime output, preserving imported source text.
- const literals = new Set(values);
- for (const value of new Set([...literals, ...Object.values(environment.env), ...Object.values(command.env)])) {
- collectUrls(value);
- try {
- const parsed: unknown = JSON.parse(value);
- collectUrls(parsed);
- // JSON env objects use the same credential-field rules as argv/stdin;
- // ordinary env scalar settings retain their existing classification.
- if (typeof parsed === 'string' && literals.has(value)) values.push(parsed);
- else if (parsed && typeof parsed === 'object') structured.push({ id: `command_${structured.length}`, format: 'command-input', value: parsed });
- } catch { /* Non-JSON command literals still receive exact-value masking. */ }
- }
- // Reuse credential-field classification for nested objects/arrays, keeping
- // ordinary report values readable. Raw and JSON-escaped children are private.
- values.push(...urlValues, ...Object.values(importedContentRedactions({ env: {}, mcp: [], credentials: structured })));
- for (const [index, value] of [...new Set(values)].entries()) {
- secrets[`command_literal_${index}`] = value;
- const escaped = JSON.stringify(value).slice(1, -1);
- if (escaped !== value) secrets[`command_literal_${index}_json`] = escaped;
- }
+ Object.assign(secrets, commandLiteralRedactions(
+ [command.command, command.cwd, cwd, command.input, ...command.args].filter((value): value is string => !!value),
+ [...Object.values(environment.env), ...Object.values(command.env)],
+ ));
return secrets;
}
diff --git a/apps/desktop/src/main/bot-import/commandRedactions.ts b/apps/desktop/src/main/bot-import/commandRedactions.ts
new file mode 100644
index 0000000000..a1a8d52f5f
--- /dev/null
+++ b/apps/desktop/src/main/bot-import/commandRedactions.ts
@@ -0,0 +1,43 @@
+import { importedContentRedactions, isImportedCredentialField } from './connectionCatalog.js';
+
+/** Shared by readable import copies and execution output; originals stay intact. */
+export function commandLiteralRedactions(literals: string[], environmentValues: string[] = [], maskLiterals = true): Record<string, string> {
+ const candidates = literals.flatMap(value => [value, /^--?[\w-]+=(.+)$/s.exec(value)?.[1]])
+ .filter((value): value is string => !!value);
+ const literalSet = new Set(candidates);
+ const values = maskLiterals ? [...candidates] : [];
+ const structured: { id: string; format: string; value: unknown }[] = [];
+ for (const value of new Set([...candidates, ...environmentValues])) {
+ // command-env applies both the credential-field rules and URL component
+ // traversal, including URLs beneath ordinary structured keys like endpoint.
+ structured.push({ id: `command_${structured.length}`, format: 'command-env', value });
+ try {
+ const parsed: unknown = JSON.parse(value);
+ if (maskLiterals && typeof parsed === 'string' && literalSet.has(value)) values.push(parsed);
+ if ((parsed && typeof parsed === 'object') || typeof parsed === 'string') {
+ structured.push({ id: `command_${structured.length}`, format: 'command-env', value: parsed });
+ }
+ } catch { /* Requested exact literal masks need no JSON parser. */ }
+ }
+ values.push(...Object.values(importedContentRedactions({ env: {}, mcp: [], credentials: structured })));
+ const secrets: Record<string, string> = {};
+ for (const [index, value] of [...new Set(values)].entries()) {
+ secrets[`command_literal_${index}`] = value;
+ const escaped = JSON.stringify(value).slice(1, -1);
+ if (escaped !== value) secrets[`command_literal_${index}_json`] = escaped;
+ }
+ return secrets;
+}
+
+/** Public copies retain ordinary CLI syntax/settings, not a blanket argv mask. */
+export function commandArgumentRedactions(argv: string[]): Record<string, string> {
+ const values: string[] = [];
+ let credentialArgument = false;
+ for (const arg of argv.slice(1)) {
+ const option = /^--?([\w-]+)(?:=([\s\S]*))?$/.exec(arg);
+ const privateValue = option ? isImportedCredentialField(option[1]) && option[2] !== undefined : credentialArgument;
+ values.push(...Object.values(commandLiteralRedactions([arg], [], privateValue)));
+ credentialArgument = !!option && option[2] === undefined && isImportedCredentialField(option[1]);
+ }
+ return Object.fromEntries([...new Set(values)].map((value, index) => [`command_argument_${index}`, value]));
+}
diff --git a/apps/desktop/src/main/bot-import/connectionCatalog.ts b/apps/desktop/src/main/bot-import/connectionCatalog.ts
index b3ace68940..69e1024898 100644
--- a/apps/desktop/src/main/bot-import/connectionCatalog.ts
+++ b/apps/desktop/src/main/bot-import/connectionCatalog.ts
@@ -13,6 +13,8 @@ const CAPABILITY_PATH_PREFIXES = new Set(['hooks', 'webhooks', 'token', 'secret'
// format names and public keys must not become global content masks.
const CREDENTIAL_FIELD = /^(?:keys?|.*(?:api|private|signing|encryption|decryption|secret|access)[_-]?keys?(?:[_-]?(?:pem|base64))?|.*(?:tokens?|secrets?|passwords?|passwds?|pass[_-]?phrases?|credentials?)|auth(?:orization)?|access|refresh|cookies?)$/i;
+export function isImportedCredentialField(name: string): boolean { return CREDENTIAL_FIELD.test(name); }
+
/** Include resolved connection-local values without overwriting same-named imports. */
export function connectionRedactions(server: ImportedMcpServer, environment: Record<string, string>): Record<string, string> {
const values = [...Object.values(environmentRedactions(environment)), ...Object.values(environmentRedactions(server.env ?? {})), ...Object.values(server.headers ?? {})];
diff --git a/apps/desktop/src/main/bot-import/environmentSelection.ts b/apps/desktop/src/main/bot-import/environmentSelection.ts
index daa75f670b..97ce719fe5 100644
--- a/apps/desktop/src/main/bot-import/environmentSelection.ts
+++ b/apps/desktop/src/main/bot-import/environmentSelection.ts
@@ -1,4 +1,5 @@
import { fingerprint } from './files.js';
+import { commandArgumentRedactions, commandLiteralRedactions } from './commandRedactions.js';
import { CompanionImportError, object, type ImportItem } from './types.js';
import { importedContentRedactions } from './connectionCatalog.js';
import { environmentRedactions, redactEnvironmentValues } from './process.js';
@@ -90,9 +91,19 @@ function importRedactions(items: ImportItem[], env: Record<string, string>): Rec
return parsed && typeof parsed === 'object' ? [{ id: `command_${index}`, format: 'command-env', value: parsed }] : [];
} catch { return []; }
});
+ const commandValues = items.flatMap(item => {
+ const payload = object(item.automation?.original.payload);
+ if (payload.kind !== 'command') return [];
+ const args = Array.isArray(payload.argv) ? payload.argv.filter((arg): arg is string => typeof arg === 'string') : [];
+ return [
+ ...Object.values(commandLiteralRedactions(typeof payload.input === 'string' ? [String(resolve(payload.input))] : [])),
+ ...Object.values(commandArgumentRedactions(args.map(arg => String(resolve(arg))))),
+ ];
+ });
+ const literalMasks = Object.fromEntries([...new Set(commandValues)].map((value, index) => [`command_input_${index}`, value]));
return importedContentRedactions({ env,
- contentRedactions: Object.fromEntries(commandEnvironments.flatMap(environment => Object.entries(environmentRedactions(environment)))
- .map(([name, value], index) => [`command_${index}_${name}`, value])),
+ contentRedactions: { ...Object.fromEntries(commandEnvironments.flatMap(environment => Object.entries(environmentRedactions(environment)))
+ .map(([name, value], index) => [`command_${index}_${name}`, value])), ...literalMasks },
mcp: items.flatMap(item => item.mcp ? [resolve(item.mcp) as NonNullable<typeof item.mcp>] : []),
credentials: [...items.flatMap(item => item.credential ? [{ id: item.view.id, ...item.credential, value: resolve(item.credential.value) }] : []), ...structured],
});
diff --git a/apps/desktop/src/main/bot-import/host.ts b/apps/desktop/src/main/bot-import/host.ts
index 7bd11dd3f9..1bd241573e 100644
--- a/apps/desktop/src/main/bot-import/host.ts
+++ b/apps/desktop/src/main/bot-import/host.ts
@@ -547,7 +547,7 @@ export async function startCompanionImport(selection: CompanionImportSelection,
let skillConfigReader: { budget: Parameters<NonNullable<TransferDeps['readSkillConfig']>>[1]; reader: ReturnType<typeof createImportSourceReader> } | undefined;
const applyProfile = async (botId: string, items: ImportItem[], baseline?: Record<string, string>, originals?: Record<string, string>) => {
const roleText = (role: 'identity' | 'user' | 'instructions', originals?: Record<string, string>) => {
- const text = redactText(items.flatMap(item => [...(item.role === role ? [originals ? originals[item.view.id] : item.text] : []), ...(item.documents ?? []).filter(document => document.role === role).map(document => originals ? originals[document.id] : document.text)]).join('\n\n'));
+ const text = redactText(items.flatMap(item => [...(item.role === role ? [originals ? originals[item.view.id] : item.text] : []), ...(item.documents ?? []).filter(document => document.role === role).map(document => originals ? originals[document.id] : document.text)]).filter((value): value is string => typeof value === 'string').join('\n\n'));
if (Buffer.byteLength(text, 'utf8') <= BOT_PROFILE_TEXT_MAX_BYTES) return text;
// Keep the original profile text without synthesizing new system instructions.
// The entire source remains in personal memory and the encrypted document archive.
@@ -623,6 +623,8 @@ export async function startCompanionImport(selection: CompanionImportSelection,
}
},
async importItem(botId, item) {
+ let pendingFailure: Error | undefined;
+ let persistedItem = item;
if (item.view.category === 'skills') {
const slug = skillSlug(item);
const projected = projectImportedSkill(item.files ?? [], slug, contentSecrets);
@@ -650,6 +652,7 @@ export async function startCompanionImport(selection: CompanionImportSelection,
}
}
let total = failedAttachments, saved = 0;
+ const savedDocuments = new Set<string>();
for (const document of documents) {
let parts = 1; total++;
try {
@@ -658,7 +661,7 @@ export async function startCompanionImport(selection: CompanionImportSelection,
parts = splitImportedMemoryText(text).length;
total += parts - 1;
await getBotMemoryService().importDocument(botId, document.id, redactText(document.name), text, document.role === 'user' ? 'user' : 'reference');
- saved += parts;
+ saved += parts; savedDocuments.add(document.id);
} catch (error) {
scope.assert();
const progress = (error as { importProgress?: { saved: number; total: number } })?.importProgress;
@@ -668,14 +671,18 @@ export async function startCompanionImport(selection: CompanionImportSelection,
}
if (firstFailure) {
const error = firstFailure instanceof Error ? firstFailure : new CompanionImportError('IMPORT_ITEM_FAILED');
- throw Object.assign(error, { importProgress: { saved, total } });
+ pendingFailure = Object.assign(error, { importProgress: { saved, total } });
+ // Failed siblings remain in the encrypted checkpoint. Only documents
+ // saved in full may advance the profile projection and its baseline.
+ persistedItem = { ...item, text: savedDocuments.has(item.view.id) ? item.text : undefined,
+ documents: item.documents?.filter(document => savedDocuments.has(document.id)) };
}
}
if (prior?.environmentSaved && (item.role || item.documents?.some(document => document.role))) {
const environment = await companionEnvironmentStore.read(scope.root, botId, scope.assert);
const previous = environment?.documents ?? {};
await applyProfile(botId, selected.map(candidate => candidate.view.id === item.view.id ? item : candidate), previous,
- { ...previous, ...Object.fromEntries(documentEntries(item)) });
+ { ...previous, ...Object.fromEntries(documentEntries(persistedItem)) });
}
if (prior?.environmentSaved) await companionEnvironmentStore.update(scope.root, botId, scope.assert, environment => {
// A formerly unreadable manifest may only now supply its own settings.
@@ -689,7 +696,7 @@ export async function startCompanionImport(selection: CompanionImportSelection,
}
} else if (item.asset) environment.files = { ...environment.files, [item.asset.name]: item.asset.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; }
+ for (const [id, text] of documentEntries(persistedItem)) { environment.documents ??= {}; environment.documents[id] = text; }
if (item.view.category === 'skills') {
const slug = skillSlug(item);
const originals = projectImportedSkill(item.files ?? [], slug, contentSecrets).originals;
@@ -697,6 +704,7 @@ export async function startCompanionImport(selection: CompanionImportSelection,
}
environment.contentRedactions = { ...environment.contentRedactions, ...publicationRedactions([item]) };
});
+ if (pendingFailure) throw pendingFailure;
},
async saveCheckpoint(botId, items) {
const previous = await companionEnvironmentStore.read(scope.root, botId, scope.assert);
diff --git a/apps/desktop/src/main/bot-import/sources.ts b/apps/desktop/src/main/bot-import/sources.ts
index c1c6c78f22..60b7a6d2fd 100644
--- a/apps/desktop/src/main/bot-import/sources.ts
+++ b/apps/desktop/src/main/bot-import/sources.ts
@@ -129,7 +129,7 @@ async function memoryDocuments(items: ImportItem[], root: string, prefix: string
if (!(await directories(root)).includes(prefix)) return;
const directory = path.join(root, prefix);
const failed = (name: string, error: unknown, kind: 'file' | 'directory' | 'unknown') => items.push({ view: { id: entryId('memory', `${prefix}/${name}`), category: 'memory', name: name || prefix, selected: true },
- sourceFile: { root: directory, file: path.join(directory, name), kind, sharedDocumentRoots }, captureIssue: error instanceof CompanionImportError ? error.code : 'IMPORT_ITEM_FAILED' });
+ sourceFile: { root: directory, file: path.join(directory, name), kind, logicalPrefix: prefix, sharedDocumentRoots }, captureIssue: error instanceof CompanionImportError ? error.code : 'IMPORT_ITEM_FAILED' });
let files;
try { files = await readImportTree(directory, undefined, budget, failed, directory, sharedDocumentRoots); }
catch (error) { failed('', error, 'directory'); return; }
diff --git a/apps/desktop/src/main/bot-import/transfer.ts b/apps/desktop/src/main/bot-import/transfer.ts
index 1e694401fb..1c3efad9fc 100644
--- a/apps/desktop/src/main/bot-import/transfer.ts
+++ b/apps/desktop/src/main/bot-import/transfer.ts
@@ -1,4 +1,5 @@
import { promises as fs } from 'node:fs';
+import path from 'node:path';
import type { CompanionImportResult, CompanionImportSelection } from '@cindy/maker-shared/companion-import';
import type { RoutineInput } from '@cindy/maker-scheduler';
import { createImportBudget, fingerprint, readImportFile, readImportTree, reserveSnapshotItems, type ImportReadBudget } from './files.js';
@@ -160,13 +161,21 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com
try {
const source = item.sourceFile;
const sharedDocumentRoots = source.sharedDocumentRoots ?? [];
+ // Older checkpoints recorded only the physical root. Recover its
+ // logical prefix only when both the known root and original entry ID
+ // agree; custom/standalone document checkpoints keep their old names.
+ const relative = path.relative(source.root, source.file).split(path.sep).join('/');
+ const prefix = source.logicalPrefix ?? ['memories', 'memory'].find(candidate =>
+ path.basename(source.root) === candidate && item.view.id === `memory-${fingerprint(`${candidate}/${relative}`).slice(0, 20)}`);
+ const logicalName = (name: string) => prefix ? `${prefix}/${name}` : name;
// Missing kind is a legacy checkpoint. Re-evaluate repaired paths, but
// keep containment anchored to the original memory root in either case.
const directory = source.kind === 'directory' || source.kind !== 'file' && (await fs.stat(source.file)).isDirectory();
if (directory) {
const files = await readImportTree(source.root, undefined, budget, undefined, source.file, sharedDocumentRoots);
item.files = []; item.documents = [];
- for (const file of files) {
+ for (const captured of files) {
+ const file = { ...captured, name: logicalName(captured.name) };
const content = memoryFileContent(file);
if (content.kind !== 'text') item.files.push(file);
else if (content.kind === 'text') item.documents.push({
@@ -175,9 +184,14 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com
});
}
} else {
- const file = await readImportFile(source.root, source.file, budget, sharedDocumentRoots);
+ const captured = await readImportFile(source.root, source.file, budget, sharedDocumentRoots);
+ const file = { ...captured, name: logicalName(captured.name) };
const content = memoryFileContent(file);
- if (content.kind === 'text') item.text = content.text;
+ if (content.kind === 'text') {
+ item.text = content.text;
+ // A failed individual USER.md has no role from initial discovery.
+ if (!item.role && /(^|\/)USER\.md$/i.test(file.name)) item.role = 'user';
+ }
else item.asset = { name: file.name, bytes: file.bytes };
}
delete item.captureIssue;
diff --git a/apps/desktop/src/main/bot-import/types.ts b/apps/desktop/src/main/bot-import/types.ts
index b14b87530d..898665c4a5 100644
--- a/apps/desktop/src/main/bot-import/types.ts
+++ b/apps/desktop/src/main/bot-import/types.ts
@@ -46,7 +46,7 @@ export interface ImportItem {
sourceDirectory?: string;
sourceAlias?: string;
/** Failed document or subtree read; retained for an explicit retry. */
- sourceFile?: { root: string; file: string; kind?: 'file' | 'directory' | 'unknown'; sharedDocumentRoots?: string[] };
+ sourceFile?: { root: string; file: string; kind?: 'file' | 'directory' | 'unknown'; logicalPrefix?: string; sharedDocumentRoots?: string[] };
/** Recovered subtree documents stay under the original selected entry/receipt. */
documents?: Array<{ id: string; name: string; text: string; role?: 'user' }>;
/** Selected skill resources have been captured for copying, verification and restart. */