Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

18 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

ai-context-surgeon

npm version License: 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

# 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.

# 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

╔═══════════════════════════════════════════════════════════════╗
β•‘  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:

// 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

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:

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:

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:

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
# 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:

# 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
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
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
npx @ivannikov-pro/ai-context-surgeon@latest knowledge agent-context

πŸ“‚ Source Structure

See STRUCTURE.md for the complete verbose file and directory map.


πŸ›‘οΈ CI/CD Integration

After init, inject these gates into your CI pipeline:

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:

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 | npm | GitHub

About

Surgical monorepo restructuring for minimal AI agent context consumption

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages