Skip to content

Repository files navigation

🔮 PhantomindAI

Universal AI Development Enhancement Layer

"You already pay for Copilot, Cursor, or Claude. PhantomindAI makes what you already have 10x more effective."

npm versionLicense: MITNode.js >=18TypeScriptMCP Compatible


What is PhantomindAI?

PhantomindAI solves the context amnesia problem: AI assistants forget everything about your project every session, every context switch, and every time a new team member onboards.

PhantomindAI provides:

  • Persistent context layer — one source of truth (SKILLS.md, RULES.md, schema.json) synced to every AI assistant automatically
  • Universal LLM abstraction — one API for Anthropic, OpenAI, Gemini, Groq, Mistral, Ollama, DeepSeek, and OpenRouter, with automatic fallback and budget routing
  • Agentic task execution — multi-role agent orchestration with human-in-the-loop checkpoints
  • AI output quality enforcement — secret scanning, hallucination detection, dual-model verification, consistency checking
  • MCP Server — expose project intelligence as a Model Context Protocol server for Cursor, Continue, Claude Code, and more
  • Full observability — cost tracking, audit trails, and analytics dashboard

Table of Contents


Installation

# Install globally (recommended — enables `phantomind` CLI)
npm install -g @phantomind/core
# Or install as a project dependency
npm install @phantomind/core
# Verify
phantomind --version

Requirements: Node.js ≥ 18


Quick Start

1. Initialize in your project

npx phantomind init

This creates:

.phantomind/
SKILLS.md ← Auto-learned project patterns
RULES.md ← AI behavior rules
schema.json ← Output contracts
config.yaml ← PhantomindAI configuration

2. Sync to your AI tools

npx phantomind sync

Generated adapter files (auto-updated, never edit directly):

.github/copilot-instructions.md ← GitHub Copilot
.cursorrules ← Cursor
.clinerules ← Cline
.continue/config.json ← Continue
.windsurfrules ← Windsurf
.zed/settings.json ← Zed
.aider.conf.yml ← Aider
.claude/CLAUDE.md ← Claude Code CLI
AGENTS.md ← OpenAI Codex CLI

3. Use the programmatic API (optional)

import{phantom}from'@phantomind/core';awaitphantom.init();// Complete with auto-routing across providersconstresponse=awaitphantom.complete('Refactor this function to use async/await');// Run an agentic taskconstresult=awaitphantom.agent('Add input validation to the user registration endpoint');// Semantic search across codebaseconstmatches=awaitphantom.search('authentication middleware');

CLI Reference

phantomind [command] [options]
CommandDescription
phantomind initInitialize PhantomindAI in the current project
phantomind learnScan codebase and regenerate learned project context
phantomind syncSync context to all configured AI assistant adapters
phantomind diffPreview adapter output diffs without writing files
phantomind contextPreview ranked context or search context sections
phantomind compareCompare generated adapter payloads
phantomind watchWatch project files and refresh context automatically
phantomind hooksInstall git hooks to keep context in sync
phantomind serveStart the MCP server (stdio or HTTP transport)
phantomind dashboardStart the observability dashboard server
phantomind evalTest and benchmark LLM provider connections
phantomind validate [files...]Scan code for secrets, hallucinations, and consistency issues
phantomind auditView cost reports and audit trail
phantomind dashboardStart the observability dashboard server
phantomind statsDisplay project context statistics
phantomind agent <task>Execute an agentic task from the CLI
phantomind schema [name]List or display schema definitions

phantomind init

phantomind init [options]
Options:
--provider <name> Optional LLM provider for agent/eval workflows
--adapters <list> Space-separated adapter list (e.g. copilot cursor cline)
--template <name> auto|default|node-library|node-cli|react-app|nextjs-app
--yes Skip interactive prompts

phantomind learn

phantomind learn [options]
Options:
--sync Run adapter sync after learning
--verbose Show detailed output

phantomind sync

phantomind sync [options]
Options:
--adapters <list> Only sync specific adapters
--dry-run Preview changes without writing files
--verbose Show per-file diff

phantomind diff

phantomind diff [options]
Options:
--adapters <list> Only diff specific adapters
--verbose Show full diff output

phantomind context

phantomind context [options]
Options:
--file <path> Rank context for a specific file
--search <query> Search across context sections
--max-tokens <n> Token budget for preview output
--json Emit raw JSON

phantomind compare

phantomind compare [options]
Options:
--adapters <list> Only compare specific adapters
--preview Show generated content preview

phantomind watch

phantomind watch [options]
Options:
--sync Run sync after each refresh

phantomind hooks

phantomind hooks [options]
Options:
--force Overwrite existing git hooks

phantomind dashboard

phantomind dashboard [options]
Options:
--port <n> Server port (default: 3101)
--host <host> Server host (default: 127.0.0.1)
--ui <path> Path to built dashboard assets
--cors Enable CORS forlocal development
--token <token> Require token for API access
--token-env <name> Env var containing dashboard token
--token-query <q> Optional query parameter name for token auth

phantomind validate

phantomind validate [files...] [options]
Options:
--no-secrets Skip secret scanning
--no-hallucinations Skip hallucination detection
--no-consistency Skip consistency checking
--fix Auto-fix detected secrets (redaction)

phantomind audit

phantomind audit [options]
Options:
--period <p> today|week|month|all (default: today)
--type <t> dashboard|costs|actions (default: dashboard)
--format <f> terminal|markdown|json

phantomind dashboard

phantomind dashboard [options]
Options:
--port <port> Server port (default: 3101)
--host <host> Server host (default: 127.0.0.1)
--ui <path> Path to built dashboard assets
--cors Enable CORS forlocal dev
--token <token> Require token for API access
--token-env <n> Env var containing API token (default: PHANTOMIND_DASHBOARD_TOKEN)
--token-query <n> Optional query param name for token

phantomind agent

phantomind agent <task> [options]
Options:
--role <role> architect|implementer|securityReviewer|testWriter|documenter
--orchestrate Use multi-role orchestration
--roles <list> Roles for orchestration (e.g. architect,implementer,testWriter)
--max-steps <n> Maximum agent steps (default: 30)

Configuration

PhantomindAI is configured via .phantomind/config.yaml:

# .phantomind/config.yamlproviders:
primary:
name: anthropicmodel: claude-opus-4-5apiKey: ${ANTHROPIC_API_KEY}fallback:
name: openaimodel: gpt-4oapiKey: ${OPENAI_API_KEY}budget:
name: groqmodel: llama-3.3-70b-versatileapiKey: ${GROQ_API_KEY}adapters:
- copilot
- cursor
- cline
- continuemcp:
enabled: trueport: 3333budget:
maxCostPerDay: 5.00warningAt: 0.80fallbackOnBudget: budgetagent:
maxSteps: 30memory:
enabled: truemaxEntries: 200quality:
secretScanning: truehallucinationDetection: truedualVerification: false

Environment Variables

VariableProvider
ANTHROPIC_API_KEYAnthropic (Claude)
OPENAI_API_KEYOpenAI (GPT)
GEMINI_API_KEYGoogle Gemini
GROQ_API_KEYGroq
MISTRAL_API_KEYMistral
DEEPSEEK_API_KEYDeepSeek
OPENROUTER_API_KEYOpenRouter

Provider-backed commands load .phantomind/.env when present. Core flows like init, learn, sync, diff, and context do not require API keys.

Dashboard UI

If you build the optional Angular dashboard package, PhantomindAI can serve both the API and the static UI:

npm run dashboard:build
phantomind dashboard

Without a built UI, phantomind dashboard still starts an API-only observability server.


Supported AI Assistants

AdapterFile GeneratedStatus
GitHub Copilot.github/copilot-instructions.md
Cursor.cursorrules
Cline.clinerules
Continue.continue/config.json
Windsurf.windsurfrules
Zed.zed/settings.json
Aider.aider.conf.yml
Claude Code.claude/CLAUDE.md
OpenAI CodexAGENTS.md

Supported LLM Providers

ProviderModelsNotes
Anthropicclaude-opus-4-5, claude-sonnet-4-5, claude-haiku-3-5Recommended primary
OpenAIgpt-4o, gpt-4o-mini, o3, o4-miniExcellent fallback
Google Geminigemini-2.0-flash, gemini-2.5-proBest for large context
Groqllama-3.3-70b, mixtral-8x7bBest budget option
Mistralmistral-large-latest, codestralStrong for code
Ollamaany local modelNo API key, fully local
DeepSeekdeepseek-chat, deepseek-reasonerCost-efficient
OpenRouter200+ modelsMeta-provider

Provider Routing

providers:
primary: # Highest quality — used by defaultname: anthropicmodel: claude-opus-4-5fallback: # Used if primary failsname: openaimodel: gpt-4obudget: # Used when daily cost threshold exceededname: groqmodel: llama-3.3-70b-versatilelocal: # Used for offline/sensitive tasksname: ollamamodel: llama3.2

Programmatic API

import{phantom}from'@phantomind/core';// Initialize (loads config, connects providers)awaitphantom.init();// Get project context (intelligent multi-layer Context)constctx=awaitphantom.ctx({maxTokens: 4000});// Complete with context injection and auto-routingconstresponse=awaitphantom.complete('Explain the auth module',{maxTokens: 1000,temperature: 0.3,});// Complete with intelligent retry on failureconstresult=awaitphantom.completeWithRetry('Implement JWT refresh logic');// Run an agentic task (single role)constagentResult=awaitphantom.agent('Refactor the payment service to use dependency injection',{role: 'implementer',maxSteps: 25,});// Multi-agent orchestrationconstorchestrated=awaitphantom.orchestrate('Build a rate limiting middleware',['architect','implementer','securityReviewer','testWriter'],);// Semantic search across codebaseconstmatches=awaitphantom.search('database connection pooling',5);// returns: Array<{ path, score, snippet }>// Sync adaptersawaitphantom.sync(['copilot','cursor'],/* dryRun */false);// Validate codeconst{ secrets, hallucinations }=awaitphantom.validate(code,'auth.ts');// Cost reportconstcosts=phantom.costs('today');// 'today' | 'week' | 'month' | 'all'// Analytics dashboardconstdashboard=phantom.dashboard();console.log(dashboard.formatTerminal());// Learn project patternsconstskills=awaitphantom.learn();// Save stateawaitphantom.save();

MCP Server

PhantomindAI exposes a Model Context Protocol server providing 9 tools to any MCP-compatible AI assistant:

phantomind serve

MCP Tools

ToolDescription
get_project_contextFull project context (skills, rules, schema)
search_codebaseSemantic search across indexed files
validate_codeSecret + hallucination scan
get_schemaRetrieve a named JSON/Zod schema
list_schemasList all registered schemas
completeLLM completion via provider router
run_agentExecute an agentic task
get_cost_reportCurrent cost breakdown
get_audit_logRecent audit entries

MCP Configuration (Claude Desktop / Continue)

{
"mcpServers": {
"phantomind": {
"command": "npx",
"args": ["phantomind", "serve"],
"cwd": "/path/to/your/project"
}
}
}

Agent System

Roles

RoleSpecialization
architectSystem design, architecture decisions, dependency planning
implementerFeature implementation, code generation, refactoring
securityReviewerVulnerability scanning, threat modeling, secure coding
testWriterUnit tests, integration tests, edge cases, mocks
documenterAPI docs, README, inline comments, changelogs

Single-Agent Execution

phantomind agent "Add rate limiting to the API" --role implementer --max-steps 20

Multi-Agent Orchestration

phantomind agent "Build OAuth2 integration" --orchestrate \
--roles architect,implementer,securityReviewer,testWriter

Orchestration phases run sequentially with output aggregation between phases.

Task Queue (Programmatic)

import{phantom}from'@phantomind/core';awaitphantom.init();// Enqueue tasksphantom.enqueue('Refactor database layer',{role: 'implementer',priority: 'high'});phantom.enqueue('Write migration tests',{role: 'testWriter',priority: 'normal'});

Quality Layer

Secret Scanning

Detects and redacts API keys, tokens, passwords, and credentials:

phantomind validate src/ --secrets

Detects: AWS keys, GitHub tokens, Stripe keys, OpenAI keys, JWT secrets, PEM certificates, database connection strings, and 20+ other patterns.

Hallucination Detection

Checks AI-generated code for:

  • import statements referencing non-existent packages
  • References to files that don't exist in the project
  • Usage of type names not defined in the codebase

Consistency Checking

Identifies inconsistencies across the codebase:

  • Naming convention violations (camelCase vs snake_case drift)
  • Mixed async patterns (callbacks vs promises vs async/await)
  • Architectural boundary violations

Dual-Model Verification

For critical outputs, a second model independently verifies correctness before acceptance.


Observability

Cost Tracking

phantomind audit --type costs --period week

Tracks cost per provider, per model, per day with budget alerts.

Audit Trail

All agent actions are logged to .phantomind/audit/audit.jsonl:

phantomind audit --type actions

Analytics Dashboard

phantomind audit --type dashboard

Displays: request count, total cost, success rate, response time, quality events, agent task completion.


Architecture

packages/core/src/
├── types.ts ← All shared TypeScript interfaces
├── index.ts ← PhantomMind class + phantom singleton
│
├── config/ ← Config loading (cosmiconfig, .env, deep-merge)
├── providers/ ← LLM provider abstractions + router
│ ├── anthropic.ts
│ ├── openai.ts
│ ├── gemini.ts
│ ├── groq.ts
│ ├── mistral.ts
│ ├── ollama.ts
│ ├── deepseek.ts
│ ├── openrouter.ts
│ └── router.ts ← Budget routing + fallback + EventEmitter
│
├── context/ ← Project context management
│ ├── engine.ts ← Context orchestration
│ ├── embedder.ts ← TF-IDF codebase indexer + semantic search
│ ├── learner.ts ← Pattern learning → SKILLS.md generation
│ └── versioning.ts ← SHA-256 change tracking
│
├── adapters/ ← AI assistant adapter sync
│ ├── base.ts
│ ├── copilot.ts, cursor.ts, cline.ts, continue.ts
│ ├── windsurf.ts, zed.ts, aider.ts, claude-code.ts, codex.ts
│ └── index.ts ← syncAllAdapters()
│
├── mcp/ ← MCP Server (9 tools)
│ └── server.ts
│
├── agent/ ← Agentic execution engine
│ ├── executor.ts ← Single-agent loop (plan→act→verify)
│ ├── orchestrator.ts ← Multi-agent orchestration
│ ├── decomposer.ts ← Task decomposition (4 phases)
│ ├── roles.ts ← Role system prompts
│ ├── memory.ts ← Cross-session persistent memory
│ ├── retry.ts ← 5 retry strategies
│ ├── queue.ts ← Priority queue + cron scheduler
│ └── index.ts
│
├── quality/ ← Output quality enforcement
│ ├── secret-scanner.ts
│ ├── hallucination-guard.ts
│ ├── consistency.ts
│ ├── dual-verifier.ts
│ ├── regression.ts
│ └── anomaly.ts
│
├── schemas/ ← Schema registry (Zod + JSON Schema)
│ ├── registry.ts
│ └── index.ts ← 7 prebuilt schemas
│
├── templates/ ← SKILLS.md + RULES.md templates
│ ├── SKILLS.template.md
│ ├── RULES.template.md
│ └── engine.ts
│
├── observability/ ← Audit, cost, dashboard
│ ├── audit.ts
│ ├── cost-tracker.ts
│ └── dashboard.ts
│
└── cli/ ← CLI commands (Commander.js)
├── main.ts
├── init.ts, sync.ts, serve.ts, eval.ts
├── validate.ts, audit.ts, stats.ts, agent.ts
└── index.ts

Development

Prerequisites

  • Node.js ≥ 18
  • npm ≥ 9

Setup

git clone https://github.com/your-username/PhantomindAI
cd PhantomindAI
npm install

Commands

# Build TypeScript
make build
# Watch mode (rebuild on changes)
make dev
# Run CLI locally (without building)
make run CMD="init"# Run tests
make test# Clean build artifacts
make clean
# Full rebuild
make rebuild
# Check types without emitting
make typecheck

Project Structure

PhantomindAI/
├── packages/
│ └── core/ ← @phantomind/core package
│ ├── src/
│ ├── dist/ ← Built output (gitignored)
│ ├── package.json
│ └── tsconfig.json
├── docs/
│ └── PhantomMindAI_PRD.md
├── package.json ← Monorepo root
├── tsconfig.json
├── Makefile
└── README.md

Tutorial Lengkap

Panduan komprehensif langkah demi langkah tersedia di docs/TUTORIAL.md, mencakup:

#Topik
1Persiapan & Instalasi
2Inisialisasi Project Pertama
3Memahami Struktur File
4Konfigurasi Provider LLM
5Sync ke AI Assistant
6Menggunakan CLI
7Penggunaan Programmatic API
8Sistem Agent
9MCP Server
10Quality Validation
11Observability & Cost Tracking
12Schema Registry
13Workflow Tim
14Tips & Trik
15Troubleshooting

Roadmap

VersionFeatures
v0.1Context sync, adapter generation, CLI init/sync
v0.2Provider router, budget management, MCP server
v0.3Agent executor, orchestrator, task queue
v0.4Quality layer (secrets, hallucinations, consistency)
v0.5Observability (audit, costs, dashboard)
v1.0Schema registry, templates, stable API
v1.xVS Code extension, Git hooks, CI/CD integration

License

MIT © Synaptode

About

No description, website, or topics provided.

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages