Orchestrata Ultimate / Specs / 102-volk-test-harness

102-volk-test-harness: Spec 102 — Individual Volk Test Harness

The Individual Volk Test Harness is a scenario-driven evaluation system that exercises each volk (agent) individually through real LLM calls with real Redis/Neo4j infrastructure, operating on the orchestrata-ultimate codebase itself (dogfooding). It is an on-demand quality assurance tool, not part of the standard CI/CD test suite.

At a glance

Item Value
Spec directory specs/102-volk-test-harness/
Status line in the spec | Draft |
Requirement IDs defined 131
With a @traces citation in src/ 104 (79.4%)
With a @traces citation in tests/ 0 (0.0%)
Tracked files 3
RTM page 102-volk-test-harness

Reading this spec

This spec defines the Individual Volk Test Harness, a scenario-driven evaluation system that exercises each volk (agent) on its own, using real LLM calls and real Redis and Neo4j infrastructure, against the orchestrata-ultimate codebase itself. It is an on-demand quality assurance tool and is not part of the standard CI/CD test suite. The reason is that volks act autonomously and their output varies from run to run, so quality has to be measured statistically, with real infrastructure, and attributed to a specific agent rather than inferred from end-to-end tests. The harness also catches regressions by comparing snapshots across runs, and can run a self-healing loop of at most 3 hops when a scenario fails.

The method: each volk has a directory of YAML scenarios (harness/scenarios/<volk_name>/) that describe tasks, expected outcomes and evaluation criteria; Python setup hooks prepare the environment; each scenario runs three independent trials, isolated in git worktrees or Incus containers; evaluators judge the result. The twenty functional requirements (FR-001 to FR-020) cover the scenario format, setup hooks, a dual LLM model strategy, CXP packet injection and direct method call modes, three trials per scenario, snapshot comparison, deterministic evaluators and an LLM-as-judge evaluator, volk-specific quality criteria, the self-healing loop, a command whitelist for safety, history in JSON and Neo4j, GitLab CI integration, a CLI, resource isolation, timeouts and cancellation, a configuration file and parallel execution. The 131 requirement IDs (REQ-102-NNN) pin down details: trials use separate Redis databases per worker; results sync to Neo4j after each scenario; healing triggers only on failure, not timeout; a trial passes only when all evaluators pass and the composite score meets the threshold; a setup hook times out after 30 seconds; and a rate-limited LLM call retries with exponential backoff, 5 retries with a 2 second base.

The code is spread across the harness package, with the most citations in the runner (26 requirements) and the healing loop (16), followed by the models, executor, CLI and history modules, plus the evaluators. The requirements traceability matrix lists each ID. The status line in the spec reads Draft and it tracks 3 files. Measured coverage is 104 of 131 requirements cited by at least one @traces in src/ (79.4%), spread over 16 modules; the module citing the most of them is orchestrata_ultimate/harness/runner (26 requirements). In tests/, 0 requirements are cited by a test-side @traces. The 27 requirements with no citing symbol are mainly the GitLab CI requirements, some volk-specific quality criteria, several error-condition handlers and the harness testing requirements; the behaviour may still exist in code that was never annotated. The spec also leaves five open questions, such as whether snapshot updates are automated and whether healing may change a volk's own source.

Requirements

Checkbox is the state recorded in the requirements checklist; Traced by is the count of src/ symbols whose @traces names the ID.

ID Done Requirement Traced by
REQ-102-001 no Scenarios defined in YAML under harness/scenarios/&lt;volk_name>/ 1
REQ-102-002 no Scenario schema includes: id, volk, description, mode, input, evaluation 2
REQ-102-003 no Scenario schema optionally includes: setup_hook, llm_model, timeout_seconds 1
REQ-102-004 no Scenario YAML validated via Pydantic on load 2
REQ-102-005 no Invalid scenario YAML skipped with error logged; harness continues none
REQ-102-006 no harness list displays all scenarios with volk, mode, description 5
REQ-102-007 no harness run &lt;volk> executes all scenarios for the given volk 3
REQ-102-008 no harness run --scenario &lt;id> executes a single scenario 2
REQ-102-009 no harness run --trials &lt;n> overrides default trial count 1
REQ-102-010 no Each scenario runs exactly 3 independent trials by default 1
REQ-102-011 no Trials use separate git worktrees for isolation 1
REQ-102-012 no Trials use separate Redis DBs per worker (gwN→dbN) none
REQ-102-013 no Trials use UUID-based test_id for Neo4j resource isolation 1
REQ-102-014 no Scenario timeout defaults to 300s; configurable per scenario 2
REQ-102-015 no Scenario passes only if all trials pass 2
REQ-102-016 no Scenario aggregate score is weighted average across evaluators 1
REQ-102-017 no Exit code 0 if all scenarios pass; 1 if any fail 1
REQ-102-018 no Results table printed: scenario, volk, trials, pass/fail, score, time 1
REQ-102-019 no Results appended to harness/history/runs/&lt;YYYY-MM>.json 3
REQ-102-020 no JSON entry includes: scenario_id, volk, trials, scores, timestamp, git_commit 3
REQ-102-021 no JSON writes are atomic (temp file + rename) 1
REQ-102-022 no Corrupt history files handled gracefully (warning + continue) 2
REQ-102-023 no Results synced to Neo4j after each scenario run 1
REQ-102-024 no Neo4j graph includes :Scenario nodes linked to :Volk nodes 2
REQ-102-025 no Neo4j graph includes :Run nodes with scores and timestamps 1
REQ-102-026 no Neo4j graph includes :Regression nodes when snapshot diffs detected 1
REQ-102-027 no Neo4j sync failures are non-fatal (JSON history still saved) 1
REQ-102-028 no Cypher trend queries available: pass rate, regression count, avg score 5
REQ-102-029 no harness report generates HTML from JSON history 3
REQ-102-030 no HTML report includes: total runs, pass rate, avg score, regression count 2
REQ-102-031 no HTML report includes per-volk pass-rate bar chart 2
REQ-102-032 no HTML report includes per-scenario score trends table 2
REQ-102-033 no HTML report includes regression diff previews 2
REQ-102-034 no Healing triggered only on scenario failure (not timeout) 1
REQ-102-035 no Healing max depth configurable (default: 3 hops) 1
REQ-102-036 no Healing disabled if max_healing_hops set to 0 1
REQ-102-037 no Diagnostic packet captures: evaluator results, error, snapshot diff 2
REQ-102-038 no Diagnostic packet sent as CXP ERROR packet to failing volk 1
REQ-102-039 no Diagnostic packet includes scenario_id and test_id for isolation none
REQ-102-040 no Repair packet includes previous hop history 1
REQ-102-041 no Repair packet sent as CXP COMMAND packet 1
REQ-102-042 no Repair strategy extracted from response payload ("retry" or "patch") 2
REQ-102-043 no Escalation packet includes full diagnostic history 1
REQ-102-044 no Escalation packet references reasoning_llm for complex repairs 1
REQ-102-045 no Escalation packet sent as CXP ERROR packet 1
REQ-102-046 no Success: trial marked passed with healing_hops_used set 2
REQ-102-047 no Exhaustion: trial remains failed; diagnostic trace saved to JSON 3
REQ-102-048 no Healing never modifies main working directory (worktree only) 2
REQ-102-049 no Fallback mode when dispatcher unavailable: logs + simulated retry 2
REQ-102-050 no Scenario output serialized to text snapshot on first run 3
REQ-102-051 no Snapshot stored in tests/volk_harness/snapshots/&lt;scenario_id>.snap 2
REQ-102-052 no Snapshot format versioned (# snapshot:v1 header) 1
REQ-102-053 no Subsequent runs compare output against stored snapshot 3
REQ-102-054 no Snapshot mismatch flagged as regression (trial fails) 3
REQ-102-055 no harness snapshot update refreshes baselines to current output 3
REQ-102-056 no Snapshot comparison deterministic (sorted keys, ISO datetimes, base64 bytes) 2
REQ-102-057 no QA Volk: zero lint/syntax errors; false-positive rate < 5% none
REQ-102-058 no CodeDirector: proper patterns, no except/pass, functional style none
REQ-102-059 no Architect: diagrams render, architecture standards respected none
REQ-102-060 no Composite pass threshold: 0.8 (80%) minimum aggregate score 2
REQ-102-061 no GitLab CI job for nightly batch execution at 02:00 UTC none
REQ-102-062 no CI pipeline fails if any volk's overall pass rate < 90% none
REQ-102-063 no CI artifacts: HTML report + JSON history + snapshot diffs none
REQ-102-064 no syntax_check: parses Python with ast.parse; fails on SyntaxError 5
REQ-102-065 no lint_check: runs ruff check; fails on ERROR severity 4
REQ-102-066 no trace_validator: parses traces for unhandled exceptions 6
REQ-102-067 no file_exists: verifies expected output files created 3
REQ-102-068 no Evaluators run concurrently per trial 1
REQ-102-069 no Evaluator crashes don't crash trial (score=0, details=error) 1
REQ-102-070 no llm_judge sends output to DeepSeek v4-pro with structured prompt 2
REQ-102-071 no Judge prompt includes scenario rubric and evaluation criteria 1
REQ-102-072 no Judge temperature=0.0 for consistency 1
REQ-102-073 no Judge returns score (0–100) and categorical feedback 2
REQ-102-074 no Judge failure (API error) returns score=0, passed=False 1
REQ-102-075 no Composite score is weighted average of evaluator scores 1
REQ-102-076 no Evaluator weights configurable per scenario 1
REQ-102-077 no Per-evaluator thresholds configurable per scenario 1
REQ-102-078 no Trial passes only if all evaluators pass AND composite ≥ threshold 1
REQ-102-079 no Worktree created per trial via git worktree add 5
REQ-102-080 no Worktree path validated to be inside repo none
REQ-102-081 no Worktree cleaned up after trial (success or failure) 4
REQ-102-082 no Worktree creation failure falls back to temp directory none
REQ-102-083 no Cleanup failures logged as warnings (non-fatal) 1
REQ-102-084 no Incus container mode available for full sandboxing 7
REQ-102-085 no Incus fallback to worktree when daemon unavailable 1
REQ-102-086 no Incus containers have no outbound network (except API/Redis/Neo4j) 1
REQ-102-087 no Setup hooks defined in harness/scenarios/&lt;volk>/setup.py 1
REQ-102-088 no Setup hooks are async functions accepting HarnessContext 1
REQ-102-089 no Setup hook timeout: 30s default 1
REQ-102-090 no Setup hook failure marks trial FAILED 1
REQ-102-091 no All hook-created resources cleaned up via isolation mechanism 1
REQ-102-092 no Redis DB isolation: worker gwN maps to dbN 1
REQ-102-093 no Neo4j resources prefixed with test_id 1
REQ-102-094 no All Neo4j nodes/relations cleaned up by test_id in teardown none
REQ-102-095 no cxp_inject mode constructs CXP packet with intent + payload 2
REQ-102-096 no Packet dispatched via kernel dispatcher with timeout 2
REQ-102-097 no Packet recipient built from volk registry definition 2
REQ-102-098 no CXP response waited for; timeout marks trial FAILED 1
REQ-102-099 no direct_call mode instantiates volk class directly 3
REQ-102-100 no Method name specified in scenario input (method field) 1
REQ-102-101 no Method args passed as dict (args field) 1
REQ-102-102 no Sync methods offloaded to thread to avoid blocking event loop 1
REQ-102-103 no Missing method or import failure marks trial FAILED 2
REQ-102-104 no Config loaded from harness/config.yaml with env var overlay 3
REQ-102-105 no Env vars prefixed with HARNESS_ override YAML values 1
REQ-102-106 no Redis/KG connection params resolved from the active env profile; required endpoints raise when unset (RUL-003 — no localhost fallback) 1
REQ-102-107 no Default LLM: deepseek-v4-flash; reasoning LLM: deepseek-v4-pro 1
REQ-102-108 no Config directories auto-created on load 1
REQ-102-109 no Scenario YAML schema violation → skip + log error none
REQ-102-110 no Setup hook import failure → trial FAILED + stack trace none
REQ-102-111 no LLM API rate limit (429) → exponential backoff (5 retries, base 2s) none
REQ-102-112 no LLM API auth failure (401/403) → all trials fail immediately none
REQ-102-113 no Redis connection failure → auto-start attempt once none
REQ-102-114 no Neo4j connection failure → history sync skipped (non-fatal) 2
REQ-102-115 no Git worktree creation failure → fallback to temp directory none
REQ-102-116 no Timeout → cancel LLM, kill worktree, mark TIMEOUT, no healing 2
REQ-102-117 no Deterministic evaluator crash → score=ERROR, other evaluators continue 1
REQ-102-118 no Snapshot file corruption → skip comparison + warning 1
REQ-102-119 no Parallel resource collision → new test_id + retry none
REQ-102-120 no Command whitelist enforced: ruff, python, git, orchestrata-tools, black, isort, uv, pytest 3
REQ-102-121 no Whitelist violation → SecurityError + trial FAILED + incident logged 2
REQ-102-122 no DeepSeek API key read from .env only; never logged none
REQ-102-123 no Path traversal blocked; writes restricted to worktree 1
REQ-102-124 no LLM judge prompts templated with clear delimiters 1
REQ-102-125 no Snapshots scanned for secrets before git commit none
REQ-102-126 no Harness self-tests cover: parsing, hooks, evaluators, snapshots, healing, whitelist none
REQ-102-127 no Integration tests use "echo volk" for end-to-end verification none
REQ-102-128 no All harness tests pass under the threadpool runner python scripts/run_tests.py (pytest-xdist banned) none
REQ-102-129 no No session-scope fixtures; no global mutable state none
REQ-102-130 no Deterministic evaluators: 100% true-positive, zero false-positive on valid input none
REQ-102-131 no Snapshot format backward-compatible across versions none

Code that traces this spec

Module Symbols Requirements
orchestrata_ultimate/harness/cli 11 10
orchestrata_ultimate/harness/config 3 4
orchestrata_ultimate/harness/evaluators/file_exists 2 1
orchestrata_ultimate/harness/evaluators/lint 3 1
orchestrata_ultimate/harness/evaluators/llm_judge 4 6
orchestrata_ultimate/harness/evaluators/syntax 3 1
orchestrata_ultimate/harness/evaluators/trace 5 1
orchestrata_ultimate/harness/executor 8 11
orchestrata_ultimate/harness/healing 14 16
orchestrata_ultimate/harness/history 8 9
orchestrata_ultimate/harness/isolation 15 8
orchestrata_ultimate/harness/models 5 12
orchestrata_ultimate/harness/reporting 11 7
orchestrata_ultimate/harness/runner 16 26
orchestrata_ultimate/harness/scenario 6 6
orchestrata_ultimate/harness/snapshots 11 8

Checklists

checklists/constitutional.md

SPEC-102: Constitutional Compliance Checklist — Individual Volk Test Harness

Article I: Human Authority
Article II: Real Infrastructure Only
Article III: Trial Isolation
Article IV: Safety and Sandboxing
Article V: Determinism Where Possible
Article VI: Statistical Significance
Article VII: Transparency and Traceability
Article VIII: Graceful Degradation
Article IX: Dogfooding
Article X: No Main Working Directory Mutation

checklists/requirements.md

The requirement list above comes from this file; 0 of 131 checkbox items are ticked.

Full spec text

Verbatim from specs/102-volk-test-harness/spec.md; headings are pushed down two levels.

Spec 102 — Individual Volk Test Harness

Metadata

Field Value
Spec ID 102
Title Individual Volk Test Harness
Status Draft
Version 0.1.0
Author Orchestrata Core Team
Date 2026-05-26
Target src/orchestrata_ultimate/harness/
Dependencies Spec 097 (Testing Standards), Spec 098 (API Standards), Spec 099 (Security Auth Framework), Spec 101 (Ultimate Architecture), CXP Dispatcher (kernel/dispatcher.py), Neo4jSyncer, SessionController
Stakeholders Core Team, QA Volk, CodeDirector Volk, Architect Volk

Overview

What

The Individual Volk Test Harness is a scenario-driven evaluation system that exercises each volk (agent) individually through real LLM calls with real Redis/Neo4j infrastructure, operating on the orchestrata-ultimate codebase itself (dogfooding). It is an on-demand quality assurance tool, not part of the standard CI/CD test suite.

Why

Individual volks operate autonomously with significant decision-making latitude. Unlike traditional unit tests that validate deterministic functions, volk evaluation requires:

Without this harness, volk quality is only measured indirectly through end-to-end system tests, making it impossible to attribute failures to specific agents.

How
  1. Scenario Definition: Each volk has a directory of YAML scenario files (harness/scenarios/<volk_name>/) describing tasks, expected outcomes, and evaluation criteria
  2. Setup Hooks: Python functions in harness/scenarios/<volk_name>/setup.py prepare the runtime environment (e.g., create temp files, seed Neo4j state)
  3. Execution: For each scenario, the harness runs 3 independent trials using git worktrees for isolation (or Incus containers for full sandboxing)
  4. Dual LLM Strategy:
    • DeepSeek v4-pro (deepseek-v4-pro) for reasoning-heavy scenarios (architecture review, code quality judgment, judge role)
    • DeepSeek v4-flash (deepseek-v4-flash) for fast execution scenarios (syntax checks, trace analysis, bulk operations)
  5. Packet Injection: Scenarios can inject CXP packets into the kernel dispatcher or invoke volk methods directly
  6. Evaluation Pipeline:
    • Deterministic evaluators: Syntax validation, lint checks (ruff), trace analysis, file existence checks
    • LLM-as-judge: For subjective quality (code style, architectural conformance, test quality)
  7. Snapshot Comparison: Results compared against stored snapshots in tests/volk_harness/snapshots/; mismatches flagged as regressions
  8. Self-Healing Loop: On failure, trigger up to 3 repair hops using CXP routing (derived from kernel/dispatcher.py)
  9. History Tracking: Results stored in JSON (committed monthly) and Neo4j (updated every run) for trend analysis
  10. CI Integration: GitLab CI pipeline (not GitHub Actions) for nightly batch runs

User Stories


Terminology

Term Definition
Volk An autonomous agent in the orchestrata-ultimate system (e.g., QA Volk, CodeDirector Volk, Architect Volk)
Scenario A YAML-defined test case describing inputs, expected behavior, and evaluation criteria for a single volk
Trial One execution of a scenario (3 trials per scenario for statistical significance)
Snapshot A serialized, text-based representation of a scenario's output, stored in git for diff-based regression detection
Deterministic Evaluator A non-LLM evaluation function (e.g., syntax check, ruff lint, trace parser) that produces binary pass/fail results
LLM-as-Judge Using a separate LLM call (DeepSeek v4-pro) to evaluate subjective qualities like code style or architectural correctness
Self-Healing Loop An autonomous retry mechanism that, on scenario failure, dispatches repair packets through the CXP kernel (max 3 hops)
Hop One iteration of the self-healing loop (max 3 hops per failure)
Dogfooding The practice of using orchestrata-ultimate's own codebase as the target for volk operations during evaluation
Worktree A git worktree providing an isolated working directory for scenario execution without cloning the repo
CXP Packet A Communication eXchange Protocol packet used for inter-agent messaging in the kernel dispatcher
Packet Injection Directly enqueueing a CXP packet into the kernel's dispatch queue to trigger volk behavior
Direct Method Call Invoking a volk's public method directly (bypassing CXP) for unit-like evaluation

Functional Requirements

FR-001 — Scenario Definition Format

Scenarios SHALL be defined in YAML files under harness/scenarios/<volk_name>/ with the following schema:

FR-002 — Python Setup Hooks

Setup hooks SHALL be defined in harness/scenarios/<volk_name>/setup.py as async functions accepting a HarnessContext parameter. Hooks MAY create temporary files, seed Neo4j data, or configure Redis state. All resources created by hooks SHALL be automatically cleaned up via the isolation fixture mechanism.

FR-003 — Dual LLM Model Strategy

The harness SHALL support two LLM configurations:

FR-004 — CXP Packet Injection Mode

In cxp_inject mode, the harness SHALL construct a CXP packet and enqueue it via the kernel dispatcher. The packet SHALL contain:

FR-005 — Direct Method Call Mode

In direct_call mode, the harness SHALL instantiate the target volk class and invoke the specified method directly. This mode SHALL bypass CXP routing and is intended for fast, deterministic evaluation of specific volk methods.

FR-006 — Three Trials Per Scenario

Each scenario SHALL execute exactly 3 independent trials. Trials SHALL use separate git worktrees (or Incus containers) to ensure no shared mutable state. Results SHALL be compared for consistency across trials.

FR-007 — Snapshot Comparison

After each scenario run, the harness SHALL serialize the output (file contents, traces, evaluation scores) to a text-based snapshot in tests/volk_harness/snapshots/<scenario_id>.snap. On subsequent runs, the harness SHALL compare outputs against stored snapshots and flag any differences as potential regressions. Snapshots SHALL be stored in git.

FR-008 — Deterministic Evaluators

The harness SHALL implement the following deterministic evaluators (no LLM calls):

FR-009 — LLM-as-Judge Evaluator

For subjective quality assessment, the harness SHALL support an llm_judge evaluator that:

FR-010 — Volk-Specific Quality Criteria

Each volk SHALL have defined quality thresholds:

FR-011 — Self-Healing Loop

On scenario failure, the harness SHALL enter a self-healing loop:

  1. Hop 1: Capture failure details (trace, evaluator output, snapshot diff) into a CXP diagnostic packet
  2. Hop 2: Route diagnostic packet to the responsible volk (or a repair volk) via kernel/dispatcher.py routing logic
  3. Hop 3: Apply the repair (code patch, config change, or retry with modified parameters)
  4. Max Depth: 3 hops. If unresolved after 3 hops, mark scenario as FAILED and emit detailed diagnostics. The healing loop SHALL NOT modify the main working directory (only the worktree/container).
FR-012 — Command Whitelist for Safety

Volk executions within the harness SHALL be restricted to the following commands:

FR-013 — History Tracking (JSON)

After each run, the harness SHALL append results to harness/history/runs/<YYYY-MM>.json. Each entry SHALL include: scenario ID, volk name, trial number, pass/fail status, evaluator scores, LLM judge score, execution time, git commit hash, and timestamp.

FR-014 — History Tracking (Neo4j)

After each run, the harness SHALL sync results to Neo4j using Neo4jSyncer. The graph SHALL include:

FR-015 — GitLab CI Integration

The harness SHALL provide a .gitlab-ci.yml job (not GitHub Actions) for nightly batch execution:

FR-016 — Harness CLI Interface

The harness SHALL expose a CLI via python -m orchestrata_ultimate.harness with subcommands:

FR-017 — Resource Isolation

Each trial SHALL run in an isolated environment:

FR-018 — Timeout and Cancellation

Each scenario trial SHALL have a configurable timeout (default: 300s). On timeout:

  1. Cancel the LLM call (if in progress)
  2. Kill the worktree/container process
  3. Mark trial as TIMEOUT
  4. Do NOT enter self-healing loop for timeouts
FR-019 — Configuration File

The harness SHALL read configuration from harness/config.yaml (or harness/config.json) with:

FR-020 — Parallel Execution

Multiple scenarios SHALL be runnable in parallel via the threadpool runner python scripts/run_tests.py (pytest-xdist -n/--dist is banned — it deadlocks this suite). Parallel execution SHALL respect Redis DB isolation and KG test_id prefixes.


Error Conditions

ERR-001 — Scenario YAML Schema Violation

Trigger: Scenario file missing required fields (id, volk, mode, evaluation). Effect: Scenario skipped; error logged; harness continues with remaining scenarios. Resolution: Fix YAML schema; re-run.

ERR-002 — Setup Hook Import Failure

Trigger: setup_hook references a non-existent function or module. Effect: Scenario marked FAILED; stack trace captured; no self-healing attempted for import errors. Resolution: Fix setup.py module path or function name.

ERR-003 — LLM API Rate Limit

Trigger: DeepSeek API returns 429 (rate limit exceeded). Effect: Trial paused with exponential backoff (max 5 retries, base 2s). If all retries exhausted, trial marked FAILED. Resolution: Reduce concurrency or upgrade API tier; retry manually.

ERR-004 — LLM API Authentication Failure

Trigger: Invalid or expired API key (401/403). Effect: All trials for this scenario fail immediately. Harness logs secure error (key masked). Resolution: Update DEEPSEEK_API_KEY in .env.

ERR-005 — Redis Connection Failure

Trigger: Redis container unreachable or misconfigured. Effect: Scenarios requiring Redis fail. Harness attempts auto-start via scripts/start_test_services.py once. Resolution: Verify the active env profile's Redis host/port; start containers via incus/redis-launch.sh.

ERR-006 — Neo4j Connection Failure

Trigger: Neo4j container unreachable or auth failure. Effect: History sync to Neo4j skipped (JSON history still saved). Real-time scenarios using Neo4j fail. Resolution: Verify the active env profile's KG_ROUTING_URI/KG_DATABASE; deploy the test node via incus/orchgraph-test-node-deploy.sh.

ERR-007 — Git Worktree Creation Failure

Trigger: Insufficient disk space, permission denied, or existing worktree conflict. Effect: Trial falls back to temporary directory clone. If fallback fails, trial marked FAILED. Resolution: Free disk space; clean old worktrees via git worktree prune.

ERR-008 — Snapshot Mismatch (Regression)

Trigger: Scenario output differs from stored snapshot. Effect: Trial marked FAILED with detailed diff. Regression node created in Neo4j. Resolution: Investigate diff. If intentional improvement, run harness snapshot update.

ERR-009 — Self-Healing Loop Exhaustion

Trigger: Scenario fails and self-healing loop reaches max 3 hops without resolution. Effect: Scenario marked FAILED. Full diagnostic trace (all 3 hops) saved to harness/history/diagnostics/. Resolution: Manual investigation of diagnostic trace; fix root cause in volk or scenario.

ERR-010 — Command Whitelist Violation

Trigger: Volk execution attempts to run a command outside the whitelist (e.g., rm -rf /, curl to external URL). Effect: Command blocked immediately. Trial marked FAILED with security flag. Incident logged. Resolution: Review volk prompt/instructions; whitelist violation indicates prompt injection or misalignment.

ERR-011 — Timeout During LLM Call

Trigger: LLM response exceeds timeout_seconds. Effect: LLM call cancelled. Trial marked TIMEOUT. Partial response (if any) discarded. Resolution: Increase timeout in scenario YAML; investigate LLM latency (v4-pro is slower than v4-flash).

ERR-012 — Incus Container Launch Failure

Trigger: Incus daemon not running, bridge misconfigured, or image unavailable. Effect: Falls back to git worktree mode. If worktree also fails, trial marked FAILED. Resolution: Start Incus daemon; verify bridge configuration in incus/README.md.

ERR-013 — Deterministic Evaluator Crash

Trigger: Bug in evaluator code (e.g., ast.parse on non-Python file, ruff config missing). Effect: Evaluator score marked as ERROR. Other evaluators continue. Trial may still pass if remaining evaluators succeed. Resolution: Fix evaluator code or scenario input.

ERR-014 — Snapshot File Corruption

Trigger: Stored snapshot file is not valid UTF-8 or has been manually edited to invalid format. Effect: Snapshot comparison skipped for this scenario; warning logged. Resolution: Delete corrupted snapshot; re-run to regenerate.

ERR-015 — Parallel Execution Resource Conflict

Trigger: Two trials share a Redis DB or Neo4j namespace due to test_id collision or worker misconfiguration. Effect: Non-deterministic failures in both trials. Harness detects collision via pre-flight check and retries with new test_id. Resolution: Verify worker-to-DB mapping; ensure UUID-based test_id generation.


API Contracts

HarnessContext
@dataclass
class HarnessContext:
    """Runtime context passed to setup hooks and evaluators."""
    scenario_id: str
    volk_name: str
    trial_number: int
    test_id: str  # UUID for resource isolation
    worktree_path: Path
    redis_db: int  # Worker-isolated Redis DB number
    neo4j_prefix: str  # test_id prefix for Neo4j resources
    config: HarnessConfig
    logger: logging.Logger
HarnessConfig
@dataclass
class HarnessConfig:
    """Harness configuration loaded from harness/config.yaml."""
    default_llm: str = "deepseek-v4-flash"
    reasoning_llm: str = "deepseek-v4-pro"
    snapshot_dir: Path = Path("tests/volk_harness/snapshots")
    history_dir: Path = Path("harness/history/runs")
    diagnostics_dir: Path = Path("harness/history/diagnostics")
    command_whitelist: list[str] = field(default_factory=lambda: [
        "ruff", "python", "git", "orchestrata-tools", "black", "isort", "uv", "pytest"
    ])
    max_healing_hops: int = 3
    default_timeout: int = 300
    trials_per_scenario: int = 3
    redis_host: str = "localhost"
    redis_port: int = 6379
    neo4j_uri: str = "bolt://localhost:7687"
Scenario Definition (Pydantic Model)
class Scenario(BaseModel):
    id: str
    volk: str
    description: str
    mode: Literal["cxp_inject", "direct_call"]
    input: dict[str, Any]
    setup_hook: str | None = None
    evaluation: list[EvaluatorConfig]
    llm_model: str | None = None
    timeout_seconds: int = 300

class EvaluatorConfig(BaseModel):
    name: str  # e.g., "syntax_check", "llm_judge"
    params: dict[str, Any] = Field(default_factory=dict)
    weight: float = 1.0  # For composite scoring
    threshold: float = 0.0  # Minimum score to pass
HarnessRunner
class HarnessRunner:
    """Main entry point for executing scenarios."""

    def __init__(self, config: HarnessConfig) -> None:
        ...

    async def run_scenario(
        self,
        scenario: Scenario,
        trials: int = 3,
    ) -> ScenarioResult:
        """Run a scenario for N trials and return aggregated results."""
        ...

    async def run_volk(
        self,
        volk_name: str,
        trials: int = 3,
    ) -> list[ScenarioResult]:
        """Run all scenarios for a given volk."""
        ...

    def list_scenarios(self, volk_name: str | None = None) -> list[Scenario]:
        """List all loaded scenarios, optionally filtered by volk."""
        ...
ScenarioResult
@dataclass
class ScenarioResult:
    scenario_id: str
    volk_name: str
    trials: list[TrialResult]
    aggregate_score: float  # Weighted average across evaluators
    passed: bool  # True if all trials pass and no snapshot regressions
    execution_time_ms: int
    git_commit: str
    timestamp: datetime

@dataclass
class TrialResult:
    trial_number: int
    passed: bool
    evaluator_results: list[EvaluatorResult]
    llm_judge_score: float | None
    snapshot_diff: str | None  # None if no diff or no snapshot
    healing_hops_used: int
    execution_time_ms: int
    error: str | None

@dataclass
class EvaluatorResult:
    name: str
    passed: bool
    score: float
    details: str
Evaluator Interface
class Evaluator(ABC):
    """Base class for deterministic and LLM evaluators."""

    @abstractmethod
    async def evaluate(
        self,
        output: Any,
        context: HarnessContext,
        config: EvaluatorConfig,
    ) -> EvaluatorResult:
        ...

class SyntaxEvaluator(Evaluator): ...
class LintEvaluator(Evaluator): ...
class TraceEvaluator(Evaluator): ...
class LLMJudgeEvaluator(Evaluator): ...
SelfHealingLoop
class SelfHealingLoop:
    """Manages autonomous repair attempts on scenario failure."""

    def __init__(
        self,
        dispatcher: CXP_Dispatcher,  # From kernel/dispatcher.py
        max_hops: int = 3,
    ) -> None:
        ...

    async def heal(
        self,
        failure: TrialResult,
        context: HarnessContext,
    ) -> HealingResult:
        """Attempt to heal a failed trial. Returns result after max_hops or success."""
        ...

@dataclass
class HealingResult:
    success: bool
    hops_used: int
    diagnostics: list[HopDiagnostic]
    final_trial_result: TrialResult | None

@dataclass
class HopDiagnostic:
    hop_number: int
    action: str
    packet_sent: CXPPacket
    response: CXPPacket | None
    error: str | None

Security Requirements

SEC-001 — Command Execution Whitelist

The harness SHALL enforce a strict command whitelist (FR-012). Any subprocess invocation by a volk during harness execution MUST be validated against this list. Violations SHALL be logged as security incidents.

SEC-002 — API Key Isolation

DeepSeek API keys SHALL be read from environment variables (.env) only. Keys SHALL never be logged, stored in scenario files, or committed to git. The harness SHALL mask API keys in all log output.

SEC-003 — Network Isolation (Incus Mode)

When running in Incus container mode, containers SHALL have no outbound network access except to:

SEC-004 — Git Push Prevention

The git command whitelist SHALL exclude git push, git push --force, and any git operation that modifies remote state. Harness worktrees SHALL be configured with remote.origin.push= NOTHING.

SEC-005 — File System Sandboxing

Volk operations in the harness SHALL be restricted to the worktree directory. Access to paths outside the worktree (e.g., /etc, ~/.ssh, parent directories) SHALL be blocked via chroot (Incus) or path validation (worktree mode).

SEC-006 — Secret Scanning in Snapshots

Before committing snapshots to git, the harness SHALL scan for potential secrets (API keys, passwords, tokens) using git-secrets or equivalent. Matches SHALL block the commit and alert the operator.

SEC-007 — LLM Prompt Injection Mitigation

LLM-as-judge prompts SHALL be constructed with clear delimiters and explicit instructions to prevent the evaluated output from hijacking the judge's reasoning. System prompts SHALL be templated and validated.


Dependencies

DEP-001 — DeepSeek API

Requires active DeepSeek API account with access to deepseek-v4-pro and deepseek-v4-flash models. API key via DEEPSEEK_API_KEY environment variable.

DEP-002 — Redis (Incus Container)

Redis container must be running for scenarios requiring queue/state operations. Auto-start attempted via scripts/start_test_services.py. Configuration from the active env profile.

DEP-003 — Operational KG (Incus Memgraph node)

The operational KG (Memgraph, orchkg database) must be running for history sync and graph-based scenarios. Configuration from the active env profile.

DEP-004 — Git Worktree Support

Git version >= 2.25 required for worktree operations. git worktree command must be available.

DEP-005 — Incus (Optional)

Incus daemon required only for full container sandboxing. Worktree mode does not require Incus.

DEP-006 — Python 3.14+

Harness code uses Python 3.14 features (e.g., improved typing syntax, free-threading support).

DEP-007 — Existing Volk Implementations

The harness evaluates volks in src/orchestrata_ultimate/agents/volks/. Each volk must implement the expected interface for its scenarios.

DEP-008 — CXP Kernel Dispatcher

src/orchestrata_ultimate/kernel/dispatcher.py must be operational for cxp_inject mode and self-healing loop routing.

DEP-009 — SessionController

src/orchestrata_ultimate/session/session.py for session tracking and changelog generation during harness runs.

DEP-010 — ruff, black, mypy

Required for deterministic evaluators. Must be installed in the virtual environment (uv sync --dev).


Testing Requirements

TST-001 — Harness Self-Tests

The harness itself SHALL have tests in tests/harness/ covering:

TST-002 — Mock LLM Mode

The harness SHALL support a --mock-llm flag (or config option) that replaces real LLM calls with deterministic responses for fast testing of harness infrastructure. Mock responses SHALL be defined in tests/harness/fixtures/mock_llm_responses.yaml.

TST-003 — Integration Tests

Integration tests SHALL verify end-to-end harness execution with:

TST-004 — Parallel Safety

Harness tests SHALL pass under the threadpool runner python scripts/run_tests.py (pytest-xdist -n/--dist is banned). No session-scope fixtures. No global mutable state. Use test_id for all resource names.

TST-005 — Incus Fallback Test

Test that worktree mode is correctly used when Incus is unavailable.

TST-006 — Deterministic Evaluator Accuracy

Each deterministic evaluator SHALL be tested with:

TST-007 — Snapshot Format Stability

Snapshots SHALL use a stable, versioned text format. Tests SHALL verify backward compatibility with existing snapshot files.

TST-008 — Performance Benchmarks

The harness SHALL include performance tests measuring:

TST-009 — Security Test Suite

Security tests SHALL verify:

TST-010 — Failure Injection Tests

The harness SHALL be tested with simulated failures:


Open Questions

  1. Should the harness support evaluating volk-to-volk interactions (multi-agent scenarios), or strictly individual volks?
  2. Should snapshot updates be fully automated (on CI pass), or require human approval?
  3. What is the retention policy for JSON history files? (Propose: 12 months local, indefinite in Neo4j)
  4. Should the self-healing loop be able to modify the volk's own source code, or only the worktree?
  5. Do we need a dedicated "Harness Volk" to manage scenario execution, or should it be imperative code?