Логотип Graphenium

Graphenium

Сообщество
lambda-alpha-labs

Local pre-flight linter and architecture gate for AI agents. Uses tree-sitter, Stack Graphs, and Datalog to mechanically block structural drift, layering bypasses, and scope creep on virtual ASTs before code changes land.

Издательlambda-alpha-labs
РепозиторийGraphenium
ЯзыкRust
Форки
4
Звёзды
25
Доступные инструменты
0
Тип транспортаstdio
Категории
ЛицензияMIT
Ссылки
  • Подключайте инструменты к рабочим процессам с ИИ

    Graphenium предоставляет возможности MCP, доступные совместимым ИИ-клиентам и агентам.

  • Доступные инструменты: 0

    Ниже представлены доступные для вызова действия с названиями и описаниями, если сервер их предоставляет.

  • Готовая конфигурация для копирования

    Используйте примеры конфигурации, чтобы настроить этот сервер в предпочитаемом MCP-клиенте.

  • Показатели интереса к открытому проекту

    Звёзды: 25, форки: 4 — в связанном репозитории.

Graphenium is a local, pre-flight linter and external architecture gate for AI coding agents.

It enforces structural compliance on AI assistants (such as Claude Code, Cursor, Aider, and Grok) by mechanically blocking code changes that violate your module boundaries, bypass your service layers, or introduce architectural drift.

Standard developer tools help agents find files. Graphenium prevents agents from creating architectural debt.

text
Without Graphenium (Vibe-Coding)        With Graphenium (Containment)
--------------------------------        -----------------------------
Agent edits files blindly               Agent validates design pre-flight
Agent ignores architectural layers      Graphenium blocks direct boundary violations
Constraints decay in long chats         External Datalog engine enforces strict rules
Reviewer hunts for bypassed layers      Reviewer gets deterministic scope-creep audits
CI checks only test passing             CI fails on architectural drift

Binary: gm
Schema: 0.2.0
Status: AST + Stack Graphs resolver stable, pre-flight policy engine stable, zero-drift delta gating stable, telemetry overlay experimental


Why Graphenium Exists: The Containment Gap

AI coding agents are highly efficient at local edits, but they suffer from structural blindness and context decay. Over a long chat session, an agent will lose track of your system instructions and optimize for the path of least resistance (e.g., writing a raw database call inside an HTTP controller to make a local test pass).

Relying on "soft" guardrails like CLAUDE.md or system prompts to maintain design patterns does not work. When context windows get full, these constraints are dropped.

Graphenium establishes external engineering governance. It operates outside the LLM context, treating architectural boundaries as a strict, compiled contract.


The Core Technical Lifecycle: Design-then-Verify

Graphenium enforces an explicit three-step compiler loop on the agent:

  1. Declare Intent (Pre-Flight Spec): Before editing any code, the agent registers its planned changes (classes, methods, and dependencies) in a virtual planning workspace.
  2. Transitive Policy Solving: Graphenium's engine runs a local Datalog solver to analyze the proposed virtual AST. If the design bypasses an intermediary architectural layer or uses banned symbols, Graphenium blocks the plan and provides structural feedback.
  3. Zero-Drift Delta Gating: Even without a .graphenium/policy.json file, Graphenium applies in-memory modularity analysis (ΔQ) and surprise edge profiling to reject plans that mathematically degrade community structure.
  4. Post-Facto Compliance Audit: After the agent writes the code, Graphenium parses the physical modifications, ensuring that the agent did not touch files outside the declared scope, introduce unplanned dependencies, or fail to implement its declared spec.

Quick Start

sh
# 1. Initialize workspace
# Generates .grapheniumignore with standard project defaults
gm init

# 2. Build local AST and Stack Graphs index (No LLM keys required)
gm run . --no-semantic --no-viz

# 3. Diagnose codebase health and import resolution
gm doctor --graph graphenium-out/graph.json --resolution

# 4. Analyze structural neighborhoods
gm query "authentication flow" --budget 2000

# 5. Start the MCP server for AI coding agents
gm serve --graph graphenium-out/graph.json --watch

Installation

sh
# From a local checkout
cargo install --locked --path .

# Or use the platform installer
curl -fsSL https://raw.githubusercontent.com/lambda-alpha-labs/Graphenium/main/install.sh | sh

Requires Rust 1.81 or later. Tree-sitter language grammars are compiled and bundled.


Core Technical Capabilities

1. AST-Proven Provenance (Facts vs. Heuristics)

Most AI developer tools use LLMs to guess how modules depend on each other, leading to hallucinations. Graphenium establishes an index of compiler-proven truth using Tree-sitter and Stack Graphs. Every relationship carries explicit provenance:

  • EXTRACTED (AST-Proven): Compiler-backed facts (imports, type inheritance, explicit call signatures).
  • INFERRED (Heuristics): Semantic leads that the agent is forced to verify.
  • AMBIGUOUS (Collisions): Identifier collisions that force the agent to halt and inspect source files directly.

2. Datalog-Powered Policy Solving

Static linters can check direct imports, but they are blind to multi-hop architectural bypasses. Graphenium solves this by compiling your codebase structure into logical facts and running an embedded Datalog inference engine (src/analyze/query.rs & stdlib.dl).

It uses first-order logic and fixed-point iteration to mathematically prove boundary violations over an infinite number of dependency hops.

3. Zero-Drift Delta Gating (Topological Entropy Guardrails)

Even without explicit policy rules, Graphenium applies in-memory modularity analysis to every planning workspace. The delta engine compares physical-only and virtual (plan-overlay) subgraphs, computing Louvain modularity deltas (ΔQ) and profiling surprise edges. Plans that degrade community structure or introduce architectural shortcuts (cross-community, peripheral→hub) are rejected automatically.

Available via evaluate_delta_gate (MCP), validate_plan (orchestrator), and gm check --delta --plan <id> (CLI).

4. Declarative Structural Governance

Enforce system design boundaries at commit-time or in CI. You declare rules in .graphenium/policy.json at the root of your repository:

json
{
  "rules": [
    {
      "type": "forbidden_dependency",
      "from_pattern": "src/controllers/**",
      "to_pattern": "src/db/**",
      "reason": "Controllers must use services, not access DB directly"
    },
    {
      "type": "strict_layering",
      "layers": [
        "src/serve/**",
        "src/analyze/**",
        "src/extract/**",
        "src/model/**"
      ],
      "reason": "Respect tiered architecture: serve -> analyze -> extract -> model"
    }
  ]
}

Use gm check --plan <id> --strict to run pre-flight policy checks and post-facto compliance audits in CI.

sh
# Topological delta gate (zero-config modularity protection)
gm check --delta --plan <id>

Technical Safeguards: Friction & Loop Mitigations

Traditional static analysis tools and natural-language guardrails (like CLAUDE.md or system prompts) fail when context windows fill up, leading to agent "vibe-coding" and rapid token consumption. Graphenium implements three structural safeguards to prevent developer friction and agent deadlock:

1. Mitigating the "Agent Deadlock" Loop (Pre-Flight Virtual ASTs)

  • The Friction: If an agent is blocked by a strict linter, it can fall into a token-wasting trial-and-error cycle (Propose → Blocked → Tweak → Blocked).
  • Graphenium's Mechanism: Graphenium prevents this loop by isolating change evaluations to a virtual planning workspace (create_planning_workspace). The agent registers its intent — classes, methods, and imports — before editing any physical files. Graphenium's pre-flight solver evaluates this virtual AST in milliseconds.
  • If a violation is found, the agent does not receive a vague natural-language rejection. It receives structured, compiler-proven topological path violations (e.g., demonstrating the exact transitively bypassed service layers). This allows the agent to correctly refactor its design plan in memory before wasting LLM tokens on physical file rewrites.

2. Solving "Policy Rot" (Zero-Config Topological Delta Gating)

  • The Friction: Declaring and maintaining strict architectural rules in a static JSON file (policy.json) introduces manual configuration overhead that fast-moving teams often neglect.
  • Graphenium's Mechanism: If no .graphenium/policy.json file is present in the repository, Graphenium dynamically falls back to Zero-Drift Delta Gating (gm check --delta). Instead of relying on static directory regexes, Graphenium uses its native Louvain community-detection engine to evaluate your codebase's current structural cohesion.
  • When an agent proposes a virtual plan, Graphenium calculates the modularity delta (ΔQ) and surprise coupling score of the new edges. It gracefully accepts your existing legacy complexity as the baseline, but mechanically blocks the agent from introducing new topological decay. No configuration files are required to protect your system's modularity.

3. Resolving Agent Integration Friction (Direct Skill-Folder Injection)

  • The Friction: Standard stateless MCP setups mean agents can easily bypass sequential "three-step" design loops (Declare → Solve → Post-audit), requiring manual developer mediation.
  • Graphenium's Mechanism: Graphenium circumvents this integration barrier by programmatically injecting its behavioral rules directly into the agentic runtime. During installation (install.sh or install.ps1), Graphenium copies its standard system skill instruction set (skills/graphenium/SKILL.md) directly into Claude Code's native skill directory (~/.claude/skills/graphenium/SKILL.md).
  • This ensures that the moment the assistant handshakes with Graphenium, it ingests explicit, structured operating parameters on how to manage virtual workspaces and resolve topological violations, without requiring the developer to configure system prompts manually.

Language Support

Graphenium supports mixed repositories with Rust, Python, Go, JavaScript, TypeScript, Java, C, C++, and C#.

C# projects receive build-boundary awareness through .sln and .csproj parsing, enabling Graphenium to model assemblies, namespaces, and project references as structural boundaries.


MCP Setup

Integrate Graphenium directly into your agent's execution loop. For tools that spawn MCP from the project directory, use the scripts/graphenium-mcp launcher (rebuilds only when the index is missing, keeping startup instantaneous).

sh
install -m 755 scripts/graphenium-mcp ~/.local/bin/graphenium-mcp

Claude Code

sh
claude mcp add graphenium --scope user -- gm serve --graph /path/to/graphenium-out/graph.json --watch

Grok

Configure in ~/.grok/config.toml:

toml
[mcp_servers.graphenium]
command = "/Users/<you>/.local/bin/graphenium-mcp"
args = []
enabled = true

Cursor

Add to ~/.cursor/mcp.json:

json
{
  "mcpServers": {
    "graphenium": {
      "command": "gm",
      "args": ["serve", "--graph", "/path/to/graphenium-out/graph.json", "--watch"]
    }
  }
}

Detailed Documentation Map

Root

DocumentPurpose
AI_SETUP.mdStep-by-step assistant setup playbook.
CONTRIBUTING.mdContributor guidelines and module reference.
CHANGELOG.mdRelease history and milestone summary.
SECURITY.mdLocal-first security guarantees and vulnerability reporting.
MANIFEST.mdComplete package manifest indexing all documentation.

Core Documentation (docs/)

DocumentPurpose
docs/GETTING_STARTED.mdInstallation, initial codebase indexing, and MCP setup.
docs/AGENT_WORKFLOWS.mdContainment workflows: pre-flight, in-edit planning, and verification.
docs/CI_AND_GOVERNANCE.mdEnforcing architecture policies in CI pipelines.
docs/COMMAND_REFERENCE.mdComplete CLI syntax and configuration arguments.
docs/MCP_TOOLS.mdBehavior specifications for MCP clients.
docs/ARCHITECTURE.mdIndexing pipelines, C# project references, and Datalog evaluation.
docs/TRUST_MODEL.mdUnder-the-hood details of AST-proven vs heuristic confidence.
docs/BENCHMARKING.mdPerformance metrics: latency, token budgets, and scaling limits.
docs/COMPARISON.mdWhy Graphenium is distinct from grep, AST tools, and GraphRAG.
docs/POSITIONING.mdMarket positioning, target personas, and competitive differentiation.
docs/HARNESS_ADAPTER.mdEmbedding Graphenium's structural engine as a library.
docs/WORKED_EXAMPLES.mdCase studies proving containment on real repositories.
docs/GRAPH_REPORT.mdInterpreting the generated codebase audit report.
docs/DOCUMENTATION_MAP.mdFull documentation ecosystem overview.

Agent Integration

DocumentPurpose
skills/graphenium/SKILL.mdAgentic skill instructions and containment behavior rules.
contrib/harness-adapter/README.mdEmbedding Graphenium's engine inside AI coding harnesses.

Case Studies (worked/)

DocumentPurpose
worked/README.mdOverview of structural containment case studies.
worked/TEMPLATE.mdTemplate for documenting new codebase case studies.
worked/graphenium-self-analysis/README.mdGraphenium self-analysis: applying the containment engine to itself.
worked/graphenium-self-analysis/sample-queries.mdSample query output on Graphenium's own codebase.

Contact & Enterprise


License

MIT. See docs/LICENSE.md.

Установка

TypingMind
{
  "mcpServers": {
    "graphenium": {
      "command": "gm",
      "args": [
        "serve",
        "--graph",
        "/absolute/path/to/graphenium-out/graph.json"
      ]
    }
  }
}

Используйте MCP Graphenium с разными ИИ-моделями

TypingMind подключает инструменты MCP на уровне рабочего пространства, поэтому после подключения Graphenium вы можете использовать их с разными моделями ИИ в TypingMind, не настраивая подключение отдельно для каждой модели. Эта интеграция MCP работает локально на вашем устройстве через коннектор MCP TypingMind.

Руководство по настройке локального коннектора

Выберите этот способ, если серверу MCP нужен доступ к локальным файлам, приложениям или закрытым ресурсам на вашем компьютере.

1

Откройте настройки MCP

В TypingMind откройте «Настройки», затем «Расширенные настройки», перейдите в раздел «Протокол контекста модели» и выберите «Настроить коннектор».

  1. Откройте TypingMind в браузере.
  2. Нажмите значок настроек.
  3. Перейдите в «Расширенные настройки».
  4. Откройте раздел «Протокол контекста модели».
  5. Нажмите «Настроить коннектор» и выберите «Это устройство».
Экран настройки коннектора MCP в TypingMind с выбранным вариантом «Это устройство»
2

Выполните команду коннектора

Выберите «Это устройство», скопируйте команду из TypingMind и выполните её в терминале. Не останавливайте процесс, пока используете MCP.

  1. Скопируйте команду настройки, показанную в TypingMind.
  2. Откройте «Терминал» в macOS или Windows Terminal в Windows.
  3. Вставьте и выполните команду.
  4. Подтвердите установку пакета, если терминал запросит разрешение продолжить.
  5. Не закрывайте окно терминала и не останавливайте процесс, пока используете инструменты MCP.
3

Добавьте Graphenium как сервер

Когда статус коннектора сменится на «Готов», нажмите «Изменить серверы» и вставьте конфигурацию сервера MCP.

  1. Дождитесь, пока статус коннектора сменится на «Готов».
  2. Нажмите «Изменить серверы».
  3. Вставьте конфигурацию сервера MCP для Graphenium.
  4. Сохраните список серверов.
  5. Обновите статус, если хотите убедиться, что коннектор по-прежнему готов к работе.
Настройки MCP в TypingMind с активным сервером и кнопкой «Изменить серверы»
{
  "mcpServers": {
    "graphenium": {
      "command": "npx",
      "args": [
        "-y",
        "<mcp-server-package>"
      ]
    }
  }
}
4

Используйте подключение с разными моделями

Сохраните список серверов, откройте раздел «Плагины», включите инструменты MCP для Graphenium, затем выберите любую поддерживаемую модель ИИ в TypingMind и используйте инструменты в чате или назначьте их ИИ-агенту.

  1. Откройте страницу «Плагины» в TypingMind.
  2. Включите инструменты MCP для Graphenium.
  3. Начните чат и выберите модель ИИ, которую хотите использовать.
  4. Используйте инструменты MCP в чате или назначьте их ИИ-агенту.
  5. При необходимости переключайтесь на другую модель ИИ без повторного подключения MCP.
Чат TypingMind с включёнными инструментами MCP и выбранной ИИ-моделью
Можете помочь мне с этой задачей с помощью Graphenium?
Graphenium
Конечно. Я всё прочитал.
Вот что я нашёл с помощью Graphenium.

Часто задаваемые вопросы

Для чего используется сервер MCP Graphenium?

Graphenium — это сервер MCP, который позволяет совместимым ИИ-клиентам подключаться к внешним инструментам и получать контекст. В TypingMind достаточно один раз добавить этот сервер MCP, чтобы его инструменты стали доступны в вашем рабочем пространстве с ИИ.

Можно ли использовать сервер MCP Graphenium с несколькими ИИ-моделями в TypingMind?

Да. TypingMind подключает инструменты MCP на уровне рабочего пространства, поэтому вы можете использовать Graphenium с разными ИИ-моделями, например Claude, ChatGPT, Gemini или другими моделями, настроенными в TypingMind, без отдельной настройки сервера MCP для каждой модели.

Зачем использовать MCP Graphenium с TypingMind?

TypingMind — один из лучших интерфейсов для чата с LLM: он объединяет разные ИИ-модели, промпты, плагины, ИИ-агентов, ключи API и инструменты MCP в одном рабочем пространстве. Подключив Graphenium, вы сможете использовать его инструменты MCP с предпочитаемыми моделями, сохраняя удобную организацию работы с чатами в TypingMind.

Как подключить сервер MCP Graphenium к TypingMind?

Graphenium работает через локальный коннектор MCP TypingMind. Этот вариант лучше всего подходит, когда серверу MCP нужен доступ к локальным файлам, настольным приложениям, инструментам командной строки или закрытым ресурсам на вашем компьютере.

Какие инструменты предоставляет сервер MCP Graphenium в TypingMind?

Graphenium предоставляет возможности MCP, которые можно включить на странице «Плагины» в TypingMind и использовать в чате или назначить ИИ-агентам.

Нужно ли передавать TypingMind свои ключи API для использования сервера MCP Graphenium?

Нет. TypingMind ориентирован прежде всего на локальную работу и позволяет вам контролировать выбор провайдеров моделей, ключи API, промпты и конфигурацию MCP. Если Graphenium требует аутентификации, при создании подключения добавьте необходимые заголовки, настройки OAuth или локальную конфигурацию для этого сервера MCP.

Похожие серверы MCP

Все

Создайте свою рабочую ИИ-среду сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇