Skip to content
alok-108Public

Repository files navigation

Phantom

🌐 Translations: हिन्दी · Deutsch · Español · Português (Brasil) · Français · 简体中文 · 日本語 · Bahasa Indonesia · Tiếng Việt

tests release license: MIT python good first issues first timers only PRs Welcome discussions GitHub stars GitHub forks

Contributors welcome. New here? ⭐ Star this repository to bookmark it, pick a good first issue (comment /take to claim instantly!), read the Contributor Guide, and say hello in Discussions. Adding a new instruction takes four code edits. Issues labelled mentor available come with maintainer help. Open in a Codespace for a ready-to-go environment.

Phantom is a zero-dependency dual-layer toolkit for Python: audit entire repositories for hidden Unicode / Trojan Source attacks, build AST-bound ownership & provenance catalogs without imports, and embed a typed, validated instruction layer in ordinary Python comments.

Version 0.1.1 — zero runtime dependencies, tested on Python 3.10–3.13, and honest about what it does not do (see Limitations).

Terminal demo: python ignores the Phantom lines; phantom check validates them; phantom run applies them; phantom generate proposes them as a diff

Why use Phantom?

Phantom solves three practical problems in Python repositories without adding a single runtime dependency or modifying your code's AST:

  1. Zero-dependency Polyglot Security Scanner (phantom check --strict --homoglyphs --polyglot .) Recursively scans Python, JS/TS, Go, Rust, C/C++, Java, YAML, and Markdown repos for Trojan Source bidirectional overrides (CVE-2021-42574), zero-width smuggling, Unicode tag-block LLM prompt injections (U+E0000–U+E0FFF), and mixed-script Cyrillic/Greek homoglyph spoofing. Exports JSON and SARIF 2.1.0, and strips hidden characters safely with phantom strip --invisible-only.
  2. Zero-Import Ownership, Provenance, Stale Check & CODEOWNERS Sync (phantom catalog .) Annotate modules, classes, or functions with #: (Python/Shell/YAML) or //: (JS/TS/Go/Rust/C/C++/Java) comments (meta.author, meta.license, meta.version, meta.tags, meta.description, diagnostic.warn) — no imports, no decorators. Export Markdown (CATALOG.md), JSON, or auto-synced .github/CODEOWNERS (--format codeowners), enforce CI policies (--require-meta), and detect unused/stale annotations (--check-stale).
  3. Live Function Tracing, Hardened Sandbox & AST-Safe AI Generation (run --live / --sandbox / generate)
    • phantom run --live app.py (or with phantom.trace_session(...): inside pytest) tracks live per-function call counts, timing (ms), and function-bound counters/events with zero host imports.
    • phantom run --sandbox / phantom verify --sandbox isolates subprocesses with python -I, scrubbed environment variables (no leaked API keys), temp cwd, and POSIX CPU/memory limits.
    • phantom generate supports local Ollama (free, offline, zero dependencies), OpenAI / OpenRouter / Groq / vLLM, and Gemini — insert-only and AST-verified.
    • phantom convert --to comment migrates fragile whitespace/zero-width blocks into Black/Ruff formatter-safe comments; phantom init scaffolds CI + pre-commit in one command.
  • Your code stays untouched. python app.py runs it identically; phantom strip cleanly extracts pure Python.
  • Zero core dependencies. Pure Python standard library (>=3.10), including HTTP support for OpenAI-compatible and Ollama endpoints.
  • 13 typed instructions & strict security gates. Formal grammar, capability policies, SARIF/JSON exports, and pre-commit + GitHub Action integration.

Try it in 30 seconds

pip install "git+https://github.com/alok-108/phantom.git"

# 1. Audit any Python repo for hidden Unicode / Trojan Source characters
phantom check --strict .

# 2. Generate a Markdown ownership & diagnostics catalog for a repo
phantom catalog docs/examples --format markdown

# 3. Run a dual-layer Python file (zero imports in host code)
printf 'print("Hello")\n#: phantom:0.1.0 diagnostic.note("it works")\n' > hello.py
phantom run hello.py

You should see Hello followed by a Phantom diagnostic it works. (Not on PyPI yet; see docs/RELEASING.md.)

If Phantom is useful to your team or workflow, a star helps other developers discover it. If you want to shape it, the good first issues are the best way in.

What it is

def process_payment(amount: float) -> bool:
    return amount > 0

#: phantom:0.1.0 meta.author("Payments team")
#: phantom:0.1.0 counter.create("payments", 1000)
#: phantom:0.1.0 diagnostic.note("Payment module annotated")
  • python app.py runs your code; Phantom lines are comments and are not executed by stock Python.
  • phantom run app.py parses and validates the instruction layer, applies it, then runs your unmodified file as a subprocess.

Phantom does not modify Python, install import hooks, or change your environment. The execution model is spelled out in docs/RUNTIME.md.

Features

  • 13 typed instructions: events, bounded counters, diagnostic notes/warnings, and provenance metadata (author, version, license, tags, description) (reference).
  • Recursive repo auditing: phantom check --strict . scans entire repositories (skipping .git, .venv, __pycache__) with --exclude, --json, and SARIF 2.1.0 output.
  • Project catalog & compliance gates: phantom catalog . --format markdown builds AST-bound ownership and diagnostic reports and enforces --require-meta policies in CI.
  • Safe stripping & Unicode sanitization: phantom strip extracts pure host Python (AST-verified) or removes hidden invisible/bidirectional characters (--invisible-only).
  • Four encodings: comment (recommended), whitespace, zero-width Unicode, hybrid (ENCODINGS.md).
  • Multi-provider LLM generator: built-in zero-dependency Ollama (local/private) and OpenAI-compatible (openai, OpenRouter, Groq, vLLM) providers plus optional Gemini (GENERATOR.md).
  • Python library API: import parse, validate, audit_source, build_catalog, strip_phantom, strip_invisible, and PhantomRuntime directly from phantom.
  • Zero core runtime dependencies. No network calls unless you run generate with a remote provider and consent.

Install

Python ≥ 3.10.

pip install .                 # core
pip install -e ".[dev]"       # development (pytest, ruff)
pip install -e ".[llm]"       # optional: google-genai for `phantom generate`

See docs/INSTALLATION.md for details and editor support. Kate and KWrite users can install the Phantom syntax definition using the Kate / KWrite instructions.

Quick start

phantom check   docs/examples/comments.py     # validate, run nothing
phantom inspect docs/examples/comments.py     # show decoded instructions
phantom run     docs/examples/comments.py     # apply instructions, run the host
=== Phantom Runtime v0.1.1 ===
[OK] Validation passed (5 instruction(s), 0 warning(s))
Hello, World!

--- Phantom Diagnostics ---
[INFO] [docs/examples/comments.py:18:0 [comment]] Greeting counter initialised

Walkthrough: docs/QUICKSTART.md.

Commands

Command Purpose Executes your code?
phantom check PATH... [--strict] [--homoglyphs] [--polyglot] [--json] [--format sarif] [--exclude GLOB] Recursively validate files/dirs, audit hidden Unicode & homoglyphs; exit 2 on errors No
phantom catalog [PATH...] [--format text|markdown|json|codeowners] [--polyglot] [--check-stale] [--require-meta KEY] [-o FILE] Build an AST/symbol-bound ownership & diagnostic catalog, sync CODEOWNERS, or flag stale annotations No
phantom strip FILE [--invisible-only] [--check] [-o FILE | --in-place] Remove Phantom layers (AST-verified) or sanitize invisible/bidi Unicode characters No
phantom convert FILE [--to comment|whitespace|unicode] [-o FILE | --in-place] Migrate fragile whitespace/zero-width blocks to formatter-safe #: comments (or vice versa) No
phantom init [--dir DIR] [--ci] [--pre-commit] [--force] Scaffold .github/workflows/phantom.yml and .pre-commit-config.yaml in one command No
phantom inspect FILE [--json] [--strict] [--deny CAP] [--allow-only CAP] Show recognised instructions, locations, capabilities, and parse errors No
phantom run FILE [--live] [--sandbox] [--timeout SEC] [--max-output BYTES] [--deny CAP] [-- ARGS] Run with live function tracing (--live) or hardened subprocess isolation (--sandbox) Yes
phantom generate FILE --intent TEXT [--provider gemini|openai|ollama] [--model M] [--base-url URL] [--allow-remote] Propose an AST-verified candidate with Phantom instructions No (local Ollama stays offline; remote providers require consent)
phantom diff ORIGINAL CANDIDATE [--host-only] [--exit-code] Unified diff; opt in to exit 1 on differences, 2 on errors No
phantom verify ORIGINAL CANDIDATE [--sandbox] [--args ...] [--stdin-file FILE] Run both and compare stdout/stderr/exit code across test cases Yes (both)

python -m phantom … is equivalent to phantom ….

Instructions

Instruction Effect
event.declare(name) declare an event
event.on(event, handler) register "module.function" for a declared event
diagnostic.note(message) record a located informational note
diagnostic.warn(message) record a located warning diagnostic
counter.create(name, limit) bounded counter (limit > 0)
counter.increment(name) add 1 (logs an error diagnostic past the limit)
counter.decrement(name) subtract 1 (logs an error diagnostic below 0)
counter.reset(name) reset counter value back to 0
meta.author(name) record module/component owner or author
meta.version(version) record module or annotation schema version
meta.license(spdx) record SPDX license identifier
meta.tags(csv) record comma-separated classification tags
meta.description(text) record short description of the instruction layer

Instruction effects are applied at initialisation, before the host starts, not when execution reaches the line. Only the lifecycle events phantom.pre_execute, phantom.post_execute and phantom.shutdown are fired.

LLM generator

phantom generate asks a model for a JSON plan from the real instruction registry, validates it, inserts the instructions as new lines at a location it resolves itself, and checks that the result is valid Python, valid Phantom, and has an identical Python AST to your original. It never overwrites your file and never runs the candidate.

  • Local & private (zero dependencies): phantom generate app.py --provider ollama --model llama3.2 --intent "add provenance metadata" -o candidate.py
  • OpenAI-compatible (zero dependencies): OPENAI_API_KEY=... phantom generate app.py --provider openai --model gpt-4o-mini --allow-remote --intent "..." -o candidate.py (works with OpenAI, OpenRouter, Groq, Together, vLLM via --base-url or OPENAI_BASE_URL)
  • Gemini: GEMINI_API_KEY=... phantom generate app.py --provider gemini --allow-remote --intent "..." -o candidate.py

Remote providers always require explicit consent (--allow-remote). Details and limits: docs/GENERATOR.md.

Security notes

  • Parsing, check, inspect, diff never execute or rewrite your files (covered by tests).
  • Instruction arguments are literals; nothing decoded is passed to eval/exec/a shell.
  • phantom run executes the file, and handler paths import modules — only run files you trust. There is no sandbox.
  • Whitespace / zero-width encodings are not secret or secure; --strict exists to surface them.

See SECURITY.md and docs/THREAT_MODEL.md.

Current limitations

  • Runtime execution (phantom run / verify) is Python-only; static checking, homoglyph auditing, hidden-Unicode stripping, and catalog work across 20+ languages (--polyglot, supporting both #: and //: comments).
  • --sandbox provides OS-level environment/path/resource hardening (python -I, scrubbed env, temp cwd, POSIX rlimit), not a kernel/VM container boundary (like Docker/gVisor).
  • Whitespace and zero-width encodings are fragile under formatters — use phantom convert --to comment for formatter-safe annotations.
  • verify compares tested runs; it is not a mathematical proof of equivalence.
  • CI has passed on Python 3.10–3.13 on Ubuntu and Windows; macOS is untested.
  • Phantom C (a dual-layer model for compiled languages and a study of observer visibility) is a long-term research vision, not implemented: docs/research/PHANTOM_C.md. Status of every feature: docs/RESEARCH_STATUS.md.

Tests

pytest                                   # full suite
pytest --cov=phantom --cov-report=term-missing
ruff check src tests scripts
python scripts/verify_release.py         # release consistency gates

Contributing

Contributions of every size are welcome: bug fixes, tests, docs, new instructions, encodings, LLM providers and research experiments. Start with CONTRIBUTING.md and the step-by-step Contributor Guide (adding an instruction takes four code edits). Ideas are tracked as GitHub issues labelled good first issue, help wanted, mentor available and needs design. Before a pull request run ruff check src tests scripts, pytest and python scripts/verify_release.py. Questions and ideas are welcome in Discussions; maintainers are listed in MAINTAINERS.md and design decisions in docs/adr/.

Contributors

Contributors

Everyone who has a pull request merged is thanked in the release notes.

Star History

Star History Chart


⭐ Support Phantom

If you find this project interesting, please consider starring the repository ⭐ and sharing it! It helps other developers discover dual-layer programming.

Documentation

SPECIFICATION · VISION · ROADMAP · CHANGELOG · SECURITY · CONTRIBUTING

Guides: Contributor guide · Installation · CI · Quickstart · Language · Encodings · Runtime · Generator · Architecture · Compatibility · Troubleshooting · FAQ · Threat model · Research status

Research: overview · Phantom C · Observability · Method

License

MIT — see LICENSE.

Releases

Packages

Contributors

Languages