GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — claude-code-source-code/src/utils/claudemd.ts at main · wangwang4git/claude-code-source-code Expand file tree/ Copy pathclaudemd.tsMore file actions 1479 lines (1344 loc) · 45.3 KB / Copy pathclaudemd.tsFile metadata and controls1479 lines (1344 loc) · 45.3 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 /** * Files are loaded in the following order: * * 1. Managed memory (eg. /etc/claude-code/CLAUDE.md) - Global instructions for all users * 2. User memory (~/.claude/CLAUDE.md) - Private global instructions for all projects * 3. Project memory (CLAUDE.md, .claude/CLAUDE.md, and .claude/rules/*.md in project roots) - Instructions checked into the codebase * 4. Local memory (CLAUDE.local.md in project roots) - Private project-specific instructions * * Files are loaded in reverse order of priority, i.e. the latest files are highest priority * with the model paying more attention to them. * * File discovery: * - User memory is loaded from the user's home directory * - Project and Local files are discovered by traversing from the current directory up to root * - Files closer to the current directory have higher priority (loaded later) * - CLAUDE.md, .claude/CLAUDE.md, and all .md files in .claude/rules/ are checked in each directory for Project memory * * Memory @include directive: * - Memory files can include other files using @ notation * - Syntax: @path, @./relative/path, @~/home/path, or @/absolute/path * - @path (without prefix) is treated as a relative path (same as @./path) * - Works in leaf text nodes only (not inside code blocks or code strings) * - Included files are added as separate entries before the including file * - Circular references are prevented by tracking processed files * - Non-existent files are silently ignored */ import { feature } from 'bun:bundle' import ignore from 'ignore' import memoize from 'lodash-es/memoize.js' import { Lexer } from 'marked' import { basename, dirname, extname, isAbsolute, join, parse, relative, sep, } from 'path' import picomatch from 'picomatch' import { logEvent } from 'src/services/analytics/index.js' import { getAdditionalDirectoriesForClaudeMd, getOriginalCwd, } from '../bootstrap/state.js' import { truncateEntrypointContent } from '../memdir/memdir.js' import { getAutoMemEntrypoint, isAutoMemoryEnabled } from '../memdir/paths.js' import { getFeatureValue_CACHED_MAY_BE_STALE } from '../services/analytics/growthbook.js' import { getCurrentProjectConfig, getManagedClaudeRulesDir, getMemoryPath, getUserClaudeRulesDir, } from './config.js' import { logForDebugging } from './debug.js' import { logForDiagnosticsNoPII } from './diagLogs.js' import { getClaudeConfigHomeDir, isEnvTruthy } from './envUtils.js' import { getErrnoCode } from './errors.js' import { normalizePathForComparison } from './file.js' import { cacheKeys, type FileStateCache } from './fileStateCache.js' import { parseFrontmatter, splitPathInFrontmatter, } from './frontmatterParser.js' import { getFsImplementation, safeResolvePath } from './fsOperations.js' import { findCanonicalGitRoot, findGitRoot } from './git.js' import { executeInstructionsLoadedHooks, hasInstructionsLoadedHook, type InstructionsLoadReason, type InstructionsMemoryType, } from './hooks.js' import type { MemoryType } from './memory/types.js' import { expandPath } from './path.js' import { pathInWorkingPath } from './permissions/filesystem.js' import { isSettingSourceEnabled } from './settings/constants.js' import { getInitialSettings } from './settings/settings.js' /* eslint-disable @typescript-eslint/no-require-imports */ const teamMemPaths = feature('TEAMMEM') ? (require('../memdir/teamMemPaths.js') as typeof import('../memdir/teamMemPaths.js')) : null /* eslint-enable @typescript-eslint/no-require-imports */ let hasLoggedInitialLoad = false const MEMORY_INSTRUCTION_PROMPT = 'Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.' // Recommended max character count for a memory file export const MAX_MEMORY_CHARACTER_COUNT = 40000 // File extensions that are allowed for @include directives // This prevents binary files (images, PDFs, etc.) from being loaded into memory const TEXT_FILE_EXTENSIONS = new Set([ // Markdown and text '.md', '.txt', '.text', // Data formats '.json', '.yaml', '.yml', '.toml', '.xml', '.csv', // Web '.html', '.htm', '.css', '.scss', '.sass', '.less', // JavaScript/TypeScript '.js', '.ts', '.tsx', '.jsx', '.mjs', '.cjs', '.mts', '.cts', // Python '.py', '.pyi', '.pyw', // Ruby '.rb', '.erb', '.rake', // Go '.go', // Rust '.rs', // Java/Kotlin/Scala '.java', '.kt', '.kts', '.scala', // C/C++ '.c', '.cpp', '.cc', '.cxx', '.h', '.hpp', '.hxx', // C# '.cs', // Swift '.swift', // Shell '.sh', '.bash', '.zsh', '.fish', '.ps1', '.bat', '.cmd', // Config '.env', '.ini', '.cfg', '.conf', '.config', '.properties', // Database '.sql', '.graphql', '.gql', // Protocol '.proto', // Frontend frameworks '.vue', '.svelte', '.astro', // Templating '.ejs', '.hbs', '.pug', '.jade', // Other languages '.php', '.pl', '.pm', '.lua', '.r', '.R', '.dart', '.ex', '.exs', '.erl', '.hrl', '.clj', '.cljs', '.cljc', '.edn', '.hs', '.lhs', '.elm', '.ml', '.mli', '.f', '.f90', '.f95', '.for', // Build files '.cmake', '.make', '.makefile', '.gradle', '.sbt', // Documentation '.rst', '.adoc', '.asciidoc', '.org', '.tex', '.latex', // Lock files (often text-based) '.lock', // Misc '.log', '.diff', '.patch', ]) export type MemoryFileInfo = { path: string type: MemoryType content: string parent?: string // Path of the file that included this one globs?: string[] // Glob patterns for file paths this rule applies to // True when auto-injection transformed `content` (stripped HTML comments, // stripped frontmatter, truncated MEMORY.md) such that it no longer matches // the bytes on disk. When set, `rawContent` holds the unmodified disk bytes // so callers can cache a `isPartialView` readFileState entry — presence in // cache provides dedup + change detection, but Edit/Write still require an // explicit Read before proceeding. contentDiffersFromDisk?: boolean rawContent?: string } function pathInOriginalCwd(path: string): boolean { return pathInWorkingPath(path, getOriginalCwd()) } /** * Parses raw content to extract both content and glob patterns from frontmatter * @param rawContent Raw file content with frontmatter * @returns Object with content and globs (undefined if no paths or match-all pattern) */ function parseFrontmatterPaths(rawContent: string): { content: string paths?: string[] } { const { frontmatter, content } = parseFrontmatter(rawContent) if (!frontmatter.paths) { return { content } } const patterns = splitPathInFrontmatter(frontmatter.paths) .map(pattern => { // Remove /** suffix - ignore library treats 'path' as matching both // the path itself and everything inside it return pattern.endsWith('/**') ? pattern.slice(0, -3) : pattern }) .filter((p: string) => p.length > 0) // If all patterns are ** (match-all), treat as no globs (undefined) // This means the file applies to all paths if (patterns.length === 0 || patterns.every((p: string) => p === '**')) { return { content } } return { content, paths: patterns } } /** * Strip block-level HTML comments (<!-- ... -->) from markdown content. * * Uses the marked lexer to identify comments at the block level only, so * comments inside inline code spans and fenced code blocks are preserved. * Inline HTML comments inside a paragraph are also left intact; the intended * use case is authorial notes that occupy their own lines. * * Unclosed comments (`<!--` with no matching `-->`) are left in place so a * typo doesn't silently swallow the rest of the file. */ export function stripHtmlComments(content: string): { content: string stripped: boolean } { if (!content.includes('<!--')) { return { content, stripped: false } } // gfm:false is fine here — html-block detection is a CommonMark rule. return stripHtmlCommentsFromTokens(new Lexer({ gfm: false }).lex(content)) } function stripHtmlCommentsFromTokens(tokens: ReturnType<Lexer['lex']>): { content: string stripped: boolean } { let result = '' let stripped = false // A well-formed HTML comment span. Non-greedy so multiple comments on the // same line are matched independently; [\s\S] to span newlines. const commentSpan = /<!--[\s\S]*?-->/g for (const token of tokens) { if (token.type === 'html') { const trimmed = token.raw.trimStart() if (trimmed.startsWith('<!--') && trimmed.includes('-->')) { // Per CommonMark, a type-2 HTML block ends at the *line* containing // `-->`, so text after `-->` on that line is part of this token. // Strip only the comment spans and keep any residual content. const residue = token.raw.replace(commentSpan, '') stripped = true if (residue.trim().length > 0) { // Residual content exists (e.g. `<!-- note --> Use bun`): keep it. result += residue } continue } } result += token.raw } return { content: result, stripped } } /** * Parses raw memory file content into a MemoryFileInfo. Pure function — no I/O. * * When includeBasePath is given, @include paths are resolved in the same lex * pass and returned alongside the parsed file (so processMemoryFile doesn't * need to lex the same content a second time). */ function parseMemoryFileContent( rawContent: string, filePath: string, type: MemoryType, includeBasePath?: string, ): { info: MemoryFileInfo | null; includePaths: string[] } { // Skip non-text files to prevent loading binary data (images, PDFs, etc.) into memory const ext = extname(filePath).toLowerCase() if (ext && !TEXT_FILE_EXTENSIONS.has(ext)) { logForDebugging(`Skipping non-text file in @include: ${filePath}`) return { info: null, includePaths: [] } } const { content: withoutFrontmatter, paths } = parseFrontmatterPaths(rawContent) // Lex once so strip and @include-extract share the same tokens. gfm:false // is required by extract (so ~/path doesn't tokenize as strikethrough) and // doesn't affect strip (html blocks are a CommonMark rule). const hasComment = withoutFrontmatter.includes('<!--') const tokens = hasComment || includeBasePath !== undefined ? new Lexer({ gfm: false }).lex(withoutFrontmatter) : undefined // Only rebuild via tokens when a comment actually needs stripping — // marked normalises \r\n during lex, so round-tripping a CRLF file // through token.raw would spuriously flip contentDiffersFromDisk. const strippedContent = hasComment && tokens ? stripHtmlCommentsFromTokens(tokens).content : withoutFrontmatter const includePaths = tokens && includeBasePath !== undefined ? extractIncludePathsFromTokens(tokens, includeBasePath) : [] // Truncate MEMORY.md entrypoints to the line AND byte caps let finalContent = strippedContent if (type === 'AutoMem' || type === 'TeamMem') { finalContent = truncateEntrypointContent(strippedContent).content } // Covers frontmatter strip, HTML comment strip, and MEMORY.md truncation const contentDiffersFromDisk = finalContent !== rawContent return { info: { path: filePath, type, content: finalContent, globs: paths, contentDiffersFromDisk, rawContent: contentDiffersFromDisk ? rawContent : undefined, }, includePaths, } } function handleMemoryFileReadError(error: unknown, filePath: string): void { const code = getErrnoCode(error) // ENOENT = file doesn't exist, EISDIR = is a directory — both expected if (code === 'ENOENT' || code === 'EISDIR') { return } // Log permission errors (EACCES) as they're actionable if (code === 'EACCES') { // Don't log the full file path to avoid PII/security issues logEvent('tengu_claude_md_permission_error', { is_access_error: 1, has_home_dir: filePath.includes(getClaudeConfigHomeDir()) ? 1 : 0, }) } } /** * Used by processMemoryFile → getMemoryFiles so the event loop stays * responsive during the directory walk (many readFile attempts, most * ENOENT). When includeBasePath is given, @include paths are resolved in * the same lex pass and returned alongside the parsed file. */ async function safelyReadMemoryFileAsync( filePath: string, type: MemoryType, includeBasePath?: string, ): Promise<{ info: MemoryFileInfo | null; includePaths: string[] }> { try { const fs = getFsImplementation() const rawContent = await fs.readFile(filePath, { encoding: 'utf-8' }) return parseMemoryFileContent(rawContent, filePath, type, includeBasePath) } catch (error) { handleMemoryFileReadError(error, filePath) return { info: null, includePaths: [] } } } type MarkdownToken = { type: string text?: string href?: string tokens?: MarkdownToken[] raw?: string items?: MarkdownToken[] } // Extract @path include references from pre-lexed tokens and resolve to // absolute paths. Skips html tokens so @paths inside block comments are // ignored — the caller may pass pre-strip tokens. function extractIncludePathsFromTokens( tokens: ReturnType<Lexer['lex']>, basePath: string, ): string[] { const absolutePaths = new Set<string>() // Extract @paths from a text string and add resolved paths to absolutePaths. function extractPathsFromText(textContent: string) { const includeRegex = /(?:^|\s)@((?:[^\s\\]|\\ )+)/g let match while ((match = includeRegex.exec(textContent)) !== null) { let path = match[1] if (!path) continue // Strip fragment identifiers (#heading, #section-name, etc.) const hashIndex = path.indexOf('#') if (hashIndex !== -1) { path = path.substring(0, hashIndex) } if (!path) continue // Unescape the spaces in the path path = path.replace(/\\ /g, ' ') // Accept @path, @./path, @~/path, or @/path if (path) { const isValidPath = path.startsWith('./') || path.startsWith('~/') || (path.startsWith('/') && path !== '/') || (!path.startsWith('@') && !path.match(/^[#%^&*()]+/) && path.match(/^[a-zA-Z0-9._-]/)) if (isValidPath) { const resolvedPath = expandPath(path, dirname(basePath)) absolutePaths.add(resolvedPath) } } } } // Recursively process elements to find text nodes function processElements(elements: MarkdownToken[]) { for (const element of elements) { if (element.type === 'code' || element.type === 'codespan') { continue } // For html tokens that contain comments, strip the comment spans and // check the residual for @paths (e.g. `<!-- note --> @./file.md`). // Other html tokens (non-comment tags) are skipped entirely. if (element.type === 'html') { const raw = element.raw || '' const trimmed = raw.trimStart() if (trimmed.startsWith('<!--') && trimmed.includes('-->')) { const commentSpan = /<!--[\s\S]*?-->/g const residue = raw.replace(commentSpan, '') if (residue.trim().length > 0) { extractPathsFromText(residue) } } continue } // Process text nodes if (element.type === 'text') { extractPathsFromText(element.text || '') } // Recurse into children tokens if (element.tokens) { processElements(element.tokens) } // Special handling for list structures if (element.items) { processElements(element.items) } } } processElements(tokens as MarkdownToken[]) return [...absolutePaths] } const MAX_INCLUDE_DEPTH = 5 /** * Checks whether a CLAUDE.md file path is excluded by the claudeMdExcludes setting. * Only applies to User, Project, and Local memory types. * Managed, AutoMem, and TeamMem types are never excluded. * * Matches both the original path and the realpath-resolved path to handle symlinks * (e.g., /tmp -> /private/tmp on macOS). */ function isClaudeMdExcluded(filePath: string, type: MemoryType): boolean { if (type !== 'User' && type !== 'Project' && type !== 'Local') { return false } const patterns = getInitialSettings().claudeMdExcludes if (!patterns || patterns.length === 0) { return false } const matchOpts = { dot: true } const normalizedPath = filePath.replaceAll('\\', '/') // Build an expanded pattern list that includes realpath-resolved versions of // absolute patterns. This handles symlinks like /tmp -> /private/tmp on macOS: // the user writes "/tmp/project/CLAUDE.md" in their exclude, but the system // resolves the CWD to "/private/tmp/project/...", so the file path uses the // real path. By resolving the patterns too, both sides match. const expandedPatterns = resolveExcludePatterns(patterns).filter( p => p.length > 0, ) if (expandedPatterns.length === 0) { return false } return picomatch.isMatch(normalizedPath, expandedPatterns, matchOpts) } /** * Expands exclude patterns by resolving symlinks in absolute path prefixes. * For each absolute pattern (starting with /), tries to resolve the longest * existing directory prefix via realpathSync and adds the resolved version. * Glob patterns (containing *) have their static prefix resolved. */ function resolveExcludePatterns(patterns: string[]): string[] { const fs = getFsImplementation() const expanded: string[] = patterns.map(p => p.replaceAll('\\', '/')) for (const normalized of expanded) { // Only resolve absolute patterns — glob-only patterns like "**/*.md" don't have // a filesystem prefix to resolve if (!normalized.startsWith('/')) { continue } // Find the static prefix before any glob characters const globStart = normalized.search(/[*?{[]/) const staticPrefix = globStart === -1 ? normalized : normalized.slice(0, globStart) const dirToResolve = dirname(staticPrefix) try { // sync IO: called from sync context (isClaudeMdExcluded -> processMemoryFile -> getMemoryFiles) const resolvedDir = fs.realpathSync(dirToResolve).replaceAll('\\', '/') if (resolvedDir !== dirToResolve) { const resolvedPattern = resolvedDir + normalized.slice(dirToResolve.length) expanded.push(resolvedPattern) } } catch { // Directory doesn't exist; skip resolution for this pattern } } return expanded } /** * Recursively processes a memory file and all its @include references * Returns an array of MemoryFileInfo objects with includes first, then main file */ export async function processMemoryFile( filePath: string, type: MemoryType, processedPaths: Set<string>, includeExternal: boolean, depth: number = 0, parent?: string, ): Promise<MemoryFileInfo[]> { // Skip if already processed or max depth exceeded. // Normalize paths for comparison to handle Windows drive letter casing // differences (e.g., C:\Users vs c:\Users). const normalizedPath = normalizePathForComparison(filePath) if (processedPaths.has(normalizedPath) || depth >= MAX_INCLUDE_DEPTH) { return [] } // Skip if path is excluded by claudeMdExcludes setting if (isClaudeMdExcluded(filePath, type)) { return [] } // Resolve symlink path early for @import resolution const { resolvedPath, isSymlink } = safeResolvePath( getFsImplementation(), filePath, ) processedPaths.add(normalizedPath) if (isSymlink) { processedPaths.add(normalizePathForComparison(resolvedPath)) } const { info: memoryFile, includePaths: resolvedIncludePaths } = await safelyReadMemoryFileAsync(filePath, type, resolvedPath) if (!memoryFile || !memoryFile.content.trim()) { return [] } // Add parent information if (parent) { memoryFile.parent = parent } const result: MemoryFileInfo[] = [] // Add the main file first (parent before children) result.push(memoryFile) for (const resolvedIncludePath of resolvedIncludePaths) { const isExternal = !pathInOriginalCwd(resolvedIncludePath) if (isExternal && !includeExternal) { continue } // Recursively process included files with this file as parent const includedFiles = await processMemoryFile( resolvedIncludePath, type, processedPaths, includeExternal, depth + 1, filePath, // Pass current file as parent ) result.push(...includedFiles) } return result } /** * Processes all .md files in the .claude/rules/ directory and its subdirectories * @param rulesDir The path to the rules directory * @param type Type of memory file (User, Project, Local) * @param processedPaths Set of already processed file paths * @param includeExternal Whether to include external files * @param conditionalRule If true, only include files with frontmatter paths; if false, only include files without frontmatter paths * @param visitedDirs Set of already visited directory real paths (for cycle detection) * @returns Array of MemoryFileInfo objects */ export async function processMdRules({ rulesDir, type, processedPaths, includeExternal, conditionalRule, visitedDirs = new Set(), }: { rulesDir: string type: MemoryType processedPaths: Set<string> includeExternal: boolean conditionalRule: boolean visitedDirs?: Set<string> }): Promise<MemoryFileInfo[]> { if (visitedDirs.has(rulesDir)) { return [] } try { const fs = getFsImplementation() const { resolvedPath: resolvedRulesDir, isSymlink } = safeResolvePath( fs, rulesDir, ) visitedDirs.add(rulesDir) if (isSymlink) { visitedDirs.add(resolvedRulesDir) } const result: MemoryFileInfo[] = [] let entries: import('fs').Dirent[] try { entries = await fs.readdir(resolvedRulesDir) } catch (e: unknown) { const code = getErrnoCode(e) if (code === 'ENOENT' || code === 'EACCES' || code === 'ENOTDIR') { return [] } throw e } for (const entry of entries) { const entryPath = join(rulesDir, entry.name) const { resolvedPath: resolvedEntryPath, isSymlink } = safeResolvePath( fs, entryPath, ) // Use Dirent methods for non-symlinks to avoid extra stat calls. // For symlinks, we need stat to determine what the target is. const stats = isSymlink ? await fs.stat(resolvedEntryPath) : null const isDirectory = stats ? stats.isDirectory() : entry.isDirectory() const isFile = stats ? stats.isFile() : entry.isFile() if (isDirectory) { result.push( ...(await processMdRules({ rulesDir: resolvedEntryPath, type, processedPaths, includeExternal, conditionalRule, visitedDirs, })), ) } else if (isFile && entry.name.endsWith('.md')) { const files = await processMemoryFile( resolvedEntryPath, type, processedPaths, includeExternal, ) result.push( ...files.filter(f => (conditionalRule ? f.globs : !f.globs)), ) } } return result } catch (error) { if (error instanceof Error && error.message.includes('EACCES')) { logEvent('tengu_claude_rules_md_permission_error', { is_access_error: 1, has_home_dir: rulesDir.includes(getClaudeConfigHomeDir()) ? 1 : 0, }) } return [] } } export const getMemoryFiles = memoize( async (forceIncludeExternal: boolean = false): Promise<MemoryFileInfo[]> => { const startTime = Date.now() logForDiagnosticsNoPII('info', 'memory_files_started') const result: MemoryFileInfo[] = [] const processedPaths = new Set<string>() const config = getCurrentProjectConfig() const includeExternal = forceIncludeExternal || config.hasClaudeMdExternalIncludesApproved || false // Process Managed file first (always loaded - policy settings) const managedClaudeMd = getMemoryPath('Managed') result.push( ...(await processMemoryFile( managedClaudeMd, 'Managed', processedPaths, includeExternal, )), ) // Process Managed .claude/rules/*.md files const managedClaudeRulesDir = getManagedClaudeRulesDir() result.push( ...(await processMdRules({ rulesDir: managedClaudeRulesDir, type: 'Managed', processedPaths, includeExternal, conditionalRule: false, })), ) // Process User file (only if userSettings is enabled) if (isSettingSourceEnabled('userSettings')) { const userClaudeMd = getMemoryPath('User') result.push( ...(await processMemoryFile( userClaudeMd, 'User', processedPaths, true, // User memory can always include external files )), ) // Process User ~/.claude/rules/*.md files const userClaudeRulesDir = getUserClaudeRulesDir() result.push( ...(await processMdRules({ rulesDir: userClaudeRulesDir, type: 'User', processedPaths, includeExternal: true, conditionalRule: false, })), ) } // Then process Project and Local files const dirs: string[] = [] const originalCwd = getOriginalCwd() let currentDir = originalCwd while (currentDir !== parse(currentDir).root) { dirs.push(currentDir) currentDir = dirname(currentDir) } // When running from a git worktree nested inside its main repo (e.g., // .claude/worktrees/<name>/ from `claude -w`), the upward walk passes // through both the worktree root and the main repo root. Both contain // checked-in files like CLAUDE.md and .claude/rules/*.md, so the same // content gets loaded twice. Skip Project-type (checked-in) files from // directories above the worktree but within the main repo — the worktree // already has its own checkout. CLAUDE.local.md is gitignored so it only // exists in the main repo and is still loaded. // See: https://github.com/anthropics/claude-code/issues/29599 const gitRoot = findGitRoot(originalCwd) const canonicalRoot = findCanonicalGitRoot(originalCwd) const isNestedWorktree = gitRoot !== null && canonicalRoot !== null && normalizePathForComparison(gitRoot) !== normalizePathForComparison(canonicalRoot) && pathInWorkingPath(gitRoot, canonicalRoot) // Process from root downward to CWD for (const dir of dirs.reverse()) { // In a nested worktree, skip checked-in files from the main repo's // working tree (dirs inside canonicalRoot but outside the worktree). const skipProject = isNestedWorktree && pathInWorkingPath(dir, canonicalRoot) && !pathInWorkingPath(dir, gitRoot) // Try reading CLAUDE.md (Project) - only if projectSettings is enabled if (isSettingSourceEnabled('projectSettings') && !skipProject) { const projectPath = join(dir, 'CLAUDE.md') result.push( ...(await processMemoryFile( projectPath, 'Project', processedPaths, includeExternal, )), ) // Try reading .claude/CLAUDE.md (Project) const dotClaudePath = join(dir, '.claude', 'CLAUDE.md') result.push( ...(await processMemoryFile( dotClaudePath, 'Project', processedPaths, includeExternal, )), ) // Try reading .claude/rules/*.md files (Project) const rulesDir = join(dir, '.claude', 'rules') result.push( ...(await processMdRules({ rulesDir, type: 'Project', processedPaths, includeExternal, conditionalRule: false, })), ) } // Try reading CLAUDE.local.md (Local) - only if localSettings is enabled if (isSettingSourceEnabled('localSettings')) { const localPath = join(dir, 'CLAUDE.local.md') result.push( ...(await processMemoryFile( localPath, 'Local', processedPaths, includeExternal, )), ) } } // Process CLAUDE.md from additional directories (--add-dir) if env var is enabled // This is controlled by CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD and defaults to off // Note: we don't check isSettingSourceEnabled('projectSettings') here because --add-dir // is an explicit user action and the SDK defaults settingSources to [] when not specified if (isEnvTruthy(process.env.CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD)) { const additionalDirs = getAdditionalDirectoriesForClaudeMd() for (const dir of additionalDirs) { // Try reading CLAUDE.md from the additional directory const projectPath = join(dir, 'CLAUDE.md') result.push( ...(await processMemoryFile( projectPath, 'Project', processedPaths, includeExternal, )), ) // Try reading .claude/CLAUDE.md from the additional directory const dotClaudePath = join(dir, '.claude', 'CLAUDE.md') result.push( ...(await processMemoryFile( dotClaudePath, 'Project', processedPaths, includeExternal, )), ) // Try reading .claude/rules/*.md files from the additional directory const rulesDir = join(dir, '.claude', 'rules') result.push( ...(await processMdRules({ rulesDir, type: 'Project', processedPaths, includeExternal, conditionalRule: false, })), ) } } // Memdir entrypoint (memory.md) - only if feature is on and file exists if (isAutoMemoryEnabled()) { const { info: memdirEntry } = await safelyReadMemoryFileAsync( getAutoMemEntrypoint(), 'AutoMem', ) if (memdirEntry) { const normalizedPath = normalizePathForComparison(memdirEntry.path) if (!processedPaths.has(normalizedPath)) { processedPaths.add(normalizedPath) result.push(memdirEntry) } } } // Team memory entrypoint - only if feature is on and file exists if (feature('TEAMMEM') && teamMemPaths!.isTeamMemoryEnabled()) { const { info: teamMemEntry } = await safelyReadMemoryFileAsync( teamMemPaths!.getTeamMemEntrypoint(), 'TeamMem', ) if (teamMemEntry) { |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |