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.- High-Level System Architecture: The 4-tier stack spanning CLI parsing, the Hernex engine, storage layers, and tools.
- The Print Agent I/O Contract: Stream separation, Unix piping, and clean
stdoutcomposability. - The Agent Execution Lifecycle: Sequence diagram of turns, hooks, model invocations, and tool dispatches.
- Deterministic Permission Engine: Fail-closed security, declarative permission modes, and wildcard policy matching.
- Content-Addressed Delta Checkpoints: Pre-mutation SHA-256 snapshots and conflict-free rollbacks.
- Persistent Workspace Threads: On-disk transcript persistence, workspace isolation, and turn time travel.
- Native Language Server Protocol (LSP): AST symbol navigation and compiler-grade type analysis.
- POSIX Process Exit Codes: Deterministic exit code contracts for shell and CI scripting.
- Next Steps: Guided links to deeper guides.
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 ofgreg 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 asgreg "Fix unit tests" --permission-mode acceptEdits, the execution loop proceeds through a deterministic sequence:
The Turn Step Breakdown
- Ambient Configuration Ingestion: Resolves project-level
.greg/settings.json, environment variables, and CLI overrides. - Session Thread Hydration: Reads persistent history from
~/.greg/threads/<id>.json. If-cis passed, loads the latest workspace session. - Model Request Dispatch: Connects to the target model provider via Hernex’s first-slash routing adapter, attaching JSON schemas for authorized tools.
- Streaming & Tool Interception: Model tokens stream to
stdoutin real time. If the model emits structured tool calls, execution pauses for authorization. - Fail-Closed Policy Check: Every tool call is evaluated against the active permission mode and wildcard allow/deny rules.
- Pre-Mutation Checkpointing: If a tool will modify or create a file,
FileCheckpointStorerecords the exact file content and SHA-256 hash before disk writes occur. - 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 ingreg 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: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
- 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.
- 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. - Thread-Scoped Manifests: Each thread maintains its own manifest at
~/.greg/threads/<id>/checkpoints/manifest.jsonusing a version 2 envelope ({ version: 2, checkpoints: [...] }), tracking sequence numbers, UUIDs, labels, turn indices, and SHA-256 pre/post state hashes. - External Conflict Detection: When restoring with
greg checkpoints restore <id>,gregcompares current disk hashes against post-mutation states. If you modified files externally, restoration halts to prevent accidental overwrites unless--forceis passed. - 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:
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 tolspInputSchema:
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 ofgreg’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.