ai-ops-compiler 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +124 -0
  2. package/data/presets.yaml +52 -0
  3. package/data/references/README.md +34 -0
  4. package/data/references/claude-code/best-practices/context-optimization.md +114 -0
  5. package/data/references/claude-code/hooks.md +65 -0
  6. package/data/references/claude-code/rules.md +63 -0
  7. package/data/references/claude-code/skills.md +72 -0
  8. package/data/references/codex/best-practices/context-optimization.md +120 -0
  9. package/data/references/codex/rules.md +53 -0
  10. package/data/references/codex/skills.md +68 -0
  11. package/data/references/gemini-cli/best-practices/context-optimization.md +54 -0
  12. package/data/references/gemini-cli/custom-commands.md +60 -0
  13. package/data/references/gemini-cli/hooks.md +61 -0
  14. package/data/references/gemini-cli/rules.md +55 -0
  15. package/data/references/gemini-cli/skills.md +65 -0
  16. package/data/rules/ai-llm-python.yaml +35 -0
  17. package/data/rules/code-philosophy.yaml +30 -0
  18. package/data/rules/communication.yaml +11 -0
  19. package/data/rules/data-pipeline-python.yaml +34 -0
  20. package/data/rules/engineering-standards.yaml +40 -0
  21. package/data/rules/fastapi.yaml +37 -0
  22. package/data/rules/flutter.yaml +40 -0
  23. package/data/rules/graphql.yaml +34 -0
  24. package/data/rules/libs-backend-python.yaml +36 -0
  25. package/data/rules/libs-backend-ts.yaml +43 -0
  26. package/data/rules/libs-frontend-app.yaml +42 -0
  27. package/data/rules/libs-frontend-web.yaml +49 -0
  28. package/data/rules/naming-convention.yaml +10 -0
  29. package/data/rules/nestjs-graphql.yaml +31 -0
  30. package/data/rules/nestjs.yaml +26 -0
  31. package/data/rules/nextjs.yaml +34 -0
  32. package/data/rules/prisma-postgresql.yaml +30 -0
  33. package/data/rules/python.yaml +31 -0
  34. package/data/rules/react-typescript.yaml +11 -0
  35. package/data/rules/role-persona.yaml +14 -0
  36. package/data/rules/shadcn-ui.yaml +36 -0
  37. package/data/rules/sqlalchemy.yaml +32 -0
  38. package/data/rules/typescript.yaml +22 -0
  39. package/dist/index.d.ts +339 -0
  40. package/dist/index.js +379 -0
  41. package/dist/index.js.map +1 -0
  42. package/package.json +38 -0
package/README.md ADDED
@@ -0,0 +1,124 @@
1
+ # @ai-ops/compiler
2
+
3
+ SSOT(Single Source of Truth) YAML 룰 파일을 읽어, 각 AI 도구(Claude Code, Codex, Gemini)에 맞는 Markdown 파일로 변환·설치하기 위한 **Pure 함수 라이브러리**.
4
+
5
+ CLI(`@ai-ops/cli`)가 이 패키지를 조합해 실제 파일 쓰기를 수행한다.
6
+
7
+ ---
8
+
9
+ ## Architecture
10
+
11
+ ```
12
+ YAML rules + presets.yaml
13
+
14
+
15
+ [loader] YAML → Rule[] / Preset[]
16
+ │ resolvePresetRules → excludeRules (TUI 세부조정)
17
+
18
+ [renderer] Rule[] → 도구별 Markdown
19
+
20
+
21
+ [install-plan] Markdown → FileAction[] (경로 + 헤더 포함 컨텐츠)
22
+
23
+
24
+ CLI file write FileAction[] → 실제 파일 기록
25
+
26
+
27
+ [manifest-io] .ai-ops-manifest.json 저장
28
+
29
+ (next install)
30
+
31
+
32
+ [diff] 이전 Manifest vs 현재 상태 → DiffResult
33
+ ```
34
+
35
+ ---
36
+
37
+ ## `src/` 구조
38
+
39
+ ```
40
+ src/
41
+ ├── schemas/
42
+ │ ├── rule.schema.ts Rule, RuleContent, DecisionTableEntry 타입 + Zod 스키마
43
+ │ ├── preset.schema.ts Preset 타입 + Zod 스키마
44
+ │ └── manifest.schema.ts Manifest 타입 + Zod 스키마 (설치 추적 메타데이터)
45
+
46
+ ├── loader.ts YAML 파일 읽기 → Rule[] / Preset[] 파싱
47
+ ├── renderer.ts Rule[] → 도구별 Markdown 렌더링
48
+ ├── tool-output.ts 도구별 경로·전략 상수 (TOOL_OUTPUT_MAP, ToolId)
49
+ ├── source-hash.ts YAML 파일 내용 기반 sourceHash 계산 + Manifest 빌더
50
+ ├── managed-header.ts 파일에 ai-ops 소유 헤더 삽입·판별·파싱·제거
51
+ ├── manifest-io.ts .ai-ops-manifest.json 직렬화·역직렬화 + 파일 I/O
52
+ ├── diff.ts 이전 Manifest vs 현재 상태 비교 → DiffResult
53
+ ├── install-plan.ts renderForTool 결과 → FileAction[] (설치 계획)
54
+ └── index.ts barrel export
55
+ ```
56
+
57
+ ---
58
+
59
+ ## 주요 함수
60
+
61
+ ### loader
62
+
63
+ | 함수 | 설명 |
64
+ | -------------------------------------- | ------------------------------------------------------------------- |
65
+ | `loadAllRules(rulesDir)` | 디렉토리의 모든 `.yaml` 룰 파일 로딩 |
66
+ | `loadPresets(presetsPath)` | `presets.yaml` → `Preset[]` |
67
+ | `resolvePresetRules(preset, allRules)` | preset의 rule ID 목록 → `Rule[]` (priority 정렬) |
68
+ | `excludeRules(rules, excludeIds)` | TUI 세부조정용. 사용자가 해제한 rule ID 제거 → 나머지 `Rule[]` 반환 |
69
+
70
+ ### renderer
71
+
72
+ | 함수 | 설명 |
73
+ | ------------------------------ | ---------------------------------------------------------- |
74
+ | `renderForTool(toolId, rules)` | 핵심 진입점. 도구별 `ToolRenderResult` 반환 |
75
+ | `renderClaudeCodeRule(rule)` | 단일 Rule → Claude Code용 Markdown (path frontmatter 포함) |
76
+ | `renderRulesToMarkdown(rules)` | Rule[] → `---` separator 단일 Markdown |
77
+ | `partitionRules(rules)` | `{ global, domain }` 분리 |
78
+
79
+ ### source-hash
80
+
81
+ | 함수 | 설명 |
82
+ | ----------------------------- | --------------------------------------------------------- |
83
+ | `computeSourceHash(rulesDir)` | YAML 파일 내용 기반 SHA-256 → 6자리 hex. YAML 수정 감지용 |
84
+ | `buildManifest(params)` | Manifest 객체 생성 (generatedAt = 현재 시각) |
85
+
86
+ ### managed-header
87
+
88
+ | 함수 | 설명 |
89
+ | ------------------------------- | -------------------------------------------------------------------- |
90
+ | `wrapWithHeader(content, meta)` | `<!-- managed by ai-ops -->` 헤더 + sourceHash/generatedAt 메타 삽입 |
91
+ | `isManagedFile(content)` | ai-ops가 소유한 파일인지 판별 |
92
+ | `parseManagedHeader(content)` | 헤더에서 `{ sourceHash, generatedAt }` 추출 |
93
+ | `stripManagedHeader(content)` | 헤더 제거 → 순수 컨텐츠 반환 |
94
+
95
+ ### manifest-io
96
+
97
+ | 함수 | 설명 |
98
+ | ------------------------------- | ------------------------------------------- |
99
+ | `readManifest(path)` | `.ai-ops-manifest.json` 읽기. 없으면 `null` |
100
+ | `writeManifest(path, manifest)` | 디렉토리 자동 생성 후 JSON 저장 |
101
+ | `parseManifest(json)` | JSON string → Zod 검증된 `Manifest` |
102
+ | `serializeManifest(manifest)` | `Manifest` → pretty-print JSON string |
103
+
104
+ ### diff
105
+
106
+ | 함수 | 설명 |
107
+ | ------------------------------------------------------------ | ----------------------------------------------------------------------------- |
108
+ | `computeDiff({ previous, currentRules, currentSourceHash })` | Set 비교로 `added` / `removed` 계산, `sourceHash` 비교로 `sourceChanged` 판단 |
109
+
110
+ ### install-plan
111
+
112
+ | 함수 | 설명 |
113
+ | -------------------------------------------------- | ------------------------------------------------------------------------------------- |
114
+ | `buildInstallPlan({ toolId, renderResult, meta })` | 렌더링 결과 → `FileAction[]`. 각 action에 managed header 포함. 빈 content는 자동 생략 |
115
+
116
+ ---
117
+
118
+ ## 도구별 출력 파일
119
+
120
+ | Tool | 파일 |
121
+ | ------------- | ---------------------------------------------------------------- |
122
+ | `claude-code` | `.claude/rules/{rule-id}.md` (룰당 1파일, path frontmatter 포함) |
123
+ | `codex` | `AGENTS.md` (global) + `AGENTS.override.md` (domain) |
124
+ | `gemini` | `GEMINI.md` (global) + `GEMINI.md` (domain, 하위 폴더) |
@@ -0,0 +1,52 @@
1
+ frontend-web:
2
+ description: '웹 프론트엔드 프로젝트를 위한 프리셋'
3
+ rules:
4
+ - role-persona
5
+ - communication
6
+ - code-philosophy
7
+ - naming-convention
8
+ - engineering-standards
9
+ - typescript
10
+ - react-typescript
11
+ - shadcn-ui
12
+ - nextjs
13
+ - libs-frontend-web
14
+
15
+ frontend-app:
16
+ description: '앱 프론트엔드 프로젝트를 위한 프리셋'
17
+ rules:
18
+ - role-persona
19
+ - communication
20
+ - code-philosophy
21
+ - naming-convention
22
+ - engineering-standards
23
+ - flutter
24
+ - libs-frontend-app
25
+
26
+ backend-ts:
27
+ description: 'TypeScript 백엔드 프로젝트를 위한 프리셋'
28
+ rules:
29
+ - role-persona
30
+ - communication
31
+ - code-philosophy
32
+ - naming-convention
33
+ - engineering-standards
34
+ - typescript
35
+ - nestjs
36
+ - prisma-postgresql
37
+ - graphql
38
+ - nestjs-graphql
39
+ - libs-backend-ts
40
+
41
+ backend-python:
42
+ description: 'Python 백엔드 프로젝트를 위한 프리셋'
43
+ rules:
44
+ - role-persona
45
+ - communication
46
+ - code-philosophy
47
+ - naming-convention
48
+ - engineering-standards
49
+ - python
50
+ - fastapi
51
+ - sqlalchemy
52
+ - libs-backend-python
@@ -0,0 +1,34 @@
1
+ # 공식문서 압축용 프롬프트
2
+
3
+ ```txt
4
+ [System Role]
5
+ You are a 'Technical Context Compressor' responsible for context window optimization in a Multi-Agent environment.
6
+ Your objective is to maximize information density and perform lossless abstraction on the provided raw official documentation. The output must be heavily structured, machine-readable, and instantly actionable as execution rule-sets for target AI agents (e.g., Codex, Gemini).
7
+
8
+ [Compression Rules]
9
+ 1. Remove Noise (Decimation): Completely eliminate narrative sentences intended for human comprehension, philosophical backgrounds, greetings, and redundantly repeated code examples.
10
+ 2. Preserve Hard Facts (Immutability): Preserve absolute exactness for file paths, CLI commands, environment variables, essential syntax (e.g., YAML frontmatter, @import), and supported string matching patterns (e.g., Glob patterns). Do not alter or omit a single byte of these factual elements.
11
+ 3. Structuring (Topology): Logically classify the configuration hierarchy, scope (Global vs. Local), and execution priority.
12
+ 4. Format (Serialization): Strictly utilize Markdown tables and tree structures to allow target agents to easily parse and map the data.
13
+
14
+ [Input Documentation]
15
+ {{Insert the raw official documentation text here}}
16
+
17
+ [Output Specification]
18
+ Strictly adhere to the Markdown template structure below for the final output.
19
+
20
+ # [Technology/Feature Name] Agent Instruction Manual
21
+
22
+ ## 1. Core Architecture & Hierarchy
23
+ (Briefly specify the priority tree and hierarchical structure of the configuration files. Use `>` or list formats to show precedence.)
24
+
25
+ ## 2. Config & Path Specs
26
+ | Scope | Directory / Path | Capability / Purpose | Override Rules |
27
+ | :--- | :--- | :--- | :--- |
28
+ | ... | ... | ... | ... |
29
+
30
+ ## 3. Syntax & Commands (Hard Constraints)
31
+ - Mandatory Commands:
32
+ - Special Syntax Rules (e.g., Conditional constraints, Frontmatter):
33
+ - Caveats & Constraints (Critical rules to prevent Fatal Errors):
34
+ ```
@@ -0,0 +1,114 @@
1
+ # Agent Context Optimization Strategies (Claude Code)
2
+
3
+ This document outlines architectural patterns and best practices for managing context payload effectively within the Claude Code environment, building on the official specification in `references/claude-code/rules.md`.
4
+
5
+ ## The Challenge: Context Bloat
6
+
7
+ Claude Code's memory system eagerly loads CLAUDE.md files at session start (recursive lookup from CWD upward). Using `@import` to pull in domain-specific rules globally causes:
8
+
9
+ 1. **Token Exhaustion:** Loading Python rules while working on a React component wastes context window.
10
+ 2. **Attention Dilution:** Increased instruction density raises the likelihood of the LLM missing or misinterpreting rules.
11
+
12
+ ## Solution 1: Path-Scoped Rules (Claude Code Native — Preferred)
13
+
14
+ Claude Code has a **native lazy-loading mechanism** that Gemini CLI lacks: `paths:` frontmatter in `.claude/rules/*.md`.
15
+
16
+ Rules are automatically activated **only** when the agent reads a file matching the declared glob pattern. No manual registry required.
17
+
18
+ ```yaml
19
+ # .claude/rules/react-typescript.md
20
+ ---
21
+ paths:
22
+ - 'src/**/*.tsx'
23
+ - 'src/**/*.ts'
24
+ ---
25
+ # React & TypeScript Rules
26
+ ...
27
+ ```
28
+
29
+ ```yaml
30
+ # .claude/rules/python.md
31
+ ---
32
+ paths:
33
+ - '**/*.py'
34
+ - 'pyproject.toml'
35
+ ---
36
+ # Python Rules
37
+ ...
38
+ ```
39
+
40
+ **Result:** The agent loads Python rules only when it opens a `.py` file. React rules only when touching `.tsx`. Zero manual orchestration.
41
+
42
+ ### Recommended Rule File Layout
43
+
44
+ ```
45
+ .claude/
46
+ rules/
47
+ role-persona.md # No paths: → always loaded (global)
48
+ communication.md # No paths: → always loaded (global)
49
+ code-philosophy.md # No paths: → always loaded (global)
50
+ typescript.md # paths: src/**/*.ts
51
+ react-typescript.md # paths: src/**/*.tsx
52
+ nextjs.md # paths: src/app/**, next.config.*
53
+ python.md # paths: **/*.py
54
+ fastapi.md # paths: **/routers/**, **/main.py
55
+ prisma-postgresql.md # paths: prisma/**, **/*.prisma
56
+ ```
57
+
58
+ ## Solution 2: Child Directory CLAUDE.md (Package-Level Isolation)
59
+
60
+ In monorepos, place domain-specific rules in the package's own `.claude/CLAUDE.md`. Claude Code only loads these **on-demand** when files in that subtree are read.
61
+
62
+ ```
63
+ monorepo/
64
+ .claude/CLAUDE.md # Global: persona, communication, philosophy
65
+ packages/
66
+ frontend/
67
+ .claude/CLAUDE.md # Loaded only when working in frontend/
68
+ backend/
69
+ .claude/CLAUDE.md # Loaded only when working in backend/
70
+ data-pipeline/
71
+ .claude/CLAUDE.md # Loaded only when working in data-pipeline/
72
+ ```
73
+
74
+ **Caveat:** Requires that Claude actually reads a file within the subtree to trigger loading. Does not activate based on directory navigation alone.
75
+
76
+ ## Solution 3: Manual Rule Registry (Fallback)
77
+
78
+ Use when Solutions 1 and 2 are insufficient — for example, when rules cannot be mapped to file path patterns (e.g., architecture decisions, API design guidelines).
79
+
80
+ Inject a **Rule Registry** into the base CLAUDE.md instructing the agent to self-load rules using the `Read` tool:
81
+
82
+ ```markdown
83
+ # 🚨 Dynamic Rule Loading (CRITICAL)
84
+
85
+ DO NOT guess architectural or stylistic rules. Before modifying or generating
86
+ code, you MUST use the Read tool to load the relevant rule file based on the
87
+ tech stack you are working on.
88
+
89
+ **Rule Registry Location:** `packages/compiler/data/rules/*.yaml`
90
+
91
+ **Mapping:**
92
+
93
+ - **Python / Backend**: Read `python.yaml`, `fastapi.yaml`, `libs-backend-python.yaml`
94
+ - **React / Frontend**: Read `react-typescript.yaml`, `nextjs.yaml`, `shadcn-ui.yaml`
95
+ - **Database**: Read `sqlalchemy.yaml` or `prisma-postgresql.yaml`
96
+ - **GraphQL**: Read `graphql.yaml`, `nestjs-graphql.yaml`
97
+ ```
98
+
99
+ ## Decision Matrix
100
+
101
+ | Scenario | Recommended Solution |
102
+ | ------------------------------------------ | --------------------------------------------- |
103
+ | Rules map cleanly to file extensions/paths | **Solution 1** — `paths:` frontmatter |
104
+ | Monorepo with clearly separated packages | **Solution 2** — Child directory CLAUDE.md |
105
+ | Cross-cutting rules not tied to file paths | **Solution 3** — Manual Rule Registry |
106
+ | Universal rules (persona, communication) | No optimization needed — always load globally |
107
+
108
+ ## Summary
109
+
110
+ - **DO** use `paths:` frontmatter for domain-specific rules. This is Claude Code's native, zero-overhead lazy-loading.
111
+ - **DO** place package-level rules in child `.claude/CLAUDE.md` in monorepos.
112
+ - **DO NOT** use `@import` for large, domain-specific rulesets in the global CLAUDE.md.
113
+ - **DO** keep globally loaded rules minimal: persona, communication, core philosophy only.
114
+ - **DO** fall back to a Manual Rule Registry only when path-scoping is impossible.
@@ -0,0 +1,65 @@
1
+ ---
2
+ source: https://docs.anthropic.com/en/docs/claude-code/hooks
3
+ last_fetched: 2026-02-26
4
+ ---
5
+
6
+ # Claude Code Hooks Agent Instruction Manual
7
+
8
+ ## 1. Core Architecture & Hierarchy
9
+
10
+ **Priority & Scope Topology (Highest to Lowest Specificity):**
11
+
12
+ 1. `Component` (Skill/Agent YAML Frontmatter)
13
+ 2. `Plugin` (`hooks/hooks.json`)
14
+ 3. `Project (Local)` (`.claude/settings.local.json`)
15
+ 4. `Project (Shared)` (`.claude/settings.json`)
16
+ 5. `User (Global)` (`~/.claude/settings.json`)
17
+ 6. `Managed Policy` (Organization-wide settings)
18
+
19
+ **Execution Pipeline & Resolution:**
20
+
21
+ - `Event Trigger` -> `Matcher Validation (Regex)` -> `Handler Execution (Command/Prompt/Agent)` -> `Outcome Evaluation (Exit Code & JSON)`
22
+
23
+ ## 2. Config & Path Specs
24
+
25
+ | Scope | Directory / Path | Capability / Purpose | Override Rules |
26
+ | -------------------- | ----------------------------------------------------------- | --------------------------------------------- | ------------------------------------------------------------------- |
27
+ | **Org Policy** | Managed policy settings | Enforce organization-wide security/compliance | Overrides user `disableAllHooks` if `allowManagedHooksOnly` is true |
28
+ | **User (Global)** | `~/.claude/settings.json` | Cross-project personal workflows/preferences | Overridden by local/project configs |
29
+ | **Project (Shared)** | `.claude/settings.json` | Team-shared repo hooks | Committed to version control |
30
+ | **Project (Local)** | `.claude/settings.local.json` | Private sandbox hooks | Auto-gitignored |
31
+ | **Plugin** | `hooks/hooks.json` | Plugin-bundled automation | Active only when plugin is enabled |
32
+ | **Component** | `hooks:` field in `SKILL.md` / agent `.md` YAML Frontmatter | Component lifecycle-scoped hooks | Active only during component runtime |
33
+
34
+ ## 3. Syntax & Commands (Hard Constraints)
35
+
36
+ - **Mandatory Commands & Environment Variables:**
37
+ - `claude --debug` / `Ctrl+O`: Exposes hook execution traces, stdout/stderr, and match states.
38
+ - `/hooks`: Interactive CLI menu to manage/toggle hook configurations.
39
+ - `$CLAUDE_PROJECT_DIR`: Resolves to the absolute project root path.
40
+ - `${CLAUDE_PLUGIN_ROOT}`: Resolves to the active plugin directory.
41
+ - `$CLAUDE_ENV_FILE`: Writable file path for persisting `export` statements (Strictly available to `SessionStart` hooks only).
42
+ - `$CLAUDE_CODE_REMOTE`: Set to `"true"` in remote web environments.
43
+
44
+ - **Special Syntax Rules (Conditional constraints, Schema):**
45
+ - **Hook Types:**
46
+ - `"command"`: Spawns shell processes. Parses stdout for JSON on exit `0`.
47
+ - `"prompt"`: Single-turn LLM evaluation. Injects input via `$ARGUMENTS` placeholder. Output must be `{"ok": boolean, "reason": "..."}`.
48
+ - `"agent"`: Multi-turn subagent verification (Max 50 turns). Injects input via `$ARGUMENTS`.
49
+
50
+ - **Matchers (Regex):** Filters execution based on target fields (e.g., `tool_name` for `PreToolUse`, `agent_type` for `SubagentStart`).
51
+ - Ex: `"Bash"`, `"Edit|Write"`, `"mcp__.*"`.
52
+ - Events without matcher support (always fire): `UserPromptSubmit`, `Stop`, `TeammateIdle`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `PreCompact`.
53
+
54
+ - **Decision Control (JSON via Stdout on Exit 0):**
55
+ - _Universal:_ `{"continue": false, "stopReason": "..."}` (Hard stop agent).
56
+ - _Top-Level:_ `{"decision": "block", "reason": "..."}` (`UserPromptSubmit`, `PostToolUse`, `Stop`, `ConfigChange`).
57
+ - _Nested (PreToolUse):_ `{"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "allow|deny|ask", "updatedInput": {...}}}`.
58
+ - _Nested (PermissionRequest):_ `{"hookSpecificOutput": {"hookEventName": "PermissionRequest", "decision": {"behavior": "allow|deny", "updatedInput": {...}}}}`.
59
+
60
+ - **Caveats & Constraints (Critical rules to prevent Fatal Errors):**
61
+ - **Exit Code 2 (Blocking):** Forces an immediate block. **ALL stdout JSON is ignored**. Stderr text is fed back to the LLM.
62
+ - **JSON Purity (Exit 0):** If utilizing JSON decision control, `stdout` must contain _only_ valid JSON. Extraneous shell profile echoes will trigger parser failures.
63
+ - **Async Hook Restrictions:** `"async": true` is strictly limited to `"command"` types. Background hooks cannot return decisions, block events, or modify execution flow.
64
+ - **WorktreeCreate Payload:** Must output exactly the absolute path to the directory on `stdout` and exit `0`. JSON decision objects are strictly prohibited for this event.
65
+ - **State Mutations:** Hook files are cached at session startup. Mid-session file edits trigger a warning and require manual `/hooks` menu approval to reload.
@@ -0,0 +1,63 @@
1
+ ---
2
+ source: https://docs.anthropic.com/en/docs/claude-code/memory
3
+ last_fetched: 2026-02-26
4
+ ---
5
+
6
+ # Claude Code Memory Management Agent Instruction Manual
7
+
8
+ ## 1. Core Architecture & Hierarchy
9
+
10
+ **Priority Topology (Lowest to Highest Specificity):**
11
+
12
+ 1. `Managed policy` (Organization-wide instructions)
13
+ 2. `User rules` (`~/.claude/rules/*.md`)
14
+ 3. `User memory` (`~/.claude/CLAUDE.md`)
15
+ 4. `Project memory` & `Project rules` (`./CLAUDE.md`, `./.claude/CLAUDE.md`, `./.claude/rules/*.md`)
16
+ 5. `Project memory (local)` (`./CLAUDE.local.md`)
17
+
18
+ **Context Injection & Loading Strategy:**
19
+
20
+ - **Parent Directories:** Loaded in full at launch (recursive lookup from CWD up to, but not including, root `/`).
21
+ - **Child Directories:** Loaded on-demand when files in subtrees are read.
22
+ - **Auto Memory:** First 200 lines of `MEMORY.md` loaded at session start. Content beyond 200 lines and modular topic files (e.g., `debugging.md`) are loaded on-demand.
23
+
24
+ ## 2. Config & Path Specs
25
+
26
+ | Scope | Directory / Path | Capability / Purpose | Override Rules |
27
+ | -------------------- | ------------------------------------------------------------------ | -------------------------------------------------------- | ------------------------------ |
28
+ | **Org (macOS)** | `/Library/Application Support/ClaudeCode/CLAUDE.md` | IT/DevOps managed policy | Lowest Priority |
29
+ | **Org (Linux)** | `/etc/claude-code/CLAUDE.md` | IT/DevOps managed policy | Lowest Priority |
30
+ | **Org (Windows)** | `C:\Program Files\ClaudeCode\CLAUDE.md` | IT/DevOps managed policy | Lowest Priority |
31
+ | **User (Global)** | `~/.claude/CLAUDE.md` <br> `~/.claude/rules/*.md` | Personal preferences / workflows for all projects | Overridden by Project configs |
32
+ | **Project (Shared)** | `./CLAUDE.md` or `./.claude/CLAUDE.md` <br> `./.claude/rules/*.md` | Team-shared modular rules, testing, architecture | Overrides User configs |
33
+ | **Project (Local)** | `./CLAUDE.local.md` | Private sandbox preferences (Auto added to `.gitignore`) | Highest Priority |
34
+ | **Auto Memory** | `~/.claude/projects/<project>/memory/` | Agent's internal learnings, debug patterns, indexes | Subject to 200-line load limit |
35
+
36
+ ## 3. Syntax & Commands (Hard Constraints)
37
+
38
+ - **Mandatory Commands & Environment Variables:**
39
+ - `export CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` (Force OFF) / `0` (Force ON).
40
+ - `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1 claude --add-dir <path>` (Evaluates memory files in external directories).
41
+ - `/memory` (CLI command to open file selector/system editor).
42
+ - `/init` (CLI command to bootstrap codebase `./CLAUDE.md`).
43
+
44
+ - **Special Syntax Rules (Conditional constraints, Frontmatter):**
45
+ - **Imports Syntax:** `@path/to/import` (Supports relative, absolute, and `~` home-directory paths).
46
+ - **YAML Frontmatter:** Apply target-specific scoped rules in `.claude/rules/*.md`.
47
+
48
+ ```yaml
49
+ ---
50
+ paths:
51
+ - 'src/**/*.ts'
52
+ - '{src,lib}/**/*.{ts,tsx}'
53
+ ---
54
+ ```
55
+
56
+ - **Glob/Brace Patterns:** `**/*.ts` (Recursive), `src/**/*` (All under dir), `*.md` (Root only), `{src,lib}` (Multiple targets).
57
+
58
+ - **Caveats & Constraints (Critical rules to prevent Fatal Errors):**
59
+ - **Import Escaping:** `@import` statements are strictly ignored inside markdown code spans and code blocks.
60
+ - **Max Recursion:** Imported files can recursively import additional files with a hard limit of **5 hops**.
61
+ - **Security Gate:** First-time cross-project/external imports prompt a one-time GUI approval dialog. If declined, imports are permanently disabled for that path.
62
+ - **Path Resolution:** The `<project>` Auto memory path strictly derives from the Git repository root. Git worktrees spawn separate memory directories. Non-Git environments default to the working directory.
63
+ - **Symlink Handling:** `.claude/rules/` resolves symlinks natively; circular symlinks are detected and bypassed.
@@ -0,0 +1,72 @@
1
+ ---
2
+ source: https://docs.anthropic.com/en/docs/claude-code/skills
3
+ last_fetched: 2026-02-26
4
+ ---
5
+
6
+ # Claude Code Skills Agent Instruction Manual
7
+
8
+ ## 1. Core Architecture & Hierarchy
9
+
10
+ **Priority & Scope Topology (Highest to Lowest Specificity):**
11
+
12
+ 1. `Enterprise` (Managed settings files)
13
+ 2. `Personal` (`~/.claude/skills/<skill-name>/SKILL.md`)
14
+ 3. `Project` (`.claude/skills/<skill-name>/SKILL.md`)
15
+ 4. `Plugin` (`<plugin>/skills/<skill-name>/SKILL.md`)
16
+
17
+ **Execution & Resolution Rules:**
18
+
19
+ - **Legacy Override:** Skills take precedence over legacy `.claude/commands/*.md` files sharing the same name.
20
+ - **Namespace Isolation:** Plugin skills utilize a `plugin-name:skill-name` namespace to prevent collisions.
21
+ - **Nested Discovery:** Skills are automatically discovered from nested `.claude/skills/` directories relative to the active working directory. In monorepos, skills in each package's `.claude/skills/` are discovered when that package's directory is active (requires `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1` for `--add-dir` paths).
22
+ - **Context Budget:** Skill descriptions load into context dynamically (budgeted at 2% of context window, 16,000 chars fallback).
23
+
24
+ ## 2. Config & Path Specs
25
+
26
+ | Scope | Directory / Path | Capability / Purpose | Override Rules |
27
+ | -------------- | ---------------------------------------- | ------------------------------------------ | --------------------------- |
28
+ | **Enterprise** | Managed Settings | Organization-wide standard enforcement | Highest Priority |
29
+ | **Personal** | `~/.claude/skills/<skill-name>/SKILL.md` | Global user-specific custom slash commands | Overridden by Enterprise |
30
+ | **Project** | `./.claude/skills/<skill-name>/SKILL.md` | Repo-scoped workflows and execution logic | Overridden by Personal |
31
+ | **Plugin** | `<plugin>/skills/<skill-name>/SKILL.md` | Bundled third-party automations | Namespaced (`plugin:skill`) |
32
+ | **Legacy** | `./.claude/commands/*.md` | Deprecated command definitions | Overridden by Skills |
33
+
34
+ ## 3. Syntax & Commands (Hard Constraints)
35
+
36
+ - **Mandatory Commands & Environment Variables:**
37
+ - `/<skill-name>`: CLI invocation of a specific skill.
38
+ - `/context`: Audits context budget and warns if skills are excluded due to character limits.
39
+ - `SLASH_COMMAND_TOOL_CHAR_BUDGET`: Env var to override the default 16,000 character skill description context limit.
40
+ - `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`: Env var required to load skills from `--add-dir` paths.
41
+
42
+ - **Special Syntax Rules (Conditional constraints, Frontmatter):**
43
+ - **YAML Frontmatter Fields (Top of `SKILL.md`):**
44
+
45
+ ```yaml
46
+ ---
47
+ name: string # Max 64 chars (a-z, 0-9, -). Defaults to dir name.
48
+ description: string # Recommended. Used by LLM for auto-triggering.
49
+ disable-model-invocation: boolean # Default false. True = Manual CLI trigger only.
50
+ user-invocable: boolean # Default true. False = Hidden from UI, LLM trigger only.
51
+ allowed-tools: string # CSV list (e.g., Read, Grep, Bash).
52
+ context: fork # Spawns skill in an isolated subagent context.
53
+ agent: string # Subagent type. Requires `context: fork`. Valid values: general-purpose, Explore, Plan, claude-code-guide, etc.
54
+ ---
55
+ ```
56
+
57
+ - **String Substitution Variables:**
58
+ - `$ARGUMENTS`: Injects all provided CLI arguments. (If omitted in template, appended as `ARGUMENTS: <value>`).
59
+ - `$ARGUMENTS[N]` or `$N`: Positional argument injection (0-based index).
60
+ - `${CLAUDE_SESSION_ID}`: Injects the current active session ID.
61
+
62
+ - **Dynamic Context Injection:**
63
+ - `!`command``: Executes shell command _before_ prompt ingestion. Output permanently replaces the placeholder in the prompt fed to the LLM.
64
+
65
+ - **Permission Target Matching (`/permissions`):**
66
+ - `Skill(name)`: Exact match.
67
+ - `Skill(name *)`: Prefix match with any arguments.
68
+
69
+ - **Caveats & Constraints (Critical rules to prevent Fatal Errors):**
70
+ - **Subagent Forking Constraints:** `context: fork` requires explicit, actionable task instructions within the markdown body. Purely declarative guidelines (e.g., coding standards) will cause the subagent to return empty/meaningless output.
71
+ - **Payload Limits:** `SKILL.md` entrypoints must be kept under 500 lines. Overflow logic/data must be referenced in external supporting files (e.g., `reference.md`) within the skill directory.
72
+ - **Extended Thinking:** To enable thinking mode for a specific skill, the exact string `"ultrathink"` must be present in the skill content.
@@ -0,0 +1,120 @@
1
+ # Agent Context Optimization Strategies (Codex)
2
+
3
+ This document defines practical patterns for minimizing instruction payload while preserving rule fidelity in Codex AGENTS.md-based workflows.
4
+
5
+ ## The Challenge: Instruction Bloat
6
+
7
+ Codex builds the instruction chain once at run start, then executes with that merged payload. In large monorepos, broad AGENTS files can create:
8
+
9
+ 1. Token waste from irrelevant domain rules.
10
+ 2. Lower instruction salience from high-density prompts.
11
+ 3. Hard truncation risk when `project_doc_max_bytes` is reached.
12
+
13
+ ## Codex Loading Model (Why Optimization Works)
14
+
15
+ From `references/codex/rules.md`, the important mechanics are:
16
+
17
+ - Discovery scope: global + project path from repo root to current working directory (CWD).
18
+ - Merge order: root to CWD (later files naturally override earlier ones).
19
+ - Directory ceiling: only one instruction file per directory (`AGENTS.override.md` > `AGENTS.md` > fallback names).
20
+ - Byte ceiling: concatenation stops when `project_doc_max_bytes` is hit (default `32768`).
21
+
22
+ These constraints make path and file placement the primary optimization levers.
23
+
24
+ ## Solution 1: CWD-Scoped Execution (Preferred)
25
+
26
+ Run Codex from the narrowest directory that matches the task.
27
+
28
+ ```bash
29
+ codex --cd packages/frontend "Implement the new settings panel."
30
+ codex --cd packages/backend "Add FastAPI pagination to list endpoint."
31
+ ```
32
+
33
+ Effect:
34
+
35
+ - Loads only global + root-to-target-directory instructions.
36
+ - Excludes unrelated sibling-domain instruction files by construction.
37
+
38
+ ## Solution 2: Hierarchical Rule Partitioning
39
+
40
+ Keep global instructions minimal and push domain rules down the tree.
41
+
42
+ Recommended layout:
43
+
44
+ ```txt
45
+ repo/
46
+ AGENTS.md # global: persona, communication, universal guardrails
47
+ packages/
48
+ frontend/
49
+ AGENTS.md # frontend-specific standards
50
+ backend/
51
+ AGENTS.md # backend-specific standards
52
+ data-pipeline/
53
+ AGENTS.md # data/ETL-specific standards
54
+ ```
55
+
56
+ Guidelines:
57
+
58
+ - Root AGENTS: only cross-cutting rules needed for every task.
59
+ - Subdirectory AGENTS: only rules needed inside that subtree.
60
+ - Avoid duplicating large shared blocks across multiple directories.
61
+
62
+ ## Solution 3: Budget-Aware Instruction Design
63
+
64
+ Treat `project_doc_max_bytes` as a strict budget, not a soft target.
65
+
66
+ Guidelines:
67
+
68
+ - Keep each AGENTS file concise and non-redundant.
69
+ - Move large reference content out of AGENTS into external docs.
70
+ - Keep AGENTS focused on executable constraints and decision rules.
71
+ - Raise `project_doc_max_bytes` only after sharding is exhausted.
72
+
73
+ ## Solution 4: Manual Lazy-Loading via Rule Registry (Fallback)
74
+
75
+ For heavy or cross-cutting guidance that cannot be cleanly path-scoped, keep only an index in AGENTS and require on-demand reads.
76
+
77
+ Example registry snippet for root `AGENTS.md`:
78
+
79
+ ```markdown
80
+ # Dynamic Rule Loading (Critical)
81
+
82
+ Do not guess architecture or style constraints.
83
+ Before editing code, read the relevant rule files from:
84
+ `packages/compiler/data/rules/*.yaml`
85
+
86
+ Mapping:
87
+
88
+ - Python/Backend: `python.yaml`, `fastapi.yaml`, `libs-backend-python.yaml`
89
+ - React/Frontend: `react-typescript.yaml`, `nextjs.yaml`, `shadcn-ui.yaml`
90
+ - Database: `sqlalchemy.yaml` or `prisma-postgresql.yaml`
91
+ - GraphQL: `graphql.yaml`, `nestjs-graphql.yaml`
92
+ ```
93
+
94
+ This preserves a small base context while still enforcing domain rules when needed.
95
+
96
+ ## Verification Loop
97
+
98
+ Use runtime checks to confirm active context and prevent hidden overloading:
99
+
100
+ ```bash
101
+ codex --ask-for-approval never "Summarize the current instructions."
102
+ codex --cd <dir> --ask-for-approval never "Show which instruction files are active."
103
+ ```
104
+
105
+ ## Decision Matrix
106
+
107
+ | Scenario | Recommended Strategy |
108
+ | ----------------------------------------- | -------------------- |
109
+ | Task is isolated to one package/subtree | Solution 1 + 2 |
110
+ | Rules map cleanly to directory boundaries | Solution 2 |
111
+ | AGENTS payload approaches byte cap | Solution 3 |
112
+ | Rules are cross-cutting and high-volume | Solution 4 |
113
+
114
+ ## Summary
115
+
116
+ - Do scope execution with `--cd` to minimize loaded instruction chain.
117
+ - Do keep root AGENTS minimal; move specialized rules to deeper directories.
118
+ - Do design for `project_doc_max_bytes` proactively.
119
+ - Do use a rule registry + on-demand reads for heavy guidance.
120
+ - Do not place large, domain-specific rule bodies in global AGENTS.