HunterX v7 Core Foundation

August 11, 2026 · View on GitHub

Status: Ratified (Foundation Sprint 001) Version: 1.0.0 Owner: HunterX Architecture Council


1. Purpose / Scope

This document describes the HunterX v7 Core Foundation package (src/hunterx/), the Clean Architecture backbone of the platform. It is a module reference and architecture guide for engineers building on the foundation. It SHALL be read together with the Development Bible (docs/bible/), which remains the specification of record; where this document conflicts with a Bible document, the Bible wins (docs/bible/README.md, Binding Status).

Scope:

  • What lives in the package and why (layer responsibilities).
  • The public API of every subsystem (classes, key methods, contracts).
  • Dependency and composition rules enforced by the architecture.
  • Diagram coverage: context, container, and layered component views.

Out of scope: tool implementations, plugin packages, AI models, deployment topologies, and business workflows — those belong to later sprints and to the Bible docs (02 - Architecture.md, 05, 06, 07, 25).


2. Package Overview

The foundation implements the ratified target layout from docs/bible/03 - Folder Structure.md §3. The package root (src/hunterx/) is a side-effect-free package: importing hunterx imports no submodules (src/hunterx/__init__.py), keeping import cost low and startup deterministic.

Layer / areaModulesResponsibility
Domainhunterx.domainPure entities, value objects, ports, services, events, exceptions
Applicationhunterx.applicationUse-case services and DTOs
Infrastructurehunterx.infrastructureAdapters implementing domain ports
Engineshunterx.enginesEngine facades: mission, workflow, planner, reasoning, correlation, report, risk, dedup
Deliveryhunterx.api, hunterx.cliREST API framework + CLI framework
Platformhunterx.agents, hunterx.plugins, hunterx.tools, hunterx.knowledge, hunterx.scheduler, hunterx.reportingSubsystems behind ports
Cross-cuttinghunterx.config, hunterx.shared, hunterx.security, hunterx.managers, facade modulesConfiguration, DI, security, manager facades

Dependency rule: Delivery → Application → Domain. Infrastructure implements domain ports and is injected upward at composition time. Nothing in the Domain layer imports fastapi, sqlalchemy, requests, or any framework library.


3. System Context (C4 Level 1)

flowchart LR
    O([Operator / Pentester]) -->|CLI, REST API, scheduled missions| H[HunterX v7 Platform]
    H -->|run tool adapters| T[External Tools]
    H -->|structured, masked prompts| AI[AI Providers]
    H -->|enrichment lookups| D[External Data CVE/CWE/EPSS]

    style H fill:#bbf,stroke:#333

The operator drives the platform through the CLI, the REST API, or scheduled missions. The platform executes tools through the tool runtime, calls AI providers only through the AI port abstraction, and enriches findings from external data sources. Tools, providers, and data sources are all behind interfaces; no subsystem depends on a concrete integration.


4. Container View (C4 Level 2)

flowchart TD
    CLI[CLI<br/>hunterx.cli] --> APP[Application Layer<br/>use-cases]
    API[REST API<br/>hunterx.api] --> APP
    SCHED[Scheduler<br/>hunterx.scheduler] -->|enqueue| APP

    APP --> ENGINES[Engines<br/>hunterx.engines]
    ENGINES --> PLATFORM[Platform subsystems<br/>agents / plugins / tools / knowledge / reporting]

    ENGINES -.ports.-> INFRA[Infrastructure adapters<br/>db / cache / queue / ai / sandbox / secrets / logging / telemetry]
    INFRA --> SQL[(SQL TIDB)]
    INFRA --> KV[(Cache)]
    INFRA --> Q[(Queue)]
    INFRA --> G[(Knowledge Graph)]

    style ENGINES fill:#bfb,stroke:#333
    style INFRA fill:#fbf,stroke:#333

Engines are facades over the platform subsystems. They depend on domain ports; concrete adapters from hunterx.infrastructure are injected at composition time (the CoreEngine dataclass in hunterx.engines.core is the composition root). The agent and workflow engines additionally consume the ExecutorPort contract so workflow steps can invoke tools.


5. Layered Component View (C4 Level 3)

flowchart TB
    subgraph Delivery
        CLI[CLI Application]
        API[API Application]
    end
    subgraph Application
        MS[MissionService]
        FS[FindingService]
        RS[ReportService]
    end
    subgraph Domain
        ENT[Entities & Value Objects]
        PORTS[Ports]
        SVC[Domain Services]
        EVT[Domain Events]
        EXC[Exceptions]
    end
    subgraph Infrastructure
        AD[Adapters]
    end
    subgraph Engines
        E[CoreEngine + Engine Facades]
    end
    subgraph Subsystems
        AG[Agents]
        PL[Plugins]
        TL[Tools]
        KN[Knowledge]
        RE[Reporting]
    end

    CLI --> MS
    CLI --> FS
    CLI --> RS
    API --> MS
    API --> FS
    API --> RS
    MS --> E
    FS --> E
    RS --> E
    E --> AG
    E --> PL
    E --> TL
    E --> KN
    E --> RE
    E -.implements ports.-> AD
    SVC --> ENT
    PORTS --> SVC
    AD -.implements.-> PORTS
    EVT --> PORTS

Rules enforced by design (see §8):

  1. Domain layer imports nothing outside hunterx.domain + hunterx.shared.
  2. Application layer imports domain + shared only; never infrastructure directly.
  3. Engines compose subsystems and adapters through ports.
  4. CLI/API never import each other's internals.

6. Key Runtime Flow — Tool Execution

sequenceDiagram
    participant W as Workflow Engine
    participant X as ToolExecutor
    participant A as Tool Adapter
    participant P as Parser Engine
    participant N as Normalizer
    participant S as Store (via ports)
    W->>X: execute_workflow_action(tool, target, params)
    X->>A: run(target, params, context)
    A-->>X: ToolOutput
    X->>P: parse(output)
    P->>N: normalize(parsed)
    N-->>W: canonical entities
    W-->>S: persist + emit events

Tool output is always wrapped in ToolOutput; tool failures never raise — errors are captured inside the output (hunterx/tools/executor.py:53).


7. Module Reference

This section documents every top-level subsystem under src/hunterx/.

7.1 hunterx.domain — Pure Domain Layer

The domain layer SHALL contain no framework or I/O imports.

ModuleContents
domain/entities/Target, TargetKind, Scan, ScanStatus, Asset, Finding, Evidence, EvidenceKind, Mission, MissionStatus, MissionKind, MissionPriority, Report, ReportKind, ReportStatus, DashboardQuery, MetricSeries, DashboardPanel, DashboardModel
domain/value_objects/IPAddress, DomainName, Hostname, URL, Protocol, Port, Service, AssetIdentifier, Scope, Severity, RiskScore
domain/ports/Repository, service, store, and messaging ports (see §7.1.1)
domain/services/PlannerService, Plan, PlannedStep, CorrelatorService, CorrelationGroup, DeduplicatorService, RiskScorerService
domain/services/validation.pyTidbValidator, EnvelopeTidbValidator, EntityTidbValidator (TIDB validation)
domain/events/DomainEvent (full metadata envelope) + typed events (MissionStartedEvent, MissionCompletedEvent, MissionFailedEvent, FindingCreatedEvent, ToolExecutedEvent, PluginLoadedEvent), EventCategory/EventSeverity/EventPriority/EventStatus (enums), EventSpec/EventRegistry, 52-event catalog (catalog.build_registry), AuditEventFactory (7 audit kinds) — see docs/v7-event-bus-observability.md
domain/exceptions/HunterXError + HunterXErrorCode; category subtrees: config, domain, infrastructure, operation
domain/plugins.pyPluginDescriptor
domain/tools.pyToolDescriptor

Key invariants: Finding computes a deterministic content hash (compute_content_hash) for dedup; Mission models lifecycle status, kind, and priority; Scope.allows gates target validity at the domain edge.

7.1.1 Ports

All ports are abstract base classes in hunterx/domain/ports/:

  • Repositories (repositories.py): Repository (save/delete/get/list) plus MissionRepository, FindingRepository, TargetRepository, ScanRepository, AssetRepository, ReportRepository — each refines the generic contract with domain-typed overrides (e.g. FindingRepository.exists_by_content_hash).
  • TIDB repositories (tidb_repositories.py): TidbRepository — generic CRUD + stream for any TIDB entity; TidbRepositoryFactory — see docs/v7-tidb.md.
  • Stores (stores.py): ObjectStorePort, EvidenceStore, KnowledgeGraphPort.
  • Services (services.py): AIPort, SandboxPort, SecretsPort, TelemetryPort, PluginRegistryPort, ToolRegistryPort.
  • Messaging (messaging.py): CachePort, QueuePort, EventBusPort, Handler.
  • Observability (observability.py): ObservabilityEventBusPort, EventStorePort, DeadLetterQueuePort, MetricsPort, TracerPort, HealthRegistryPort, HealthProbePort, TelemetryProviderPort — see docs/v7-event-bus-observability.md.

7.2 hunterx.application — Use-Case Layer

ModuleContents
application/missions.pyMissionService — mission use-cases
application/findings.pyFindingService — finding use-cases
application/reports.pyReportService — report use-cases
application/observability.pyObservabilityService — unified events/metrics/tracing/health/telemetry API
application/dto.pyCreateMissionRequest, CreateFindingRequest, CreateReportRequest
Application services SHALL depend only on domain ports; concrete adapters are
injected through the container.

7.3 hunterx.engines — Engine Facades

ModuleContents
engines/core.pyCoreEngine — composition root aggregating all engines and renderers
engines/mission.pyMissionEngine — mission lifecycle orchestration
engines/workflow.pyWorkflowEngine, WorkflowDefinition, WorkflowStep, ExecutorPort — DAG execution
engines/planner.pyDeterministicPlanner — template planning
engines/reasoning.pyReasoningEngine — AI-assisted analysis (behind AIPort)
engines/correlation.pyTargetCorrelator — finding correlation
engines/risk.pyDefaultRiskScorer — risk scoring
engines/deduplicator.pyContentDeduplicator — content-hash dedup
engines/report.pyReportEngine — report assembly

The workflow engine consumes ExecutorPort so steps can invoke tools through the ToolExecutor without depending on the tool subsystem directly.

7.4 hunterx.infrastructure — Adapters

Adapters implement the domain ports. All are swappable at composition time.

ModuleAdapters
infrastructure/cache/MemoryCache, NullCache (CachePort)
infrastructure/queue/MemoryQueue, NullQueue (QueuePort)
infrastructure/event_bus/InMemoryEventBus (EventBusPort)
infrastructure/event_bus/store.pyInMemoryEventStore, InMemoryDeadLetterQueue (persistence, DLQ, replay)
infrastructure/metrics/InMemoryMetrics (counters, gauges, histograms, Prometheus render)
infrastructure/tracing/InMemoryTracer, Span (span hierarchy, propagation)
infrastructure/health/HealthProbe, HealthRegistry (unified component probes)
infrastructure/logging/JsonFormatter, JsonRotatingFileHandler, LoggingManager, correlation + masking
infrastructure/ai/NullAIClient (AIPort)
infrastructure/sandbox/SubprocessSandbox (SandboxPort)
infrastructure/secrets/EnvironmentSecrets, InMemorySecrets (SecretsPort)
infrastructure/telemetry/MemoryTelemetry (TelemetryPort)
infrastructure/db/sql/SQLAlchemy Base/models, SessionFactory, Sql*Repository for all six entities
infrastructure/db/sql/tidb_models/87 TIDB ORM models (TidbModelMixin + 11 model modules); see docs/v7-tidb.md
infrastructure/db/sql/registry.pyTIDB entity ↔ model registry
infrastructure/db/sql/mapping.pyRowMapper — entity/row coercion
infrastructure/db/sql/crud.pySqlCrudRepository, SqlTidbRepositoryFactory (generic TIDB CRUD)
infrastructure/db/sql/memory.pyInMemoryCrudRepository, InMemoryTidbRepositoryFactory
infrastructure/db/sql/versioning.pyVersioningListener, install_versioning (audit/history trail)
infrastructure/db/graph/InMemoryKnowledgeGraph (KnowledgeGraphPort)
infrastructure/db/object_store/FileSystemObjectStore, FileSystemEvidenceStore
infrastructure/db/search/InMemorySearchIndex

SQLAlchemy imports are lazy (infrastructure/db/sql/factory.py) so the foundation works without a database driver installed.

7.5 hunterx.agents — Multi-Agent Platform

ModuleContents
agents/base.pyAgentCapability (enum), SecurityAgent (abstract contract)
agents/registry.pyAgentRegistry
agents/orchestrator.pyAgentOrchestrator
agents/coordinator.pyAgentCoordinator
agents/scheduler.pyAgentSchedule, AgentScheduler
agents/memory.pyAgentMemory
agents/context.pyAgentContext
agents/events.pymessage_to_event bridging messages to domain events
agents/messaging.pyAgentMessage
agents/state.pyAgentState (enum)
agents/capabilities.pyCapabilitySet

Agents express goals; they never call AI providers directly — reasoning goes through the ReasoningEngine and AIPort only.

7.6 hunterx.plugins — Plugin System + SDK

ModuleContents
plugins/manifest.pyPluginKind, PermissionFlag, PluginManifest
plugins/registry.pyPluginRegistry (PluginRegistryPort)
plugins/loader.pyPluginLoader
plugins/manager.pyPluginManager — lifecycle: dependency resolve → load → version check → permission grant → activate
plugins/lifecycle.pyLifecycleHooks (plain mixin, no-op defaults)
plugins/permissions.pyPluginPermissions
plugins/sandbox.pySandboxPolicy
plugins/versioning.pycheck_platform_compatibility
plugins/dependencies.pyresolve_load_order
plugins/sdk/Public SDK: PluginContext, PluginSession, PluginResult, FindingResult, EvidenceResult, emit

Plugin code SHALL import only the public SDK (hunterx.plugins.sdk) and MUST NOT import private internals of the foundation.

7.7 hunterx.tools — Tool Runtime

ModuleContents
tools/adapter.pyBaseTool, ToolContext, ToolOutput
tools/categories.pyScannerTool, CrawlerTool, EnumeratorTool, AnalyzerTool, ReporterTool
tools/executor.pyToolExecutor — run tools by name, expose descriptors
tools/parser.pyParserEngine
tools/normalizer.pyNormalizerEngine
tools/validation.pyToolValidator
tools/registry.pyToolRegistry (ToolRegistryPort)
tools/discovery.pyToolDiscovery
tools/sandbox.pyToolSandboxPolicy

7.8 hunterx.knowledge — Knowledge Base

ModuleContents
knowledge/registry.pyKnowledgeRecord, KnowledgeRegistry
knowledge/loader.pyKnowledgeLoader
knowledge/graph.pyKnowledgeGraph
knowledge/engine.pyKnowledgeEngine — facade answering lookup/explain/link questions

7.9 hunterx.scheduler — Scheduler

ModuleContents
scheduler/jobs.pyJob, JobStatus, Schedule
scheduler/service.pySchedulerService — register schedules, fire jobs into the queue

The scheduler is independent from the agent scheduler: it handles mission-level operations; AgentScheduler handles recurring agent dispatches.

7.10 hunterx.reporting — Reporting

ModuleContents
reporting/views.pyFindingView, MissionView, ReportView, build_report_view
reporting/renderers.pyRenderer (ABC), JsonRenderer, MarkdownRenderer
reporting/evidence.pyEvidence packaging

7.11 hunterx.config — Configuration

ModuleContents
config/settings.pypydantic settings: Settings, DatabaseSettings, CacheSettings, QueueSettings, SecuritySettings, ApiSettings, AppConfig
config/loader.pyload_default_settings, ConfigurationManager

7.12 hunterx.shared — Cross-Cutting Helpers

ModuleContents
shared/di.pyContainer — thread-safe service container with parent chains and singletons
shared/ids.pygenerate_id, generate_content_id, is_ulid
shared/masking.pymask_secret, mask_value
shared/result.pyResult, Success, Failure
shared/time.pyutcnow, utcnow_iso

7.13 hunterx.security — Security Services

ModuleContents
security/policies.pySecurityPolicy
security/manager.pySecurityManager, Actor, Permission, Role, PermissionDeniedError

SecurityManager.authorize raises PermissionDeniedError unless any of the actor's roles grants the required permission; resolve_secret requires the secrets.read permission and delegates to SecretsPort.

7.14 hunterx.managers — Manager Facades

ModuleContents
managers.pyCacheManager, QueueManager, EventBus, DependencyManager

Each facade wraps a port (CachePort, QueuePort, EventBusPort) or the Container, keeping backends swappable. Convenience re-export facades: hunterx.cache, hunterx.queue, hunterx.events, hunterx.logging, hunterx.telemetry, hunterx.observability, hunterx.models, hunterx.exceptions, hunterx.utils.

7.15 hunterx.api — REST API Framework

ModuleContents
api/app.pycreate_app(settings, *, register_health, platform) — FastAPI app factory (lazy import); builds and wires a Platform when omitted
api/router.pyApiRouter, RouteSpec — routing structure without FastAPI import
api/middleware.pyregister_exception_handlers, _status_for
api/deps.pyAppContainer, get_container, configure_container
api/schemas.pyAPIModel, ErrorResponse

FastAPI is an optional extra; importing hunterx.api does not require it.

7.16 hunterx.cli — CLI Framework

ModuleContents
cli/app.pyCliApplication, main — command dispatcher, no third-party arg parsing
cli/registry.pyCommand, CommandRegistry
cli/commands.pyregister_default_commands
cli/render.pyOutputRenderer

8. Architecture Rules

Keywords follow RFC 2119.

  1. The domain layer (hunterx.domain) MUST NOT import any framework, infrastructure, engine, API, or CLI module.
  2. The application layer MUST depend only on hunterx.domain and hunterx.shared; it MUST NOT import hunterx.infrastructure directly.
  3. Subsystems MUST communicate through ports, the event bus, and the message bus; no subsystem SHALL import another subsystem's internals.
  4. AI providers MUST be reachable only through AIPort. Agents MUST NOT call LLMs directly.
  5. Concrete adapters MUST be wired at composition time (via CoreEngine, Container, or constructors); the foundation SHALL ship in-memory adapters so it runs with zero external services.
  6. Every public contract SHALL have a docstring; the package SHALL lint clean under the configured ruff gates and pass the test suite before a sprint is marked done.
  7. New modules MUST follow the dependency rules in docs/bible/03 - Folder Structure.md §7.

9. Verification

The foundation is gated by:

  • python -m ruff check src — lint gate (0 errors).
  • python -m compileall -q src — import/compile smoke.
  • python -m pytest -q — unit/component/integration/golden/security/ acceptance/performance suites (72 tests at Sprint 001 close).

Tests live under tests/ (unit, component, integration, golden, security, acceptance, performance, framework) with in-memory fakes (tests/framework/inmemory.py, tests/framework/fakes.py).


10. References

  • docs/bible/01 - Vision.md — platform mission and Definition of Done
  • docs/bible/02 - Architecture.md — system architecture, C4 views, ADRs
  • docs/bible/03 - Folder Structure.md — layout, dependency rules (§7)
  • docs/bible/16 - Documentation Standards.md — this document's governing standard
  • docs/bible/README.md — Bible index and binding status