Skip to main content
greg is designed from first principles as an autonomous print agent. While traditional AI coding tools operate as interactive terminal chat UIs that trap your workflow inside an endless conversational loop, greg treats the large language model as a composable Unix command-line utility. Powered by the @amaranthic/hernex agent runtime, greg executes complex multi-step developer tasks, reads abstract syntax trees through language servers, manages deterministic security guardrails, snapshots pre-mutation file states, and streams clean results directly to standard output.
Whether you are a software developer using greg for everyday refactoring or a platform engineer embedding greg into automated CI/CD pipelines, this document breaks down the underlying architecture, execution cycles, and safety mechanisms.
This page covers:

High-Level System Architecture

greg is structured into four decoupled layers, ensuring that CLI flag resolution, engine orchestration, security enforcement, and filesystem operations remain strictly isolated:

The 4 Architectural Tiers


The Print Agent I/O Contract

The central design philosophy of greg is strict stream isolation. In standard terminal programming, mixing interactive diagnostic messages with output data makes piping to tools like jq, sed, or clipboard utilities impossible without noisy scraping. greg enforces a clean I/O separation:

1. Standard Input (stdin)

When data is piped into greg (e.g. cat error.log | greg "Diagnose this"), the CLI automatically buffers standard input up to 512 KiB (maxStdinBufferBytes), injects it into the initial prompt context, and executes without waiting for keyboard interaction.

2. Standard Output (stdout)

Standard output is reserved exclusively for the model’s final response text, generated source code, or structured JSON (when --output-format json or --output-format stream-json is requested). Output redirection (greg "..." > file.ts) produces completely clean files without terminal control characters.

3. Standard Error (stderr)

All runtime telemetry—turn counters, token metrics, tool call notices (e.g. Read(src/index.ts)), LSP status, and permission denials—are routed strictly to standard error.

The Agent Execution Lifecycle

When you trigger a command such as greg "Fix unit tests" --permission-mode acceptEdits, the execution loop proceeds through a deterministic sequence:

The Turn Step Breakdown

  1. Ambient Configuration Ingestion: Resolves project-level .greg/settings.json, environment variables, and CLI overrides.
  2. Session Thread Hydration: Reads persistent history from ~/.greg/threads/<id>.json. If -c is passed, loads the latest workspace session.
  3. Model Request Dispatch: Connects to the target model provider via Hernex’s first-slash routing adapter, attaching JSON schemas for authorized tools.
  4. Streaming & Tool Interception: Model tokens stream to stdout in real time. If the model emits structured tool calls, execution pauses for authorization.
  5. Fail-Closed Policy Check: Every tool call is evaluated against the active permission mode and wildcard allow/deny rules.
  6. Pre-Mutation Checkpointing: If a tool will modify or create a file, FileCheckpointStore records the exact file content and SHA-256 hash before disk writes occur.
  7. Tool Execution & Feedback: The tool runs, captures output/errors, and feeds results back to the model for subsequent turns until the agent finishes.

Deterministic Permission Engine

Security in greg is fail-closed: any tool call that is not explicitly authorized is immediately denied. In non-interactive print mode, greg never blocks on keyboard confirmation prompts—unauthorized actions fail fast.

The 4 Permission Modes

Wildcard Scoped Allow Rules

You can grant granular execution rights to specific shell commands or file paths using PascalCase tool rules:
Rules are compiled into anchored regular expressions (src/policy/ruleMatch.ts), supporting wildcard glob expansion (*), escaped characters, and argument boundaries.

Content-Addressed Delta Checkpoints

Unlike tools that rely on Git commits (polluting your commit history with intermediate agent attempts), greg maintains an out-of-band content-addressed store powered by Hernex’s FileCheckpointStore.

Checkpoint Guarantees

  1. Pre-Mutation Atomicity: Checkpoints record file states before mutations occur. If a tool writes 5 files and crashes on the 6th, the pre-mutation state of all 6 files is preserved.
  2. Content-Addressed Blob Deduplication: Rather than creating duplicate copies of entire repositories, Hernex stores unique file contents in a global content-addressed store at ~/.greg/blobs/sha256/<hash>. Multiple checkpoints referencing the same file content share identical blob entries.
  3. Thread-Scoped Manifests: Each thread maintains its own manifest at ~/.greg/threads/<id>/checkpoints/manifest.json using a version 2 envelope ({ version: 2, checkpoints: [...] }), tracking sequence numbers, UUIDs, labels, turn indices, and SHA-256 pre/post state hashes.
  4. External Conflict Detection: When restoring with greg checkpoints restore <id>, greg compares current disk hashes against post-mutation states. If you modified files externally, restoration halts to prevent accidental overwrites unless --force is passed.
  5. Dry-Run Inspection: You can preview what files will be restored, deleted, or conflicted before touching disk using --dry-run:

Persistent Workspace Threads

greg persists conversation sessions under ~/.greg/threads/<thread-id>/ (or $HERNEX_HOME/threads/<thread-id>/). Sessions are automatically partitioned by your current working directory (process.cwd()).

On-Disk Thread Layout

Inside each thread directory, FileThreadStore maintains three core files:

Session Lifecycle & Time Travel

  • Continuing Tasks (-c): Reads the most recently updated thread for the current directory and appends the new instruction.
  • 1-Based Turn Indexing (--resume-session-at <index>): Truncates the active conversation to the exact turn count specified, allowing you to branch or explore alternate architectures without polluting model context.

Native Language Server Protocol (LSP)

Plain text regex search (grep) is fast, but struggles with multi-file renames, ambiguous symbol names, and type definitions. greg embeds a native LSP Client powered by Hernex’s LspTool and persistent LspProcessPool.

Enabling LSP Code Intelligence

By default, enableLsp is set to false in settings to ensure instant startup for general-purpose text tasks. To enable LSP code intelligence globally:
When enabled, greg automatically checks your registered servers or falls back to its curated default catalog in src/utils/lsp.ts.

Curated Default Server Catalog

Supported LSP Operations

Hernex exposes compiler-grade operations conforming to lspInputSchema: Note: Line and character parameters use 1-based indexing.

Managing Language Servers (greg lsp)

You can register custom language servers (e.g. gopls, clangd, zls, or solc) using the greg lsp subcommand tree:

POSIX Process Exit Codes

For automation and CI/CD pipelines, greg adheres to standard POSIX process exit contracts. Shell scripts can inspect $? to branch deterministically:

Next Steps

Now that you have a comprehensive understanding of greg’s internal mechanics:
  • Quickstart: Walk through your first practical task from start to finish.
  • Managing Providers: Configure frontier models, reasoning effort, and fallback chains.
  • Managing Threads: Master session branching, checkpoints, and time-travel rollbacks.
  • Common Workflows: Explore real-world recipes for exploration, refactoring, and test automation.