Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): preserve relative references in imported global rules
321sssrt-bitdb5cc585c56c
diff --git a/apps/desktop/src/main/__tests__/codexGlobalRules.test.ts b/apps/desktop/src/main/__tests__/codexGlobalRules.test.tsindex 0f8bb35105..08053b5dc3 100644--- a/apps/desktop/src/main/__tests__/codexGlobalRules.test.ts+++ b/apps/desktop/src/main/__tests__/codexGlobalRules.test.ts@@ -1,7 +1,11 @@import os from 'node:os';import path from 'node:path';import { promises as fs } from 'node:fs';+import { fileURLToPath, pathToFileURL } from 'node:url';import { afterEach, describe, expect, it } from 'vitest';+import { unified } from 'unified';+import remarkParse from 'remark-parse';+import { visit } from 'unist-util-visit';import {CODEX_GLOBAL_RULES_MARKER_FILE_NAME,@@ -17,13 +21,21 @@ async function makeTmpDir(): Promise<string> {return dir;}-async function setupPaths() {+async function setupPaths(managedHome = 'xdt-codex-home') {const root = await makeTmpDir();- const homeDir = path.join(root, 'home with spaces');- const codexHome = path.join(root, 'xdt-codex-home');+ const homeDir = path.join(root, 'home with spaces 中文#% ©');+ const codexHome = path.join(root, managedHome);return { homeDir, ...codexGlobalRulesPaths(codexHome, homeDir) };}+function ruleLinks(document: string): string[] {+ const urls: string[] = [];+ visit(unified().use(remarkParse).parse(document), (node) => {+ if (node.type === 'link' || node.type === 'definition') urls.push(node.url);+ });+ return urls;+}+async function writeFile(filePath: string, content: string): Promise<void> {await fs.mkdir(path.dirname(filePath), { recursive: true });await fs.writeFile(filePath, content, 'utf8');@@ -175,6 +187,147 @@ describe('prepareCodexGlobalRulesCopy', () => {expect(await exists(paths.markerFile)).toBe(true);});+ it.each(['xdt-codex-home', path.join('codex-accounts', 'secondary')])(+ 'keeps referenced documents readable after importing rules into %s', async (managedHome) => {+ const paths = await setupPaths(managedHome);+ const nativeHome = path.dirname(paths.sourceRulesFile);+ const executionRules = 'execution rules\n[Next](nested/next.md)\n';+ const document = '\uFEFF' + [+ '# Global rules',+ '[**Execution**](guides/execution.md "Required")',+ '[](./guides/execution.md)',+ '[Spaces](<guides/协作 notes.md#checks>)',+ '[Parent](../shared/notes%23one.md?view=1&mode=full#checks)',+ '[Escaped](guides/check\\(one\\).md)',+ '[Percent](guides/100%.md)',+ '[Encoded percent](guides/literal%2523.md)',+ '[Entity](guides/a&b.md)',+ '[Literal entity](guides/literal&copy;.md)',+ '[Label with `](` inside](guides/execution.md)',+ '[Reference][guide]',+ '[Literal reference][literal]',+ '[guide][] and [guide]',+ '',+ '[guide]: guides/execution.md "Reference title"',+ '[literal]: guides/literal&copy;.md',+ '',+ '> [Quoted][quoted]',+ '>',+ '> [quoted]:',+ "> <guides/execution.md> 'Quoted title'",+ '',+ ].join('\r\n');+ await writeFile(paths.sourceRulesFile, document);+ await fs.chmod(paths.sourceRulesFile, 0o600);+ await writeFile(path.join(nativeHome, 'guides/execution.md'), executionRules);+ await writeFile(path.join(nativeHome, 'guides/nested/next.md'), '[Leaf](../leaf.md)');+ await writeFile(path.join(nativeHome, 'guides/leaf.md'), 'deep rules');+ await writeFile(path.join(nativeHome, 'guides/协作 notes.md'), 'collaboration rules');+ await writeFile(path.join(nativeHome, '../shared/notes#one.md'), 'shared rules');+ await writeFile(path.join(nativeHome, 'guides/check(one).md'), 'check rules');+ await writeFile(path.join(nativeHome, 'guides/100%.md'), 'literal percent');+ await writeFile(path.join(nativeHome, 'guides/literal%23.md'), 'encoded percent');+ await writeFile(path.join(nativeHome, 'guides/a&b.md'), 'entity rules');+ await writeFile(path.join(nativeHome, 'guides/literal©.md'), 'literal entity rules');++ const result = await prepareCodexGlobalRulesCopy(paths.codexHome, { homeDir: paths.homeDir });+ const imported = await fs.readFile(paths.managedRulesFile, 'utf8');+ const urls = ruleLinks(imported);++ expect(result.status).toBe('copied');+ expect(urls).toHaveLength(13);+ expect((await fs.stat(paths.managedRulesFile)).mode & 0o777)+ .toBe((await fs.stat(paths.sourceRulesFile)).mode & 0o777);+ const contents = await Promise.all(urls.map((url) =>+ fs.readFile(fileURLToPath(new URL(url, pathToFileURL(paths.managedRulesFile))), 'utf8'),+ ));+ expect(contents).toEqual([+ executionRules, executionRules, 'collaboration rules', 'shared rules', 'check rules',+ 'literal percent', 'encoded percent', 'entity rules', 'literal entity rules',+ executionRules, executionRules, 'literal entity rules', executionRules,+ ]);+ const nextUrl = new URL(ruleLinks(contents[0])[0], urls[0]);+ const next = await fs.readFile(fileURLToPath(nextUrl), 'utf8');+ const leafUrl = new URL(ruleLinks(next)[0], nextUrl);+ await expect(fs.readFile(fileURLToPath(leafUrl), 'utf8')).resolves.toBe('deep rules');+ expect(urls[2]).toMatch(/#checks$/);+ expect(urls[3]).toMatch(/\?view=1&mode=full#checks$/);+ expect(imported.startsWith('\uFEFF# Global rules\r\n')).toBe(true);+ expect(imported).toContain('[**Execution**](');+ expect(imported).toContain(' "Required")\r\n');+ expect(imported).toContain('[Reference][guide]\r\n');+ expect(imported).toContain(' "Reference title"\r\n');+ expect(imported).toContain(" 'Quoted title'\r\n");+ await expect(fs.readFile(paths.sourceRulesFile, 'utf8')).resolves.toBe(document);+ expect(await exists(path.join(paths.codexHome, 'guides'))).toBe(false);+ });++ it('leaves absolute links, anchors and code examples unchanged', async () => {+ const paths = await setupPaths();+ const document = [+ '[Web](https://example.com/rules)',+ '[File](file:///tmp/rules.md)',+ '[POSIX](/opt/rules.md)',+ '[Windows](C:/rules.md)',+ '[UNC](//server/share/rules.md)',+ '[Home](~/guides/rules.md)',+ '[Anchor](#local)',+ '[Query](?view=1)',+ '[Empty]()',+ 'guides/plain-path.md',+ '[Malformed](guides/unescaped space.md)',+ '`[Inline](guides/example.md)`',+ '```md',+ '[Fenced](guides/example.md)',+ '[fenced]: guides/example.md',+ '```',+ '',+ ' [Indented](guides/example.md)',+ '',+ '<!-- [Comment](guides/example.md) -->',+ '',+ ].join('\n');+ await writeFile(paths.sourceRulesFile, document);++ await prepareCodexGlobalRulesCopy(paths.codexHome, { homeDir: paths.homeDir });++ await expect(fs.readFile(paths.managedRulesFile, 'utf8')).resolves.toBe(document);+ });++ it('upgrades old managed copies and keeps generated links stable across refreshes', async () => {+ const paths = await setupPaths();+ const document = '[Execution](guides/execution.md)\n';+ await writeFile(paths.sourceRulesFile, document);+ await writeFile(paths.managedRulesFile, document);+ await writeMarker(paths.markerFile);++ const upgraded = await prepareCodexGlobalRulesCopy(paths.codexHome, { homeDir: paths.homeDir });+ const imported = await fs.readFile(paths.managedRulesFile, 'utf8');+ const refreshed = await prepareCodexGlobalRulesCopy(paths.codexHome, { homeDir: paths.homeDir });++ expect(upgraded.status).toBe('updated');+ expect(imported).not.toBe(document);+ expect(refreshed.status).toBe('kept');+ expect(refreshed.changed).toBe(false);+ await expect(fs.readFile(paths.managedRulesFile, 'utf8')).resolves.toBe(imported);++ await writeFile(paths.sourceRulesFile, '[Other](guides/other.md)\n');+ await fs.chmod(paths.sourceRulesFile, 0o640);+ const referencedFile = path.join(path.dirname(paths.sourceRulesFile), 'guides/other.md');+ await writeFile(referencedFile, 'new rules');+ const changed = await prepareCodexGlobalRulesCopy(paths.codexHome, { homeDir: paths.homeDir });+ expect(changed.status).toBe('updated');+ expect((await fs.stat(paths.managedRulesFile)).mode & 0o777)+ .toBe((await fs.stat(paths.sourceRulesFile)).mode & 0o777);+ const target = fileURLToPath(ruleLinks(await fs.readFile(paths.managedRulesFile, 'utf8'))[0]);+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('new rules');++ await writeFile(referencedFile, 'updated reference');+ const unchanged = await prepareCodexGlobalRulesCopy(paths.codexHome, { homeDir: paths.homeDir });+ expect(unchanged.status).toBe('kept');+ await expect(fs.readFile(target, 'utf8')).resolves.toBe('updated reference');+ });+it('does not overwrite or delete an unmarked destination across source states', async () => {const paths = await setupPaths();await writeFile(paths.managedRulesFile, 'local user rules');diff --git a/apps/desktop/src/main/maker-host/codex-global-rules.ts b/apps/desktop/src/main/maker-host/codex-global-rules.tsindex 1f497f9f3e..60ebcc6c2a 100644--- a/apps/desktop/src/main/maker-host/codex-global-rules.ts+++ b/apps/desktop/src/main/maker-host/codex-global-rules.ts@@ -1,6 +1,9 @@import os from 'node:os';import path from 'node:path';import { promises as fsp } from 'node:fs';+import { pathToFileURL } from 'node:url';+import { unified } from 'unified';+import remarkParse from 'remark-parse';export const CODEX_GLOBAL_RULES_FILE_NAME = 'AGENTS.md';export const CODEX_GLOBAL_RULES_MARKER_FILE_NAME = 'AGENTS.md.xdt-managed';@@ -45,6 +48,67 @@ export function codexGlobalRulesPaths(codexHome: string, homeDir = os.homedir())};}+/** Keep document references anchored to the source without copying its directory. */+function managedRulesContent(source: Buffer, sourceRulesFile: string): Buffer {+ const original = source.toString('utf8');+ // remark removes a leading BOM before assigning offsets; keep it outside edits.+ const bom = original.startsWith('\uFEFF') ? '\uFEFF' : '';+ const text = original.slice(bom.length);+ const base = pathToFileURL(sourceRulesFile);+ const edits: { start: number; end: number; value: string }[] = [];+ const capture = (+ node: { type: string; url?: string } | undefined,+ token: { start: { offset: number }; end: { offset: number } },+ ) => {+ if (node?.type !== 'link' && node?.type !== 'definition') return;+ const url = node.url;+ if (!url || /^(?:[a-z][a-z0-9+.-]*:|[/\\#?]|~(?:[/\\]|$))/i.test(url)) return;++ // Markdown destinations use URL semantics: preserve existing escapes and+ // suffixes; encode literal percent signs and parentheses for bare links.+ // Escape ampersands for Markdown without changing URL query separators.+ const value = new URL(url.replace(/%(?![\da-f]{2})/gi, '%25'), base).href+ .replace(/&/g, '&').replace(/\(/g, '%28').replace(/\)/g, '%29');+ const enclosed = text[token.start.offset] === '<';+ edits.push({+ start: token.start.offset + (enclosed ? 1 : 0),+ end: token.end.offset - (enclosed ? 1 : 0),+ value,+ });+ };++ // Destination tokens retain exact source offsets. Hook their enclosing exit+ // after remark has decoded the URL, leaving labels, titles and examples intact.+ unified().use(remarkParse).data('fromMarkdownExtensions', [{+ exit: {+ resourceDestination(token) { capture(this.stack.at(-1), token); },+ definitionDestination(token) { capture(this.stack.at(-1), token); },+ },+ }]).parse(text);++ if (!edits.length) return source;+ let result = text;+ for (const edit of edits.sort((a, b) => b.start - a.start)) {+ result = result.slice(0, edit.start) + edit.value + result.slice(edit.end);+ }+ return Buffer.from(bom + result, 'utf8');+}++async function writeManagedRules(+ paths: ReturnType<typeof codexGlobalRulesPaths>,+ content: Buffer,+): Promise<void> {+ // copyFile used to preserve source permissions, including on existing copies.+ const mode = (await fsp.stat(paths.sourceRulesFile)).mode & 0o777;+ const file = await fsp.open(paths.managedRulesFile, 'w', mode);+ try {+ await file.writeFile(content);+ await file.chmod(mode);+ } finally {+ await file.close();+ }+}+async function statFile(value: string, followSymlink: boolean): Promise<PathState> {try {const stat = followSymlink ? await fsp.stat(value) : await fsp.lstat(value);@@ -111,7 +175,8 @@ async function copyWithMarker(paths: ReturnType<typeof codexGlobalRulesPaths>):}try {- await fsp.copyFile(paths.sourceRulesFile, paths.managedRulesFile);+ const source = await fsp.readFile(paths.sourceRulesFile);+ await writeManagedRules(paths, managedRulesContent(source, paths.sourceRulesFile));return makeResult(paths, 'copied', true);} catch (err) {const warning = `cannot copy Codex rules from ${paths.sourceRulesFile} to ${paths.managedRulesFile}: ${@@ -123,9 +188,10 @@ async function copyWithMarker(paths: ReturnType<typeof codexGlobalRulesPaths>):async function updateManagedCopy(paths: ReturnType<typeof codexGlobalRulesPaths>,+ content: Buffer,): Promise<CodexGlobalRulesPrepareResult> {try {- await fsp.copyFile(paths.sourceRulesFile, paths.managedRulesFile);+ await writeManagedRules(paths, content);} catch (err) {const warning = `cannot update Codex rules copy ${paths.managedRulesFile}: ${(err as Error).message}`;return makeResult(paths, 'error', false, [warning], warning);@@ -199,10 +265,11 @@ async function prepareCodexGlobalRulesCopyInner(fsp.readFile(paths.sourceRulesFile),fsp.readFile(paths.managedRulesFile),]);- if (sourceBuffer.equals(destinationBuffer)) {+ const content = managedRulesContent(sourceBuffer, paths.sourceRulesFile);+ if (content.equals(destinationBuffer)) {return makeResult(paths, 'kept', false);}- return updateManagedCopy(paths);+ return updateManagedCopy(paths, content);} catch (err) {const warning = `cannot compare Codex rules files: ${(err as Error).message}`;return makeResult(paths, 'error', false, [warning], warning);