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 / insertion-index.ts
44 lines · 1.3 KBRaw
1import type { InstructionFile } from 'claude-code'
2
3import Frames from '../frames'
4import { chainRootOf } from './chain-root-of.js'
5import { isProjectOwn } from './is-project-own.js'
6import { projectDirOf } from './project-dir-of.js'
7
8/**
9 * Where a directory's AGENTS.md files go among the files the engine loaded,
10 * as the engine orders project files root first.
11 *
12 * Before the first project file of a deeper directory (an imported file
13 * counts with the file at the head of its chain), else after the last
14 * project file, else before the engine's memory, else at the end.
15 *
16 * @param files the list so far
17 * @param dir the directory the AGENTS.md files stand in
18 * @returns the index to insert at
19 */
20export function insertionIndex(
21 files: readonly InstructionFile[],
22 dir: string,
23): number {
24 const byPath = new Map(files.map(file => [file.path, file]))
25 const deeper = files.findIndex(
26 file =>
27 isProjectOwn(file) &&
28 Frames.isBelow(projectDirOf(chainRootOf(file, byPath)), dir),
29 )
30
31 if (deeper !== -1) {
32 return deeper
33 }
34
35 const lastOwn = files.findLastIndex(isProjectOwn)
36
37 if (lastOwn !== -1) {
38 return lastOwn + 1
39 }
40
41 const memory = files.findIndex(file => file.kind === 'memory')
42
43 return memory === -1 ? files.length : memory
44}