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(cross-agent-convert): 修正 Codex hooks 双向转换的顶层结构并避免重复提示

Saurabh Pathakd3be89799d2a
diff --git a/apps/desktop/src/main/cross-agent-convert/__tests__/detector.test.ts b/apps/desktop/src/main/cross-agent-convert/__tests__/detector.test.ts
index 1e64613272..f947ad3e89 100644
--- a/apps/desktop/src/main/cross-agent-convert/__tests__/detector.test.ts
+++ b/apps/desktop/src/main/cross-agent-convert/__tests__/detector.test.ts
@@ -227,4 +227,20 @@ describe('detect — hooks', () => {
const r = await detect({ workingDir: tmpDir, agentKind: 'codex' });
expect(r.items.find((i) => i.kind === 'hooks')).toBeUndefined();
});
+
+ it('to-claude: source has only hooks.json (no hooks/ dir) and target has hooks config → no item', async () => {
+ await fs.mkdir(path.join(tmpDir, '.codex'), { recursive: true });
+ await fs.writeFile(path.join(tmpDir, '.codex', 'hooks.json'), JSON.stringify({ hooks: { Stop: [] } }));
+ await fs.mkdir(path.join(tmpDir, '.claude'), { recursive: true });
+ await fs.writeFile(path.join(tmpDir, '.claude', 'settings.json'), JSON.stringify({ hooks: { Stop: [] } }));
+ const r = await detect({ workingDir: tmpDir, agentKind: 'claude-code' });
+ expect(r.items.find((i) => i.kind === 'hooks')).toBeUndefined();
+ });
+
+ it('to-claude: source has only hooks.json and target lacks hooks → 1 item', async () => {
+ await fs.mkdir(path.join(tmpDir, '.codex'), { recursive: true });
+ await fs.writeFile(path.join(tmpDir, '.codex', 'hooks.json'), JSON.stringify({ hooks: { Stop: [] } }));
+ const r = await detect({ workingDir: tmpDir, agentKind: 'claude-code' });
+ expect(r.items.find((i) => i.kind === 'hooks')).toBeDefined();
+ });
});
diff --git a/apps/desktop/src/main/cross-agent-convert/__tests__/hooks.test.ts b/apps/desktop/src/main/cross-agent-convert/__tests__/hooks.test.ts
index 3fa8874ccd..4815d80c5f 100644
--- a/apps/desktop/src/main/cross-agent-convert/__tests__/hooks.test.ts
+++ b/apps/desktop/src/main/cross-agent-convert/__tests__/hooks.test.ts
@@ -52,9 +52,11 @@ describe('convertHooks — to-codex', () => {
expect(await fs.readFile(path.join(wd, '.codex', 'hooks', 'pre.sh'), 'utf8')).toContain('echo hi');
const json = JSON.parse(await fs.readFile(path.join(wd, '.codex', 'hooks.json'), 'utf8'));
// Codex 用 camelCase 与 Claude 完全一致
- expect(json.PreToolUse).toBeDefined();
- expect(JSON.stringify(json.PreToolUse)).toContain('.codex/hooks/pre.sh');
- expect(JSON.stringify(json.PreToolUse)).not.toContain('.claude/hooks/');
+ // Codex 规范:事件放在顶层 "hooks" 对象内
+ expect(json.PreToolUse).toBeUndefined();
+ expect(json.hooks.PreToolUse).toBeDefined();
+ expect(JSON.stringify(json.hooks.PreToolUse)).toContain('.codex/hooks/pre.sh');
+ expect(JSON.stringify(json.hooks.PreToolUse)).not.toContain('.claude/hooks/');
});
it('skips events that already exist in target hooks.json (no overwrite)', async () => {
@@ -67,13 +69,41 @@ describe('convertHooks — to-codex', () => {
}));
await fs.mkdir(path.join(wd, '.codex'), { recursive: true });
await fs.writeFile(path.join(wd, '.codex', 'hooks.json'), JSON.stringify({
- PreToolUse: 'USER_ORIGINAL',
+ hooks: { PreToolUse: 'USER_ORIGINAL' },
}));
const r = await convertHooks(toCodexItem());
expect(r.status).toBe('success'); // still success because script was copied
const json = JSON.parse(await fs.readFile(path.join(wd, '.codex', 'hooks.json'), 'utf8'));
- expect(json.PreToolUse).toBe('USER_ORIGINAL');
+ expect(json.hooks.PreToolUse).toBe('USER_ORIGINAL');
+ });
+
+ it('upgrades a legacy flat hooks.json into the wrapped { hooks: {...} } shape', async () => {
+ await fs.mkdir(path.join(wd, '.claude'), { recursive: true });
+ await fs.writeFile(path.join(wd, '.claude', 'settings.json'), JSON.stringify({
+ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'echo stop' }] }] },
+ }));
+ await fs.mkdir(path.join(wd, '.codex'), { recursive: true });
+ await fs.writeFile(path.join(wd, '.codex', 'hooks.json'), JSON.stringify({ PreToolUse: 'FLAT' }));
+
+ const r = await convertHooks({ ...toCodexItem(), source: path.join(wd, '.claude', 'hooks') });
+ expect(r.status).toBe('success');
+ const json = JSON.parse(await fs.readFile(path.join(wd, '.codex', 'hooks.json'), 'utf8'));
+ expect(json.PreToolUse).toBeUndefined();
+ expect(json.hooks.PreToolUse).toBe('FLAT');
+ expect(json.hooks.Stop).toBeDefined();
+ });
+
+ it('flattens a mis-nested settings.hooks.hooks when reading Claude hooks', async () => {
+ await fs.mkdir(path.join(wd, '.claude'), { recursive: true });
+ await fs.writeFile(path.join(wd, '.claude', 'settings.json'), JSON.stringify({
+ hooks: { hooks: { SessionStart: [{ hooks: [{ type: 'command', command: 'echo s' }] }] } },
+ }));
+ const r = await convertHooks(toCodexItem());
+ expect(r.status).toBe('success');
+ const json = JSON.parse(await fs.readFile(path.join(wd, '.codex', 'hooks.json'), 'utf8'));
+ expect(json.hooks.SessionStart).toBeDefined();
+ expect(json.hooks.hooks).toBeUndefined();
});
});
@@ -84,7 +114,7 @@ describe('convertHooks — to-claude', () => {
await fs.mkdir(codexHooks, { recursive: true });
await fs.writeFile(path.join(codexHooks, 'p.sh'), 'echo p');
await fs.writeFile(codexJson, JSON.stringify({
- PreToolUse: { command: '.codex/hooks/p.sh' },
+ hooks: { PreToolUse: [{ matcher: '*', hooks: [{ type: 'command', command: '.codex/hooks/p.sh' }] }] },
}));
const r = await convertHooks(toClaudeItem());
@@ -93,6 +123,37 @@ describe('convertHooks — to-claude', () => {
const settings = JSON.parse(await fs.readFile(path.join(wd, '.claude', 'settings.json'), 'utf8'));
expect(settings.hooks.PreToolUse).toBeDefined();
expect(JSON.stringify(settings.hooks.PreToolUse)).toContain('.claude/hooks/p.sh');
+ // 不得把 Codex 的外层 "hooks" 包装当作事件名写进 settings.hooks
+ expect(settings.hooks.hooks).toBeUndefined();
+ });
+
+ it('still accepts a legacy flat hooks.json', async () => {
+ await fs.mkdir(path.join(wd, '.codex'), { recursive: true });
+ await fs.writeFile(path.join(wd, '.codex', 'hooks.json'), JSON.stringify({
+ Stop: [{ hooks: [{ type: 'command', command: 'echo x' }] }],
+ }));
+ const r = await convertHooks(toClaudeItem());
+ expect(r.status).toBe('success');
+ const settings = JSON.parse(await fs.readFile(path.join(wd, '.claude', 'settings.json'), 'utf8'));
+ expect(settings.hooks.Stop).toBeDefined();
+ });
+
+ it('repairs a pre-existing settings.hooks.hooks nesting', async () => {
+ const claudeSettings = path.join(wd, '.claude', 'settings.json');
+ await fs.mkdir(path.dirname(claudeSettings), { recursive: true });
+ await fs.writeFile(claudeSettings, JSON.stringify({
+ hooks: { hooks: { SessionStart: [{ hooks: [{ type: 'command', command: 'echo s' }] }] } },
+ }));
+ await fs.mkdir(path.join(wd, '.codex'), { recursive: true });
+ await fs.writeFile(path.join(wd, '.codex', 'hooks.json'), JSON.stringify({
+ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'echo x' }] }] },
+ }));
+ const r = await convertHooks(toClaudeItem());
+ expect(r.status).toBe('success');
+ const settings = JSON.parse(await fs.readFile(claudeSettings, 'utf8'));
+ expect(settings.hooks.hooks).toBeUndefined();
+ expect(settings.hooks.SessionStart).toBeDefined();
+ expect(settings.hooks.Stop).toBeDefined();
});
it('merges into existing settings.json without removing other top-level keys', async () => {
@@ -101,7 +162,7 @@ describe('convertHooks — to-claude', () => {
await fs.writeFile(claudeSettings, JSON.stringify({ permissions: 'user-keeps' }));
await fs.mkdir(path.join(wd, '.codex'), { recursive: true });
await fs.writeFile(path.join(wd, '.codex', 'hooks.json'), JSON.stringify({
- Stop: { command: '.codex/hooks/done.sh' },
+ hooks: { Stop: [{ hooks: [{ type: 'command', command: '.codex/hooks/done.sh' }] }] },
}));
const r = await convertHooks(toClaudeItem());
diff --git a/apps/desktop/src/main/cross-agent-convert/converters/hooks.ts b/apps/desktop/src/main/cross-agent-convert/converters/hooks.ts
index d334541b63..d6e6864b44 100644
--- a/apps/desktop/src/main/cross-agent-convert/converters/hooks.ts
+++ b/apps/desktop/src/main/cross-agent-convert/converters/hooks.ts
@@ -32,6 +32,40 @@ export interface ConvertOutcome {
const CLAUDE_HOOKS_PATH_PATTERN = /\.claude\/hooks\//g;
const CODEX_HOOKS_PATH_PATTERN = /\.codex\/hooks\//g;
+/** 判断是否为普通 JSON 对象。 */
+function isPlainObject(v: unknown): v is Record<string, unknown> {
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
+}
+
+/**
+ * 取出 Codex hooks.json 里的事件表。
+ * Codex 规范顶层是 `{ "hooks": { <Event>: [...] } }`;同时兼容早期平铺写法 `{ <Event>: [...] }`
+ * (平铺时忽略非事件的 "hooks" 键本身)。
+ */
+function extractCodexEvents(root: Record<string, unknown>): Record<string, unknown> {
+ if (isPlainObject(root.hooks)) return root.hooks;
+ const flat: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(root)) {
+ if (k === 'hooks') continue;
+ flat[k] = v;
+ }
+ return flat;
+}
+
+/** 修复存量错误嵌套的 settings.hooks.hooks:把内层事件拍平到 settings.hooks 上(已有同名事件不覆盖)。 */
+function unwrapNestedClaudeHooks(hooks: Record<string, unknown>): Record<string, unknown> {
+ const nested = hooks.hooks;
+ if (!isPlainObject(nested)) return hooks;
+ const out: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(hooks)) {
+ if (k !== 'hooks') out[k] = v;
+ }
+ for (const [k, v] of Object.entries(nested)) {
+ if (!(k in out)) out[k] = v;
+ }
+ return out;
+}
+
async function exists(p: string): Promise<boolean> {
try {
await fs.access(p);
@@ -137,20 +171,25 @@ async function convertToCodex(item: MigrationItem): Promise<ConvertOutcome> {
const hadExisting = await exists(codexHooksJson);
if (hadExisting) {
const parsed = await readJsonIfExists(codexHooksJson);
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
- existing = parsed as Record<string, unknown>;
- }
+ if (isPlainObject(parsed)) existing = parsed;
+ }
+ // Codex 规范:事件放在顶层 "hooks" 对象内;旧的平铺文件就地升级为包装结构
+ const codexEvents = extractCodexEvents(existing);
+ const codexRoot: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(existing)) {
+ if (k === 'hooks' || k in codexEvents) continue;
+ codexRoot[k] = v;
}
let added = 0;
let skipped = 0;
if (claudeHooks) {
- for (const [eventName, eventConfig] of Object.entries(claudeHooks)) {
- if (eventName in existing) {
+ for (const [eventName, eventConfig] of Object.entries(unwrapNestedClaudeHooks(claudeHooks))) {
+ if (eventName in codexEvents) {
skipped += 1;
continue;
}
- existing[eventName] = rewriteHookEntry(eventConfig, 'to-codex');
+ codexEvents[eventName] = rewriteHookEntry(eventConfig, 'to-codex');
added += 1;
}
}
@@ -160,7 +199,8 @@ async function convertToCodex(item: MigrationItem): Promise<ConvertOutcome> {
}
await fs.mkdir(path.dirname(codexHooksJson), { recursive: true });
- await fs.writeFile(codexHooksJson, JSON.stringify(existing, null, 2), 'utf8');
+ codexRoot.hooks = codexEvents;
+ await fs.writeFile(codexHooksJson, JSON.stringify(codexRoot, null, 2), 'utf8');
const parts: string[] = [];
if (scriptResult.copied > 0) parts.push(`脚本 ${scriptResult.copied}`);
@@ -188,9 +228,7 @@ async function convertToClaude(item: MigrationItem): Promise<ConvertOutcome> {
let codexHooks: Record<string, unknown> = {};
try {
const parsed = await readJsonIfExists(codexHooksJson);
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
- codexHooks = parsed as Record<string, unknown>;
- }
+ if (isPlainObject(parsed)) codexHooks = extractCodexEvents(parsed);
} catch (err) {
return { status: 'failed', detail: `hooks.json 解析失败: ${err instanceof Error ? err.message : String(err)}` };
}
@@ -204,7 +242,10 @@ async function convertToClaude(item: MigrationItem): Promise<ConvertOutcome> {
settings = parsed as Record<string, unknown>;
}
}
- const existingHooks = (settings.hooks ?? {}) as Record<string, unknown>;
+ // 存量错误嵌套 settings.hooks.hooks 一并拍平修复
+ const rawHooks = isPlainObject(settings.hooks) ? settings.hooks : {};
+ const existingHooks = unwrapNestedClaudeHooks(rawHooks);
+ const repaired = existingHooks !== rawHooks;
let added = 0;
let skipped = 0;
@@ -217,7 +258,7 @@ async function convertToClaude(item: MigrationItem): Promise<ConvertOutcome> {
added += 1;
}
- if (added === 0 && scriptResult.copied === 0) {
+ if (added === 0 && scriptResult.copied === 0 && !repaired) {
return { status: 'skipped', detail: '所有 hook 已存在' };
}
@@ -229,6 +270,7 @@ async function convertToClaude(item: MigrationItem): Promise<ConvertOutcome> {
if (scriptResult.copied > 0) parts.push(`脚本 ${scriptResult.copied}`);
if (added > 0) parts.push(`索引 ${added}`);
if (skipped > 0) parts.push(`跳过 ${skipped}`);
+ if (repaired) parts.push('修复嵌套 hooks.hooks');
return { status: 'success', detail: parts.join(', ') };
}
diff --git a/apps/desktop/src/main/cross-agent-convert/detector.ts b/apps/desktop/src/main/cross-agent-convert/detector.ts
index 62a5149645..00fc6576de 100644
--- a/apps/desktop/src/main/cross-agent-convert/detector.ts
+++ b/apps/desktop/src/main/cross-agent-convert/detector.ts
@@ -215,7 +215,8 @@ async function detectHooks(wd: string, direction: MigrationDirection, items: Mig
// 目标缺失判断:claude settings.json 不存在 / 不含 hooks 段,或 .claude/hooks/ 不存在
const claudeSettingsHasHooks = await fileHasJsonKey(claudeSettings, 'hooks');
const claudeHooksDirExists = await isDir(claudeHooksDir);
- if (claudeSettingsHasHooks && claudeHooksDirExists) return;
+ // 按源端资产对齐:源端只有 hooks.json、没有 hooks/ 目录时,目标有 hooks 配置即视为完备
+ if ((!hasSourceJson || claudeSettingsHasHooks) && (!hasSourceDir || claudeHooksDirExists)) return;
items.push({
id: 'hooks:0',
kind: 'hooks',
@@ -230,7 +231,7 @@ async function detectHooks(wd: string, direction: MigrationDirection, items: Mig
if (!hasSourceDir && !hasSourceJson) return;
const codexHooksJsonExists = await isNonEmptyTextFile(codexHooksJson);
const codexHooksDirExists = await isDir(codexHooksDir);
- if (codexHooksJsonExists && codexHooksDirExists) return;
+ if ((!hasSourceJson || codexHooksJsonExists) && (!hasSourceDir || codexHooksDirExists)) return;
items.push({
id: 'hooks:0',
kind: 'hooks',