spacehub

surshar / claude-code

Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.

Built by Anthropic · github.com/anthropics

claude-code / mods / agents-md / hooks / files / with-project-files.ts
37 lines · 1.1 KBRaw
1import type { InstructionFile } from 'claude-code'
2
3import { chainRootOf } from './chain-root-of.js'
4import { insertionIndex } from './insertion-index.js'
5import { projectDirOf } from './project-dir-of.js'
6
7/**
8 * The engine's instruction files with the AGENTS.md files placed where the
9 * engine would place a project file of their directory; as is when none.
10 *
11 * @param handed the files the engine handed the hook, in its order
12 * @param added the AGENTS.md instruction files to add, root first
13 * @returns the merged list
14 */
15export function withProjectFiles(
16 handed: readonly InstructionFile[],
17 added: readonly InstructionFile[],
18): readonly InstructionFile[] {
19 if (added.length === 0) {
20 return handed
21 }
22
23 const merged = [...handed]
24 const byPath = new Map(added.map(file => [file.path, file]))
25 const byDir = new Map<string, InstructionFile[]>()
26
27 for (const file of added) {
28 const dir = projectDirOf(chainRootOf(file, byPath))
29 byDir.set(dir, [...(byDir.get(dir) ?? []), file])
30 }
31
32 for (const [dir, files] of byDir) {
33 merged.splice(insertionIndex(merged, dir), 0, ...files)
34 }
35
36 return merged
37}