npm package: @ivannikov-pro/ai-context-surgeon
Description: AI-native Knowledge API for surgical monorepo restructuring — roles, strategies, prompts, and analysis tools accessible on-demand
Author: Aleksandr Ivannikov
Latest version: 1.0.4

<!-- FNH: Project — ai-context-surgeon AI-native Knowledge API | SECTIONS: Quick Start, For AI Agents, Catalog, CLI, Tools, Roles, Prompts, Workflows, Strategy, Source Structure | DEPS: none -->

# ai-context-surgeon

[![npm version](https://img.shields.io/npm/v/@ivannikov-pro/ai-context-surgeon.svg)](https://www.npmjs.com/package/@ivannikov-pro/ai-context-surgeon)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

> Toolkit: ai-context-surgeon — an AI-native Knowledge API for autonomous agents doing surgical monorepo restructuring. Roles, strategies, prompts, skills, templates, and analysis tools — all accessible on-demand via CLI. No install required. | SECTIONS: Quick Start, For AI Agents, Catalog, CLI, Tools, Roles, Prompts, Workflows, Strategy, Source Structure | DEPS: none

**ai-context-surgeon** is a Knowledge API, not a traditional CLI tool. It provides on-demand access to roles, strategies, prompts, skills, templates, and analysis tools — everything an AI agent needs to optimize a monorepo's context for minimal token consumption.

---

## 🚀 Quick Start

```bash
# Browse everything available
npx -y @ivannikov-pro/ai-context-surgeon@latest catalog

# Run repo analysis
npx -y @ivannikov-pro/ai-context-surgeon@latest radar

# Get a role prompt for the AI agent to follow
npx -y @ivannikov-pro/ai-context-surgeon@latest role scout

# Get condensed task instructions (~60 tokens instead of ~2800)
npx -y @ivannikov-pro/ai-context-surgeon@latest prompt fnh

# Lightweight project setup
npx -y @ivannikov-pro/ai-context-surgeon@latest init
```

---

## 🤖 For AI Agents

The npm package IS the knowledge base. The CLI IS the API.
No files to copy. No install to maintain. Always the latest version.

```bash
# Step 1: Discover everything available
npx @ivannikov-pro/ai-context-surgeon@latest catalog

# Step 2: Read a role prompt and follow its instructions
npx @ivannikov-pro/ai-context-surgeon@latest role scout

# Step 3: Run analysis tools
npx @ivannikov-pro/ai-context-surgeon@latest radar
npx @ivannikov-pro/ai-context-surgeon@latest context-weight

# Step 4: Get specific instructions for a task (saves 95% tokens)
npx @ivannikov-pro/ai-context-surgeon@latest prompt fnh       # How to create FNH headers
npx @ivannikov-pro/ai-context-surgeon@latest prompt jsdoc     # How to write JSDoc
npx @ivannikov-pro/ai-context-surgeon@latest prompt god-file  # How to split large files
npx @ivannikov-pro/ai-context-surgeon@latest prompt readme    # How to write package READMEs
npx @ivannikov-pro/ai-context-surgeon@latest prompt agent-rules        # How to write AGENTS.md
npx @ivannikov-pro/ai-context-surgeon@latest prompt context-exclusion  # How to set up .antigravityignore

# Step 5: Read strategy docs when needed (full reference)
npx @ivannikov-pro/ai-context-surgeon@latest strategy fnh
npx @ivannikov-pro/ai-context-surgeon@latest strategy monorepo

# Step 6: Delegate — output a role prompt and send to another agent
npx @ivannikov-pro/ai-context-surgeon@latest role architect --output .agents/architect-prompt.md
```

---

## 📈 Token Savings: Before / After

```text
╔═══════════════════════════════════════════════════════════════╗
║  LEVEL 1: Blind Navigation (No rules)                         ║
║  Agent reads 10 files ~3,300 lines            ≈  8,000 tokens ║
╠═══════════════════════════════════════════════════════════════╣
║  LEVEL 2: Traditional Docs (Reading markdown files)           ║
║  Agent reads strategy doc ~560 lines          ≈  2,800 tokens ║
╠═══════════════════════════════════════════════════════════════╣
║  LEVEL 3: ai-context-surgeon (Knowledge API)                  ║
║  Agent calls `prompt fnh`                     ≈     60 tokens ║
╠═══════════════════════════════════════════════════════════════╣
║  SAVINGS: 99.3%  (from 8,000 → 60 tokens per task)            ║
╚═══════════════════════════════════════════════════════════════╝
```

| Scenario | Tokens | Method |
| --- | ---: | --- |
| Blind repo navigation | ~8,000 | Agent reads random files |
| Traditional Markdown Docs | ~2,800 | Agent reads `strategy/file-navigation-header.md` |
| **Knowledge API** | **~60** | Agent calls `prompt fnh` |

**JSDoc annotation example:**

```typescript
// BEFORE (220 tokens of noise):
/**
 * @fileoverview User Service
 * @author Jane Developer
 * @since 2024-03-15
 */
export class UserService {
  /** @param {CreateUserInput} input @returns {Promise<User>} */
  async create(input: CreateUserInput): Promise<User> { ... }
}

// AFTER (40 tokens — 82% reduction):
/** Service: UserService — CRUD + auth | deps: prisma, bcrypt */
export class UserService {
  /** @throws Conflict(email) | hashes pw bcrypt 12 | sends welcome email */
  async create(input: CreateUserInput): Promise<User> { ... }
}
```

---

## 📋 Catalog

```bash
npx @ivannikov-pro/ai-context-surgeon@latest catalog
```

| Category | Command | Count | Description |
| --- | --- | ---: | --- |
| 🔧 Tools | `radar`, `godfiles`, `circular`, `context-weight`, `sourcemaps` | 5 | Run analysis directly against any repo |
| 🎭 Roles | `role <name>` | 6 | Agent role prompts (scout → inspector) |
| 📖 Strategies | `strategy <name>` | 7 | Full reference docs (FNH, monorepo, JSDoc, ...) |
| 💡 Prompts | `prompt <task>` | 6 | Condensed task instructions (~60 tokens each) |
| 🧩 Skills | `skill <name>` | 2 | Reusable agent procedures |
| 📝 Templates | `template <name>` | 9 | File seeds (AGENTS.md, README, package.json, ...) |
| 📋 Checklists | `checklist <n>` | 5 | Phase task lists (1–5) |
| 🧠 Knowledge | `knowledge <name>` | 3 | Reference knowledge items |

---

## 🖥️ CLI Commands

### Content Access

| Command | Description |
| --- | --- |
| `catalog` | List all available content across all categories |
| `role <name>` | Output an agent role prompt |
| `strategy <name>` | Output a strategy document |
| `prompt <task>` | Output a condensed task prompt |
| `skill <name>` | Output a skill procedure |
| `template <name>` | Output a file template |
| `checklist <n>` | Output a phase checklist (1–5) |
| `knowledge <name>` | Output a knowledge item |

All content commands support `--output <path>` to save to a file:
```bash
npx @ivannikov-pro/ai-context-surgeon@latest role scout --output .agents/scout.md
npx @ivannikov-pro/ai-context-surgeon@latest checklist 1 --output .agents/phase-1.md
```

### Tool Execution

| Command | Script | Description |
| --- | --- | --- |
| `radar` | `scan-fnh.sh` | Semantic FNH map of any repository |
| `godfiles` | `detect-god-files.sh` | Find files exceeding LOC thresholds |
| `circular` | `detect-circular-deps.sh` | Detect circular dependencies |
| `context-weight` | `validate-context-weight.sh` | Identify files with high cognitive load (LOC + Fan-out) |
| `sourcemaps` | `generate-source-map.sh` | Generate AI-friendly structure trees |

### Project Setup

| Command | Description |
| --- | --- |
| `init` | Creates `AGENTS.md`, `.antigravityignore`, and injects CI scripts into `package.json` |

After `init`, these CI gates are available in `package.json`:
```bash
npm run check:hygiene     # FNH radar scan
npm run check:god-files   # God file detection
```

---

## 💡 Prompt Library

Available via `prompt <task>` — each prompt is ~60 tokens vs ~2800 for the full strategy doc.

| Key | Name | Description |
| --- | --- | --- |
| `fnh` | File Navigation Header | How to create FNH headers for any file type (all 5 mandatory layers) |
| `jsdoc` | JSDoc Annotation | How to write AI-optimized JSDoc (what to annotate, what to skip) |
| `readme` | Package README | How to write a README with Source Structure for AI agents |
| `agent-rules` | AGENTS.md | How to write an AGENTS.md for any repository |
| `context-exclusion` | Context Exclusion | How to configure `.antigravityignore` / `.aiignore` |
| `god-file` | God File Splitting | How to split files >300 lines into focused modules |

**Examples:**
```bash
npx @ivannikov-pro/ai-context-surgeon@latest prompt fnh
npx @ivannikov-pro/ai-context-surgeon@latest prompt god-file
npx @ivannikov-pro/ai-context-surgeon@latest prompt jsdoc --output /tmp/jsdoc-task.md
```

---

## 🎭 Agent Roles

6 specialized roles for the 5-phase optimization pipeline:

| Role | Phase | Description | Model | Mode |
| --- | --- | --- | --- | --- |
| **Scout** | 1 — Analysis | Context reconnaissance, FNH radar, telemetry gathering | Gemini 3 Flash | Fast |
| **Architect** | 2 — Planning | Design decisions, refactoring plan, package boundaries | Claude Opus 4.6 / Gemini 3.1 Pro | Planning |
| **Surgeon** | 3 — Restructuring | Surgical code splitting, import fixing, god-file extraction | Gemini 3.1 Pro (High) | Fast |
| **Librarian** | 4a — Documentation | FNH headers, JSDoc, package READMEs, Source Structure | Claude Sonnet 4.6 | Planning |
| **Tuner** | 4b — Configuration | AGENTS.md, `.antigravityignore`, package.json, CI scripts | Claude Opus 4.6 | Planning |
| **Inspector** | 5 — Validation | Scoring, health checks, before/after comparison, sign-off | Gemini 3.1 Pro (High) | Planning |

```bash
# Load a role into the current agent
npx @ivannikov-pro/ai-context-surgeon@latest role scout

# Full pipeline delegation
npx @ivannikov-pro/ai-context-surgeon@latest role scout    # → reconnaissance
npx @ivannikov-pro/ai-context-surgeon@latest role architect  # → plan
npx @ivannikov-pro/ai-context-surgeon@latest role surgeon    # → execute
npx @ivannikov-pro/ai-context-surgeon@latest role librarian  # → document
npx @ivannikov-pro/ai-context-surgeon@latest role tuner      # → configure
npx @ivannikov-pro/ai-context-surgeon@latest role inspector  # → validate
```

---

## 🔧 Analysis Tools

All 16 shell scripts in `tools/` plus one Node.js enrichment tool:

| Tool | CLI Command | Description |
| --- | --- | --- |
| `scan-fnh.sh` | `radar` | Extract FNH headers from all files — semantic repo map |
| `detect-god-files.sh` | `godfiles` | Flag files exceeding LOC thresholds (default >300) |
| `detect-circular-deps.sh` | `circular` | Find circular import chains between packages |
| `validate-context-weight.sh` | `context-weight` | Compute cognitive load (LOC + Fan-out × 20 formula) |
| `generate-source-map.sh` | `sourcemaps` | Build Source Structure block for README |
| `analyze-structure.sh` | — | Full monorepo structure metrics and overview |
| `analyze-package-json.sh` | — | Rate package.json AI-readiness (Tier 1–4 scoring) |
| `audit-jsdoc.sh` | — | Analyze JSDoc coverage and quality |
| `check-fnh-freshness.sh` | — | Warn when source changed but FNH header wasn't updated |
| `lint-imports.sh` | — | Detect cross-package boundary violations |
| `measure-context-cost.sh` | — | Estimate AI agent context cost for a package |
| `generate-jsdoc-headers.sh` | — | Add JSDoc navigation headers to source files |
| `enforce-god-files.sh` | — | CI gate — fail build if files exceed line thresholds |
| `validate-context-hygiene.sh` | — | CI gate — ensure all packages have README and ignores |
| `validate-naming.sh` | — | Check kebab-case and naming conventions |
| `enrich-package-json.js` | — | Lean/Enrich workflow — inject publish metadata before `npm publish` |

---

## 🔄 Full-Pipeline Workflow Summary

| Phase | Role | Checklist | Tools Used | Output |
| --- | --- | --- | --- | --- |
| 1 — Analysis | Scout | `checklist 1` | `radar`, `godfiles`, `context-weight`, `circular` | Telemetry report |
| 2 — Planning | Architect | `checklist 2` | `analyze-structure.sh`, `analyze-package-json.sh` | Refactoring plan |
| 3 — Restructuring | Surgeon | `checklist 3` | `lint-imports.sh`, `check-fnh-freshness.sh` | Split files, fixed imports |
| 4a — Documentation | Librarian | `checklist 4` | `audit-jsdoc.sh`, `generate-jsdoc-headers.sh` | FNH headers, JSDoc, READMEs |
| 4b — Configuration | Tuner | `checklist 4` | `validate-naming.sh`, `validate-context-hygiene.sh` | AGENTS.md, CI scripts |
| 5 — Validation | Inspector | `checklist 5` | `radar`, `context-weight`, `enforce-god-files.sh` | Score report, sign-off |

Invoke the full pipeline via workflow:
```bash
# Analyzes a target repo (requires target path argument)
npx @ivannikov-pro/ai-context-surgeon@latest # → interactive menu
```

Or use pre-built agent workflows (defined in `.agents/workflows/`):
- `/analyze-repo` — Quick analysis using Scout + tools
- `/apply-surgeon` — Step-by-step execution pipeline to overhaul the current codebase
- `/full-pipeline` — Complete 5-phase cascade guide
- `/self-check` — Validate ai-context-surgeon's own integrity

---

## 📖 Strategy Docs

All accessible via `strategy <key>` — read on-demand, no install:

| Key | Document | Size | Description |
| --- | --- | --- | --- |
| `fnh` | File Navigation Headers | ~560 lines | Universal header format for every file type |
| `monorepo` | Monorepo Strategy | ~700 lines | Architectural patterns and package boundaries |
| `jsdoc` | JSDoc Guide | ~600 lines | Token-efficient annotation standards |
| `package-json` | package.json Guide | ~540 lines | Tier 1–4 field priority, Lean+Enrich workflow |
| `context-exclusion` | Context Exclusion | ~200 lines | .antigravityignore patterns and philosophy |
| `bash` | Bash Guide | ~180 lines | Writing POSIX scripts for AI agents |
| `context-weight` | Context Weight Theory | ~120 lines | LOC + Fan-out cognitive load formula |

---

## 🧩 Skills

Reusable agent procedures — a skill is a self-contained, step-by-step instruction set:

| Key | Name | Description |
| --- | --- | --- |
| `annotate-jsdoc` | Annotate JSDoc | Reusable JSDoc/FNH injection procedure |
| `prompt-engineering` | Prompt Engineering | Prompt analysis, amplification, and extraction |

```bash
npx @ivannikov-pro/ai-context-surgeon@latest skill annotate-jsdoc
```

---

## 📝 Templates

File seeds for new projects — all use `{{UPPER_SNAKE_CASE}}` placeholders:

| Key | Template | Description |
| --- | --- | --- |
| `agents` | `AGENTS.md.template` | Agent rules with Navigation Rules, FNH, ai-context-surgeon Quick Reference |
| `readme` | `package-readme.template` | Package README with Source Structure and Scripts |
| `package-json` | `package-json-ideal.template` | Lean package.json (Tier 1 order, ≤30 lines) |
| `workflow` | `workflow.template` | Executable workflow with `// turbo` annotations |
| `skill` | `skill.template` | Skill definition with When/When-Not/Steps/Verify |
| `knowledge` | `knowledge-item.template` | Knowledge item (metadata.json + artifacts/) |
| `publish-meta` | `publish-meta.template` | Publish metadata for Lean+Enrich workflow |
| `antigravityignore` | `antigravityignore.template` | Context exclusion rules |
| `cursorrules` | `cursorrules.template` | Cursor / Windsurf IDE agent rules |

```bash
npx @ivannikov-pro/ai-context-surgeon@latest template agents
npx @ivannikov-pro/ai-context-surgeon@latest template agents --output AGENTS.md
```

---

## 🧠 Knowledge Items

Pre-loaded reference knowledge for agents:

| Key | Name | Description |
| --- | --- | --- |
| `agent-context` | Agent Context System | How Knowledge/Skills/Workflows work in AI agents |
| `vulnerabilities` | Agent Vulnerabilities | AI agent vulnerability patterns and bypass techniques |
| `power-words` | Power Words Dictionary | Enforcement directive vocabulary for AI prompts |

```bash
npx @ivannikov-pro/ai-context-surgeon@latest knowledge agent-context
```

---

## 📂 Source Structure

See [STRUCTURE.md](STRUCTURE.md) for the complete verbose file and directory map.

---

## 🛡️ CI/CD Integration

After `init`, inject these gates into your CI pipeline:

```bash
npm run check:hygiene     # FNH radar scan — verifies all files have headers
npm run check:god-files   # God file detection — fails if any file exceeds 300 LOC
```

Or run tools directly against any target repo:
```bash
npx @ivannikov-pro/ai-context-surgeon@latest radar /path/to/repo
npx @ivannikov-pro/ai-context-surgeon@latest godfiles /path/to/repo
```

---

_ai-context-surgeon | [MIT](LICENSE) | [npm](https://www.npmjs.com/package/@ivannikov-pro/ai-context-surgeon) | [GitHub](https://github.com/ivannikov-pro/ai-context-surgeon)_