Skip to content

Agent Architecture Reference ​

Audience: Developers — Contributors reading the module/lifecycle overview linked by AGENTS.md.

AGENTS.md is authoritative for development mandates. This reference holds descriptive architecture only; use the owning adapter and canonical guides for detailed behavior.

How It Works ​

  1. The user initiates hpilot from the command line, optionally pointing to a hpilot.yaml config file.
  2. The system performs a dependency pre-check (required harness SDK or CLI, authentication, and verifier API key where applicable) and fails fast if anything is missing.
  3. For each pipeline stage, the system:
    • Runs one mutually exclusive executor:
      • an agent prompt from prompt (prompt_template remains an alias), or
      • a trusted shell string from command.
    • Launches the harness for that stage (Claude Code, Codex, OpenCode, Cursor, or Antigravity) in non-interactive mode. Each stage can override the global default through stage_overrides in ~/.hpilot/config.yaml.
      • Claude: Uses the claude-agent-sdk Python package with query() for SDK turns; supported blocked evaluations continue in the same session.
      • Cursor: Uses the synchronous cursor-sdk Python API on a worker thread.
      • Codex: Uses the official openai-codex Python SDK with an explicitly selected standalone Codex CLI.
      • OpenCode: Uses loopback HTTP via opencode serve.
      • Antigravity: Uses ACP sessions over the official agy acp subprocess.
    • Harness Pilot passes an immutable StageEvaluationContext to the selected adapter and does not patch agent settings:
      • Claude: Uses claude-agent-sdk Python package. Does not require settings-file patching or Claude Code hooks. Harness Pilot enforces contracts and makes verifier decisions between SDK turns, with blocking decisions continued in the same session. Read-only paths use the shared Git-backed change-detection guard.
      • OpenCode: Starts an isolated opencode serve instance per stage. Injects native ordered permissions via a process-local overlay, normalizes inherited asks before preserving denies, and admits known MCP file writes by actual-path permission checks. Does not use Git-backed change detection enforcement.
      • Cursor: Uses the in-process cursor-sdk adapter. SDK messages are translated defensively and tool calls are mapped into canonical events. Read-only paths use Git-backed detect-only enforcement.
      • Codex: Uses Git-backed change detection (the shared Git-backed read-only guard) for read-only paths.
      • Antigravity: Launches agy with a process-local autonomous permission override and uses Git-backed detect-only enforcement.
    • Shared stage evaluation validates contracts between supported agent turns before asking the OpenAI-compatible LLM for a structured JSON-only verifier decision (decision, reason), where decision is approve or block; unsupported continuation falls back to the normal retry path.
    • If parsing fails, the evaluator requests JSON regeneration from the model.
    • After agent completion, Harness Pilot re-validates any required YAML result artifact, records the normalized status, and routes to the next stage through contract statuses or explicit stage routing.
    • On failure or exhausted correction loops, the pipeline aborts.
  4. Accepted daemon submissions use stable per-task event sequences and make three bounded cursor-based resume attempts after transport loss without repeating run; replay gaps and exhausted recovery produce an explicit unknown-status outcome, and batch submission leaves unresolved plans pending. MCP file tools (file_read, file_write, file_edit) admit blocking work through four dedicated worker threads, and modifying calls are never automatically retried after ambiguous transport loss. Yieldshell (yieldshell_execute with side_effects: ["NONE"] such as rg --files, rg -n -F, find, git grep, ls) is the canonical mechanism for file discovery and content search; the file surface is exactly those three tools plus the yieldshell_ registry and any other file_ name returns an unknown-tool error.
  5. All status transitions are reported via structured logging (stderr for humans, JSON log file for machines under .hpilot/logs/), and live agent output is streamed into stderr and per-stage log files under .hpilot/logs/. Log files are cleared before each run (standalone, daemon startup, and each daemon task) so they always reflect the current execution — previous run logs are not preserved.
  6. Persistent daemon and MCP diagnostics append under .hpilot/logs/services/ and are not owned by run cleanup; only the run JSONL, evaluation JSONL, and stage directory are disposable.
  7. On SIGINT/SIGTERM, the system gracefully shuts down by cancelling the active SDK worker task (for in-process adapters) or terminating the active subprocess group, cleaning up agent processes, and logging the interruption before exiting with code 130.

Core Structure ​

  • .specify/: The heart of the project's orchestration and memory.
    • AGENTS.md: The source of truth for all development principles and workflows.
    • templates/: Standardized templates for plans, specs, tasks, and checklists.
    • scripts/bash/: Operational scripts for prerequisite checks, feature creation, and context synchronization.
  • src/hpilot/: The Python CLI package, organized into focused subpackages with thin public re-exports at the top level.
    • cli/: CLI entry point split into commands.py, _daemon_cmds.py, _standalone_cmds.py, parser.py, instance.py, and docs.py.
    • client/: Daemon WebSocket client split into commands.py, connection.py, rendering.py, and streaming.py.
    • pipeline/: Pipeline execution split into runner.py, _agent_attempt.py, _command_attempt.py, _command_stage.py, _execution.py, _continuation.py, _pipeline_hooks.py, _session_metadata.py, _resume_reporting.py, _cleanup.py, _interrupt.py, _routing.py, artifacts.py, contract.py, and internal runtime/usage helpers.
    • server/: Daemon split into daemon.py, _daemon_config.py, handlers.py, _task_exec.py, tasks.py, _cleanup.py, and _path.py.
    • evaluation/: Immutable stage context, contract checks, verifier client, decision parsing, event logging, and shared reply evaluation.
    • adapters/: Harness adapter registry, shared process-termination helper (_process.py), and harness-specific adapters (claude, codex, opencode, cursor, antigravity, mock).
    • config/: Configuration package split into _types.py (dataclasses, constants, formatting helpers), _parsing.py (YAML loading, validation, and resolution), and _stage_parsing.py (stage-level parsing); re-exports all public names through __init__.py.
    • cli.py, client.py, pipeline.py, server.py: Thin backward-compatible re-exports from the split subpackages.
    • preflight.py: Dependency pre-check (fail fast at startup).
    • signals.py: SIGINT/SIGTERM handler with process-group-aware subprocess cleanup.
    • logging.py: Structured logging to stderr + JSON log file with execution metadata.
    • init.py: hpilot init scaffolding logic.
    • doctor.py: Diagnostic health-check command.
    • global_config.py: Per-user global config (~/.hpilot/config.yaml) read/write.
    • skills.py: Skill discovery and registry.
    • upgrade.py: Self-upgrade command.
    • stream_logging.py: Live agent output stream logging.
      • Canonical Event Kinds: Emits reply: (visible assistant text), thinking: (internal model reasoning), and tool call: (parameters rendered with field: label format, one field per indented line).
      • Tool Field Aliases: Adapters normalize tool names while preserving argument keys. The shared renderer resolves aliases through tool_field_aliases.py without mutating tool input.
      • OpenCode Handling: Native tool events are scoped/deduplicated by call identity. Completed session.text.ended and session.reasoning.ended blocks become canonical reply/thinking events; partial deltas and snapshots are not rendered twice. Raw lifecycle and metadata events remain in structured logs without noisy stderr rendering.
      • Codex Handling: Assistant and reasoning deltas are ignored. Completed message items become reply: events, and completed reasoning summary or content items become thinking: events. When the model delegates to native subagent threads (absence is normal when the model handles the task directly), Harness Pilot follows only referenced child threads for observability and interleaves their canonical events with a [subagent:<label>] suffix (nickname or last 8 thread-ID characters) while keeping parent output, final response, retry routing, and usage unchanged; child JSONL envelopes carry hierarchy metadata and history reconstruction covers fast children, with one warning per child and failure category on observation failure; subagent lines appear in both hpilot run stderr and daemon task output (hpilot submit/attach/logs) and in the per-stage JSONL (see docs/agents/codex.md and src/hpilot/adapters/codex/README.md).
    • server_events.py: Daemon event definitions.
    • server_signals.py: Daemon signal handling.
    • _constants.py: Package-wide constants.
  • mcp/: Optional authenticated Streamable HTTP server, workspace path guard, file provider, in-process yieldshell composition, request middleware, structured events, and listener lifecycle.
  • assets/verifier/: Stage-completion verifier prompt assets.
  • .agent/, .claude/: Configuration and custom workflows for various AI agents.
  • AGENTS.md: The primary mandate file for all AI agents.
  • CLAUDE.md: Agent-specific mandate reference pointing to AGENTS.md.
  • hpilot.yaml: Pipeline configuration file (stage prompts, retries, contracts, explicit routes). The default harness is set with hpilot use <harness>, not in this file.
  • docs/pipeline-authoring.md: Canonical guidance for designing hpilot.yaml pipelines and contract prompt files for both human contributors and AI agents.
  • ~/.hpilot/config.yaml: Per-user global config containing the default harness, optional model_effort, and stage_overrides for per-stage harness, model, effort, and Codex-only goal selection with optional cumulative iteration thresholds. It also holds verifier, credential, usage, server, and global lifecycle hook settings. Harness Pilot reloads it before every stage attempt. Command stages consume resolved hooks but do not resolve or construct an agent harness.

Configuration ​

The pipeline is configured through hpilot.yaml. Set the default harness with hpilot use <harness> (supported: claude, codex, opencode, cursor, antigravity, mock).

yaml
stages:
  - name: Spec
    prompt: "Generate a feature specification for: {feature_description}"
    max_retries: 3
    cleanup:
      - .hpilot/artifacts
  - name: Review Code
    max_iterations: 5
    max_iterations_next_stage: Verify
    contract:
      required_tasks:
        - "Run linter"
        - "Run type checker"
      routes:
        changes_requested:
          next_stage: "Fix Code"
          injections: [findings, required_changes]
  - name: Fix Code
    next_stage: "Review Code"

All fields have sensible defaults. A minimal config only needs stage names in stages. - Stage-level fields: - prompt: Preferred agent prompt spelling; prompt_template is an accepted alias. - command: Trusted shell executor, mutually exclusive with agent-only fields. - max_retries: Failure retry cap. - max_iterations: Total visit cap, with forced routing to max_iterations_next_stage. - reset_iterations: List of stage names whose counters reset to zero after this stage succeeds. Self-reset is invalid; duplicates are deduplicated. - cleanup: Paths swept before agent starts (useful for stages producing fresh artifacts). - keep_artifacts: Paths post-run contract evaluation blocks on if missing. - contract.required_tasks: Optional fixed work items that must appear in the artifact's Completed Tasks list before any status route passes. See Pipeline Authoring Guide. - read_only_paths: Protects Git-visible files during that stage. Claude, Cursor, Codex, and Antigravity use shared Git-backed, detect-only enforcement. OpenCode enforces ordered native and session permission rules plus programmatic MCP write admission through a process-local configuration overlay. - Overrides & Options: - Per-stage harness, model, effort, and Codex-only goal overrides are in ~/.hpilot/config.yaml under stage_overrides with optional cumulative iterations thresholds (see docs/agents/codex.md and docs/configuration.md). - When read_only_paths is empty, no read-only enforcement is active. - Adapter tool disabling is configured via each adapter's disallowed_tools. - Verifier configuration is sourced from ~/.hpilot/config.yaml.

When every agent stage in the effective slice has a self-contained prompt (no {objective} placeholder), hpilot submit and hpilot run accept execution without a positional prompt or stdin input. Command stages are always promptless and require no agent or verifier configuration.