{
  "access": "public",
  "type": "reference",
  "format": "markdown",
  "title": "Invariant Tools Reference",
  "chunked": true,
  "url": "https://library.datagrout.ai/invariant-tools",
  "summary": "Semantic code analysis powered by neuro-symbolic reasoning. Extract structural facts, query for patterns, and verify goal alignment with deterministic Prolog rules.",
  "content_markdown": "# Invariant Tools\n\nSemantic code analysis powered by neuro-symbolic reasoning. Extract structural facts, query for patterns, and verify goal alignment with deterministic Prolog rules.\n\n## invariant.code_lens\n\nAnalyzes source code to extract structural and semantic facts.\n\n**What it does:** Parses source code (Elixir via AST, other languages via LLM) and produces structured semantic facts describing functions, calls, dependencies, intent, side effects, and patterns. Facts are persisted per `repo_id` and `commit_sha` for temporal querying.\n\n**Parameters:**\n\n| Name | Type | Required | Description |\n|------|------|----------|-------------|\n| `code` | string | yes | Source code to analyze |\n| `language` | string | yes | Programming language (`elixir`, `python`, `typescript`, `javascript`, `rust`, `go`) |\n| `filepath` | string | no | File path for context |\n| `commit_sha` | string | no | Git commit SHA for version indexing |\n| `repo_id` | string | no | Repository identifier for fact persistence and querying |\n| `options.include_intent` | boolean | no | Include semantic intent analysis (default: `true`) |\n\n**Example:**\n\n```json\n{\n  \"code\": \"defmodule Auth do\\n  def login(creds), do: verify(creds)\\n  defp verify(c), do: {:ok, c}\\nend\",\n  \"language\": \"elixir\",\n  \"filepath\": \"lib/auth.ex\",\n  \"commit_sha\": \"abc123\",\n  \"repo_id\": \"my-project\"\n}\n```\n\n**Returns:** `facts` (array of structured fact statements), `summary` (counts of modules, functions, calls).\n\n**Credits:** 4 (with intent) / 2 (structural only)\n\n---\n\n## invariant.code_query\n\nExecutes predefined semantic queries over lensed code facts using a Prolog reasoning engine.\n\n**What it does:** Loads persisted facts for a given `repo_id` and `commit_sha`, consults the Invariant rule engine, and runs deterministic queries. No LLM involved at query time — results are reproducible and instant.\n\n**Parameters:**\n\n| Name | Type | Required | Description |\n|------|------|----------|-------------|\n| `repo_id` | string | yes | Repository identifier |\n| `query` | string | yes | Query name |\n| `commit_sha` | string | no | Git commit SHA (uses stored default if omitted) |\n\n**Available queries:**\n\n| Query | Description |\n|-------|-------------|\n| `orphans` | Public functions with no callers |\n| `test_gaps` | Public functions without corresponding tests |\n| `dependency_cycles` | Circular module dependencies |\n| `intent_mismatches` | Functions whose inferred intent doesn't match their declared behavior |\n| `security_concerns` | Functions handling user input, SQL, or shell execution |\n| `hotspots` | Functions with high fan-in and complexity |\n| `debug_in_prod` | Debug/logging calls in production code |\n| `high_risk_changes` | Functions with many dependents |\n\n**Credits:** 3\n\n---\n\n## invariant.diff_analyzer\n\nCompares code before and after changes against a stated goal. Returns alignment score, concerns, and unexpected changes.\n\n**What it does:** Takes a before/after code pair and a natural language goal, then evaluates whether the changes accomplish the stated intent without unintended side effects. Uses LLM for semantic understanding but produces structured, actionable output.\n\n**Parameters:**\n\n| Name | Type | Required | Description |\n|------|------|----------|-------------|\n| `before` | string | yes | Code before changes |\n| `after` | string | yes | Code after changes |\n| `goal` | string | yes | Stated goal/intent of the changes |\n| `language` | string | no | Programming language |\n| `context` | object | no | Additional context |\n\n**Returns:**\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `alignment_score` | number | 0.0–1.0 score of goal alignment |\n| `alignment_reasoning` | string | Explanation of the score |\n| `changes_detected` | object | Structured breakdown of what changed |\n| `concerns` | array | Issues with severity, type, message, and suggestion |\n| `unexpected_changes` | array | Changes not expected given the stated goal |\n\n**Credits:** 4\n\n---\n\n## invariant.review\n\nComprehensive, project-aware code review in a single call. Orchestrates diff analysis, Prolog-based code queries, and criteria/constraint evaluation to produce a structured verdict.\n\n**What it does:** Accepts a diff (unified or before/after pair) alongside a goal, acceptance criteria, and constraints. Evaluates each criterion and constraint individually, producing a per-item status and an overall pass/fail verdict. Supports two modes: `\"check\"` for a lenient progress report, and `\"gate\"` for strict pass/fail gating.\n\n**Parameters:**\n\n| Name | Type | Required | Description |\n|------|------|----------|-------------|\n| `unified_diff` | string | conditional | Unified diff text (provide either this or `before`/`after`) |\n| `before` | string | conditional | Code before changes |\n| `after` | string | conditional | Code after changes |\n| `goal` | string | no | Stated goal/intent of the changes |\n| `criteria` | array | no | Acceptance criteria to evaluate |\n| `constraints` | array | no | Invariants that must hold (e.g. \"no new dependencies\") |\n| `repo_id` | string | no | Repository ID for Prolog fact queries |\n| `commit_sha` | string | no | Git commit SHA for Prolog queries |\n| `mode` | string | no | `\"check\"` (lenient, default) or `\"gate\"` (strict) |\n\n**Example:**\n\n```json\n{\n  \"unified_diff\": \"--- a/lib/auth.ex\\n+++ b/lib/auth.ex\\n...\",\n  \"goal\": \"add rate limiting to login\",\n  \"criteria\": [\"rate limit after 5 failures\", \"return 429 status\"],\n  \"constraints\": [\"no new dependencies\"],\n  \"mode\": \"gate\"\n}\n```\n\n**Returns:** `verdict` (pass/fail), `mode`, per-criterion `results` with status and reasoning, `concerns`, `alignment_score`.\n\n**Credits:** 6\n\n---\n\n## Agent feedback loop\n\nAdd these lines to an agent's system prompt for automatic verification:\n\n> After making code changes, call `invariant.diff_analyzer` with your stated goal as the `goal` parameter.\n> If `alignment_score` is below 0.8 or `unexpected_changes` is non-empty, review the concerns and revise before presenting your work.\n\nThis creates a neuro-symbolic self-correction loop where the agent's probabilistic code generation is verified by deterministic semantic analysis.\n\n## CLI\n\nThe [Invariant CLI](https://github.com/datagrout/invariant) provides local tree-sitter fact extraction for CI pipelines:\n\n```bash\ninvariant lens .              # Extract facts from all supported files\ninvariant query orphans       # Find functions with no callers\ninvariant diff --before a.rs --after b.rs --goal \"add caching\"\n```\n\nFacts extracted locally are uploaded to DataGrout for server-side semantic enrichment and querying via `invariant.code_query`.\n"
}