Orchestrata Ultimate / Specs / 031-qa-volk
031-qa-volk: QA Volk (U:Qa)
The QA Volk (U:Qa) is the quality assurance agent in the Orchestrata multi-agent pipeline. It receives code artifacts from U:Cd (CodeDirector) and performs a full review-and-test pipeline: deterministic auto-fixing, three sequential review gates, LLM-based code review against a 31-item Google-style checklist, test generation, test execution, and fix delegation back to U:Cd on any failure. The cycle runs without a cap until all issues are resolved (G226), with escalating context on repeat...
At a glance
| Item | Value |
|---|---|
| Spec directory | specs/031-qa-volk/ |
| Status line in the spec | Implemented |
| Requirement IDs defined | 55 |
With a @traces citation in src/ |
42 (76.4%) |
With a @traces citation in tests/ |
6 (10.9%) |
| Tracked files | 7 |
| RTM page | 031-qa-volk |
Reading this spec
The QA Volk (U:Qa) is the quality assurance agent of the pipeline. It receives code artifacts from the CodeDirector and runs a full review-and-test pipeline: deterministic auto-fixing, three sequential review gates, an LLM code review against a 31-item Google-style checklist, test generation and test execution. The spec's reasoning is that LLM-generated code has predictable defects (wrong async idioms, aioredis API misuse, relative imports, hardcoded Redis hosts, missing stdlib imports) that are fixed mechanically before an LLM review spends tokens on them, that structural gates must be deterministic rather than delegated to an LLM, and that test generation is separate from code generation so one agent cannot mark its own work complete.
The pipeline has nine steps. First, 13 deterministic AST and regex fixers run. Gate 1 checks syntax (every file compiles under Python 3.13). Gate 2 runs flake8 critical codes (E9xx and F8xx). Gate 3 is the checklist of traceability, import order, docstring and structure checks. Import validation imports each source module in the workspace virtual environment to catch hallucinated APIs. The LLM review follows, then test generation (a pytest suite with zero mocking, @traces decorators and real infrastructure fixtures) and test execution. Any failure bounces back to U:Cd; on cycle 3 and later, the history of failed attempts is included so the same broken strategy is not repeated. When everything passes, the work is committed in git and forwarded to U:Cp with the subject compliance_check. The pipeline does not end until tests pass. Requirement IDs use the REQ-031- prefix.
In the code, the largest tracers are orchestrata_ultimate/agents/volks/qa/volk and orchestrata_ultimate/agents/volks/qa/_autofix, with the fixers in orchestrata_ultimate/verification/autofix/redis_fixes and orchestrata_ultimate/verification/autofix/import_fixes, and the checks in orchestrata_ultimate/agents/volks/codedirector/review_checks. The per-requirement view is on the RTM page.
The spec's status line reads Implemented. It tracks 7 files and defines 55 requirement IDs. The full text follows below.
Measured coverage is 42 of 55 requirements cited by at least one @traces in src/ (76.4%), spread over 9 modules; the module citing the most of them is orchestrata_ultimate/agents/volks/qa/volk (19 requirements). In tests/, 6 requirements are cited by a test-side @traces.
Coverage gaps: 13 requirements have no citing symbol. The largest untraced groups are REQ-031-* (13). Untraced means no @traces names the ID; the behaviour may still exist in code that was never annotated. Test-side citations are thinner than code-side ones (6 against 42).
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-031-001 |
no | _autofix_aioredis() rewrites import aioredis to import redis.asyncio as aioredis |
3 |
REQ-031-002 |
no | _autofix_aioredis() rewrites aioredis.from_url() to redis.asyncio.from_url() |
3 |
REQ-031-003 |
no | _autofix_sync_redis() rewrites synchronous redis.Redis() to redis.asyncio.Redis() in async contexts |
4 |
REQ-031-004 |
no | _autofix_f821_datetime() adds from datetime import datetime, timedelta when datetime is used as a bare name without an import |
5 |
REQ-031-005 |
no | _autofix_missing_stdlib_imports() detects missing stdlib imports by scanning for known stdlib names and adds the correct import statements |
4 |
REQ-031-006 |
no | _autofix_missing_barename_imports() adds missing third-party imports for known packages used as bare names |
5 |
REQ-031-007 |
no | _autofix_xadd_dict() serializes nested dict values in xadd calls using json.dumps() to produce flat string fields |
2 |
REQ-031-008 |
no | _autofix_hset_dict() rewrites hset(name, mapping={...}) values to JSON-serialized strings |
2 |
REQ-031-009 |
no | _autofix_redis_decode() adds decode_responses=True to Redis client constructors that omit it |
2 |
REQ-031-010 |
no | _autofix_redis_host() replaces hardcoded "localhost" in Redis constructors with core.redis_factory.resolve_redis_host() (raises when unset — RUL-003) |
5 |
REQ-031-011 |
no | _autofix_relative_imports() rewrites from .module import X to absolute import paths |
5 |
REQ-031-012 |
no | _autofix_line_length() splits lines exceeding 80 characters at logical boundaries without breaking semantics |
3 |
REQ-031-013 |
no | _autofix_import_order() reorders imports to: stdlib first, third-party second, local last, separated by blank lines |
3 |
REQ-031-014 |
no | _autofix_unused_imports() removes import statements for names that are never referenced in the file body |
1 |
REQ-031-015 |
no | All 13 auto-fixers operate on all .py files in self.workspace |
11 |
REQ-031-016 |
no | Auto-fix pass runs before Gate 1 (Syntax) on every cycle, including test-fix return cycles | 2 |
REQ-031-017 |
no | review_gate_syntax() (from review_checks.py) compiles every .py file in files_created using Python AST |
1 |
REQ-031-018 |
no | review_gate_syntax() returns a list of (code, filepath, description) tuples for each syntax error |
1 |
REQ-031-019 |
no | Gate 1 failure immediately calls _bounce_for_fix() with label "GATE 1 FAIL: Syntax errors" |
1 |
REQ-031-020 |
no | Gate 1 failure skips Gate 2, Gate 3, and all subsequent pipeline phases | 1 |
REQ-031-021 |
no | review_gate_lint() (from review_checks.py) runs flake8 with critical error codes on all files_created |
2 |
REQ-031-022 |
no | Gate 2 targets E9xx (syntax at runtime) and F8xx (undefined names, unused imports) flake8 codes | none |
REQ-031-023 |
no | Gate 2 failure calls _bounce_for_fix() with label "GATE 2 FAIL: Lint/style errors" |
1 |
REQ-031-024 |
no | Gate 2 failure skips Gate 3 and all subsequent pipeline phases | 1 |
REQ-031-025 |
no | review_gate_checklist() (from review_checks.py) runs deterministic structural checks on all files_created |
1 |
REQ-031-026 |
no | Checklist gate verifies: traceability decorators present, import order correct, public functions have docstrings, no relative imports | 4 |
REQ-031-027 |
no | Gate 3 failure calls _bounce_for_fix() with label "GATE 3 FAIL: Checklist violations" |
1 |
REQ-031-028 |
no | get_fix_instructions() converts issue tuples to a structured, human-readable fix prompt |
1 |
REQ-031-029 |
no | All three gates log status to stdout: " [U:Qa] Gate N/3: Syntax/Lint/Checklist..." and " [U:Qa] Gate N/3: PASS" | 1 |
REQ-031-030 |
no | When all three gates return empty lists, the pipeline proceeds to import validation | 2 |
REQ-031-031 |
no | CODE_REVIEW_PROMPT contains exactly 31 numbered checklist items covering all specified categories | none |
REQ-031-032 |
no | Items 1-6 cover Correctness: IMPORTS, NO_MOCKING, API_CORRECTNESS, FILE_COMPLETENESS, ENTRY_POINT, DEPENDENCY_DECLARATION | none |
REQ-031-033 |
no | Items 7-9 cover Design: DESIGN, COMPLEXITY, NO_DUPLICATION | none |
REQ-031-034 |
no | Items 10-12 cover Functions: FUNCTION_LENGTH, FUNCTION_ARGS, NO_PLACEHOLDER | none |
REQ-031-035 |
no | Items 13-14 cover Error Handling: ERROR_HANDLING, EXCEPTIONS | none |
REQ-031-036 |
no | Items 15-20 cover: RESOURCE_MANAGEMENT, NAMING, TYPE_HINTS, DEFAULT_VALUES, DOCSTRINGS, COMMENTS | none |
REQ-031-037 |
no | Items 21-29 cover Style and Python Best Practices: LINE_LENGTH, FORMATTING, STRINGS, MUTABLE_GLOBAL_STATE, COMPREHENSIONS, TRUE_FALSE, ITERATORS, DECORATORS, CONCURRENCY | none |
REQ-031-038 |
no | Items 30-31 cover SECURITY and TESTS | none |
REQ-031-039 |
no | LLM review call uses temperature=0.0, volk="U:Qa", and injects self._graph_context |
1 |
REQ-031-040 |
no | _parse_review_verdict() extracts "PASS" or "FAIL" from the REVIEW_VERDICT: line in the LLM response |
2 |
REQ-031-041 |
no | _parse_review_issues() extracts actionable issues from the ISSUES: block when verdict is FAIL |
2 |
REQ-031-042 |
no | FAIL verdict triggers _bounce_for_fix() to U:Cd with parsed issues |
1 |
REQ-031-043 |
no | Review runs on every cycle, including when packet carries from_test_fix=True (G226) |
2 |
REQ-031-044 |
no | QA_SYSTEM_PROMPT forbids unittest.mock, MagicMock, patch, AsyncMock, Mock imports | none |
REQ-031-045 |
no | QA_SYSTEM_PROMPT forbids custom Mock/Fake/Stub/Dummy classes | none |
REQ-031-046 |
no | QA_SYSTEM_PROMPT requires pytest framework (no unittest.TestCase) | none |
REQ-031-047 |
no | QA_SYSTEM_PROMPT forbids asyncio.Awaitable and asyncio.Coroutine; requires collections.abc.Awaitable | none |
REQ-031-048 |
no | QA_SYSTEM_PROMPT requires @traces decorator on every test function |
1 |
REQ-031-049 |
no | Test prompt includes 6-phase structure: Analyze, Plan, Infrastructure Rules, Source Code, Output Constraints, Traceability | 2 |
REQ-031-050 |
no | Generated tests use real Redis with the host from core.redis_factory.resolve_redis_host() (raises when unset — RUL-003) and db=15 |
2 |
REQ-031-051 |
no | _extract_and_write_tests() parses TEST_FILE blocks from LLM response and writes to self.workspace |
2 |
REQ-031-052 |
no | _validate_no_mocks() scans written test files for forbidden mock patterns |
3 |
REQ-031-053 |
no | _retry_without_mocks() re-runs LLM generation with anti-mock instruction when mock usage is detected |
3 |
REQ-031-054 |
no | Each test file is capped at MAX 120 lines; longer output is split across multiple files | 1 |
REQ-031-055 |
no | _run_tests() executes pytest in self.workspace using workspace venv Python and returns (passed: bool, output: str) |
10 |
Code that traces this spec
Checklists
checklists/README.md
QA Volk (U:Qa) Checklists
Project: Orchestrata QA Volk (Spec 031) Component: U:Qa (QA Volk) Status: Implemented Owner: Mohamed Package: orchestrata-qa
Overview
The QA Volk (U:Qa) is the quality assurance agent in the Orchestrata multi-agent code generation pipeline. It receives code artifacts from U:Cd (CodeDirector) via CXP review_and_test packets and executes a full review-and-test pipeline before forwarding to U:Cp (Compliance Volk).
The pipeline is deterministic-first: 13 auto-fixers correct mechanical LLM defects before any gate runs; three sequential gates (Syntax, Lint, Checklist) catch structural issues without spending LLM tokens; LLM review evaluates the code against a 31-item Google-style checklist; test generation produces a zero-mocking pytest suite; test execution validates real behavior. Any failure bounces back to U:Cd with escalating context (G229). The loop runs without a cap (G226) until all gates pass and all tests pass.
Checklist Summary
| Checklist | Total Items | Completed | Progress |
|---|---|---|---|
| Requirements | 55 | 0 | 0% |
| Constitutional Compliance | 20 | 0 | 0% |
| Testing Plan | 55 | 0 | 0% |
| TOTAL | 130 | 0 | 0% |
Key Components
1. QaVolk Class
- Alias: U:Qa
- Role: "QA Engineer"
- Extends: BaseVolk
- Entry:
process()-- routesreview_and_testto_handle_review() - Package:
orchestrata.volks.qa.volk - LOC: 2,914 (volk.py) + 1 (init.py) = 2,915 total
2. Auto-Fix Pass (13 fixers)
Deterministic, zero-LLM corrections run before all gates:
| Fixer | Defect Corrected |
|---|---|
_autofix_aioredis |
aioredis import and from_url API |
_autofix_sync_redis |
Synchronous redis.Redis in async code |
_autofix_f821_datetime |
Missing datetime import |
_autofix_xadd_dict |
Nested dicts in xadd calls |
_autofix_hset_dict |
Nested dicts in hset mapping |
_autofix_redis_decode |
Missing decode_responses=True |
_autofix_missing_stdlib_imports |
Missing stdlib imports by name |
_autofix_missing_barename_imports |
Missing third-party imports |
_autofix_redis_host |
Hardcoded "localhost" in Redis |
_autofix_relative_imports |
Relative import paths |
_autofix_line_length |
Lines exceeding 80 chars |
_autofix_import_order |
Out-of-order import blocks |
_autofix_unused_imports |
Unreferenced import statements |
3. Three-Gate Review Pipeline (G227)
Sequential deterministic gates; first failure bounces immediately:
| Gate | Mechanism | Bounce Label |
|---|---|---|
| Gate 1: Syntax | review_gate_syntax() -- AST compile check |
"GATE 1 FAIL: Syntax errors" |
| Gate 2: Lint | review_gate_lint() -- E9xx/F8xx flake8 |
"GATE 2 FAIL: Lint/style errors" |
| Gate 3: Checklist | review_gate_checklist() -- structural rules |
"GATE 3 FAIL: Checklist violations" |
Note: review_gate_syntax, review_gate_lint, review_gate_checklist, and get_fix_instructions are imported from orchestrata.volks.codedirector.review_checks (SPEC-029 package).
4. LLM Code Review
- Prompt: CODE_REVIEW_PROMPT -- 31-item Google-style checklist
- Temperature: 0.0
- Client:
call_llm()from SPEC-028 with graph context injection - Verdict: PASS/FAIL extracted from REVIEW_VERDICT: line
- On FAIL: issues extracted, bounce to U:Cd via
_bounce_for_fix()
5. Test Generation
- Prompt: QA_SYSTEM_PROMPT -- zero mocking, @traces required, Python 3.13 idioms
- Phase structure: Analyze, Plan, Infrastructure Rules, Source Code, Output Constraints, Traceability
- Extraction:
_extract_and_write_tests()-- parses TEST_FILE blocks - Mock detection:
_validate_no_mocks()+_retry_without_mocks()on violation
6. Test Execution
- Runner:
_run_tests()-- pytest in workspace venv - On pass:
_git_commit(), forwardcompliance_checkto U:Cp - On fail:
_extract_test_failures(), bouncefix_issuesto U:Cd withfrom_test_fix=True - G226: No cycle cap
7. Escalating Fix Context (G229)
| Cycle | Additional Context Injected |
|---|---|
| 1-2 | Current issues + fix instructions only |
| 3+ | History of last 3 failed attempts |
| 5+ | Root-cause analysis + strategy change instructions |
| 8+ | Full file contents for affected files |
8. Escalation Routing
| Condition | Target | Subject |
|---|---|---|
| Any gate fails | U:Cd | fix_issues |
| Test suite fails | U:Cd | fix_issues (with from_test_fix=True) |
| All gates pass + tests pass | U:Cp | compliance_check |
Checklist Files
1. requirements.md
Functional requirements organized by user story:
- US-031-001: Deterministic Auto-Fix Pass (REQ-031-001 to REQ-031-016, 16 items)
- US-031-002: Three-Gate Sequential Review Pipeline (REQ-031-017 to REQ-031-030, 14 items)
- US-031-003: LLM-Based Code Review (REQ-031-031 to REQ-031-043, 13 items)
- US-031-004: Test Generation (REQ-031-044 to REQ-031-054, 11 items)
- US-031-005 to 007: Test Execution, Escalation, Handoff (REQ-031-055, 1 item)
2. constitutional.md
Compliance with the Orchestrata constitutional framework (20 items):
- Article I: Agent Autonomy (5 items) -- auto-fixers scope, review vs override
- Article II: Prolog Governance (4 items) -- gates are rules, not policy
- Article VI: Python 3.14t (3 items) -- async methods, 3.13 idioms in prompts
- Article VII: No Mocking (4 items) -- QA_SYSTEM_PROMPT, _validate_no_mocks, CODE_REVIEW_PROMPT
- Article VIII: Observability (4 items) -- gate logging, test summary, counters in packets
3. testing.md
Comprehensive testing strategy (55 tests):
- Auto-Fixer Tests (15): One test per fixer category
- Review Gate Tests (12): Pass/fail logic per gate + bounce structure
- LLM Review Parsing Tests (8): Verdict extraction, issue extraction, prompt completeness
- Test Generation Tests (10): Prompt rules, file extraction, mock detection
- Escalation Context Tests (6): G229 boundary conditions and history tracking
- Integration Tests (4): Full pipeline end-to-end
Performance Targets
| Metric | Target |
|---|---|
| Auto-fix pass duration | <2 seconds for 10-file workspace |
| Gate 1 (Syntax) | <1 second per file |
| Gate 2 (Lint) | <5 seconds for 10-file workspace |
| Gate 3 (Checklist) | <3 seconds for 10-file workspace |
| LLM review call | Governed by SPEC-028 retry/backoff |
| Test generation LLM call | Governed by SPEC-028 retry/backoff |
| Test execution | Bounded by pytest timeout in workspace |
Integration Points
Upstream
- U:Cd (CodeDirector) -- sends
review_and_testpackets withfiles_created,task_summary,project_dir - SPEC-029 (review_checks.py) -- provides
review_gate_syntax,review_gate_lint,review_gate_checklist,get_fix_instructions - SPEC-028 (LLM Client) -- provides
call_llm()for code review and test generation
Downstream
- U:Cd (CodeDirector) -- receives
fix_issuespackets on any gate or test failure - U:Cp (Compliance Volk) -- receives
compliance_checkpacket on full pipeline success
Governance Rules Referenced
| Rule | Description |
|---|---|
| G100 | Do NOT regenerate test files on test-fix return -- re-run existing ones |
| G218 | Capture requirement IDs from packet payload for @traces injection |
| G226 | No cycle cap -- review loops until ALL issues resolved |
| G227 | Three-gate sequential pipeline: Syntax, Lint, Checklist |
| G229 | Fix attempt history tracking for escalation context |
References
- SPEC-029: CodeDirector Volk -- review_checks.py source
- SPEC-028: LLM Client -- call_llm facade
- SPEC-004: CXP Protocol -- packet format
- SPEC-005: Multi-Agent Coordination -- pipeline topology
Last Updated: 2026-04-04 Version: 1.0.0 Maintained By: Mohamed
checklists/constitutional.md
QA Volk (U:Qa) -- Constitutional Compliance
Component: U:Qa (QA Volk) Spec: 031-qa-volk Status: Compliance Review Total Compliance Items: 20
Overview
This document tracks compliance of the QA Volk (U:Qa) with the Orchestrata constitutional framework. U:Qa operates at the quality gate of the code generation pipeline: it enforces correctness, tests real behavior, and escalates failures deterministically. Constitutional compliance focuses on autonomy preservation (it reviews but does not override), governance separation (gates are deterministic rules, not LLM opinions), real-system testing (zero mocking), audit trail completeness, and graceful degradation when LLM or infrastructure is unavailable.
Article I: Agent Autonomy
Principle: Volks retain autonomy; QA enforces standards without overriding agent decisions.
Compliance Requirements
- [ ] CONST-031-001: U:Qa reviews code and delegates fixes -- it does not modify U:Cd output directly (except auto-fixers for mechanical defects)
- [ ] CONST-031-002: Auto-fixers are limited to mechanical, unambiguous transformations (API rewrites, import cleanup) -- they do not change logic or design
- [ ] CONST-031-003: Review gates produce issue lists and bounce packets; U:Cd retains autonomy to decide how to fix each issue
- [ ] CONST-031-004: QA_SYSTEM_PROMPT is a constraint on test generation style, not a command to U:Cd
- [ ] CONST-031-005:
_bounce_for_fix()provides fix instructions as guidance, not direct code edits
Priority: Critical Verification: Code review of auto-fixer methods
Article II: Prolog as Single Source of Truth
Principle: All governance rules are in Prolog; QA does not duplicate or override governance logic.
Compliance Requirements
- [ ] CONST-031-006: Review gates (syntax, lint, checklist) enforce Python language and style rules -- not PAM++ policy decisions
- [ ] CONST-031-007: Escalation routing (fix_issues to U:Cd, compliance_check to U:Cp) follows pipeline topology defined outside QA
- [ ] CONST-031-008: QA does not evaluate Prolog predicates directly -- it delegates compliance to U:Cp via the compliance_check packet
- [ ] CONST-031-009: G226 (no cycle cap) and G229 (escalating context) are implemented as code logic, not duplicated Prolog rules
Priority: High Verification: Confirm no pyswip calls in qa/volk.py
Article VI: Python 3.14t Implementation
Principle: All Orchestrata code targets Python 3.14t (free-threaded).
Compliance Requirements
- [ ] CONST-031-010: QaVolk uses
async defforprocess(),_handle_review(),_handle_test_gen(),_handle_test_rerun(),_run_tests(),_retry_without_mocks() - [ ] CONST-031-011: QA_SYSTEM_PROMPT explicitly prohibits
asyncio.Awaitable/asyncio.Coroutineand requirescollections.abc.Awaitablefor Python 3.13+ compatibility - [ ] CONST-031-012:
_autofix_f821_datetime()targets the Python 3.13datetimebare-name usage pattern -- a known LLM defect under this Python version
Priority: Critical Verification: Runtime import check in CI
Article VII: Testing Without Mocks
Principle: All tests use real implementations; mocking is not permitted.
Compliance Requirements
- [ ] CONST-031-013: QA_SYSTEM_PROMPT contains an explicit ZERO mocking rule covering unittest.mock, MagicMock, patch, AsyncMock, Mock, and custom Mock/Fake/Stub/Dummy classes
- [ ] CONST-031-014:
_validate_no_mocks()scans generated test files for forbidden patterns and triggers retry on detection - [ ] CONST-031-015: CODE_REVIEW_PROMPT item NO_MOCKING (item 2) explicitly fails any source or test file using mock objects
- [ ] CONST-031-016: Generated test fixtures use real Redis connections via
core.redis_factory.resolve_redis_host()(raises when unset — RUL-003; endpoints come from the active env profile), real filesystem viatmp_path, and real process execution -- no mocked infrastructure
Priority: Critical
Verification: NO_MOCKING checklist item + _validate_no_mocks() coverage
Article VIII: Metrics and Observability
Principle: All components emit observable state; QA must be inspectable.
Compliance Requirements
- [ ] CONST-031-017: QaVolk prints cycle progress to stdout: " [U:Qa] Gate N/3: ..." for all three gates
- [ ] CONST-031-018: Test result summary is printed after every test run (pass or fail count)
- [ ] CONST-031-019: Individual FAILED test names are printed for visibility in conversation transcripts
- [ ] CONST-031-020:
review_cycleand_test_fix_countcounters are included in bounce packet payloads for downstream observability
Priority: High Verification: Conversation transcript inspection from spike iterations
Summary
| Article | Items | Status |
|---|---|---|
| I -- Agent Autonomy | 5 | To verify |
| II -- Prolog Governance | 4 | To verify |
| VI -- Python 3.14t | 3 | To verify |
| VII -- No Mocking | 4 | To verify |
| VIII -- Observability | 4 | To verify |
| TOTAL | 20 |
checklists/requirements.md
The requirement list above comes from this file; 0 of 55 checkbox items are ticked.
checklists/testing.md
QA Volk (U:Qa) -- Testing Plan
Component: U:Qa (QA Volk) Spec: 031-qa-volk Status: Test Planning Phase Total Test Cases: 55
Overview
This document defines the comprehensive testing strategy for the QA Volk (U:Qa). All tests follow the strict no-mocking policy: real file I/O in tmp_path fixtures, real flake8 subprocess invocations, real pytest executions, and real Redis where infrastructure tests are involved. Tests verify the QA pipeline from auto-fixers through gate logic, LLM review parsing, test extraction, and CXP packet construction.
Test Categories Summary
| Category | Test Count | Purpose | Priority |
|---|---|---|---|
| Auto-Fixer Tests | 15 | Verify each auto-fixer transforms code correctly | Critical |
| Review Gate Tests | 12 | Gate pass/fail logic and bounce packet construction | Critical |
| LLM Review Parsing Tests | 8 | Verdict and issue extraction from CODE_REVIEW_PROMPT responses | High |
| Test Generation Tests | 10 | QA_SYSTEM_PROMPT output parsing and mock detection | Critical |
| Escalation Context Tests | 6 | G229 escalating context across fix cycles | High |
| Integration Tests | 4 | Full pipeline from CXP packet to bounce or handoff | High |
| TOTAL | 55 |
Test Infrastructure
Workspace Fixture
All tests that invoke auto-fixers or gates use a real temporary workspace:
@pytest.fixture
def workspace(tmp_path):
ws = tmp_path / "project"
ws.mkdir()
return ws
QaVolk Fixture
@pytest.fixture
def qa(workspace):
volk = QaVolk()
volk.workspace = str(workspace)
return volk
Minimal CXP Packet
def make_packet(workspace, files, summary="test task"):
return CXPPacket(
from_agent="U:Cd",
to_agent="U:Qa",
thread_id="thread-001",
subject="review_and_test",
payload={
"files_created": files,
"task_summary": summary,
"project_dir": workspace,
},
work_status=WorkStatus.IN_PROGRESS,
)
Auto-Fixer Tests (15)
aioredis Migration (3 tests)
- [ ] TEST-031-001:
_autofix_aioredis()rewritesimport aioredistoimport redis.asyncio as aioredisin a .py file - [ ] TEST-031-002:
_autofix_aioredis()rewritesaioredis.from_url(url)call toredis.asyncio.from_url(url) - [ ] TEST-031-003:
_autofix_sync_redis()rewritesredis.Redis(host=h)toredis.asyncio.Redis(host=h)in async-context file
Missing Import Injection (3 tests)
- [ ] TEST-031-004:
_autofix_f821_datetime()addsfrom datetime import datetime, timedeltato a file that usesdatetime.now()with no import - [ ] TEST-031-005:
_autofix_missing_stdlib_imports()addsimport jsonto a file that callsjson.dumps()without importing json - [ ] TEST-031-006:
_autofix_missing_barename_imports()addsimport reto a file that callsre.compile()without importing re
Redis API Fixes (4 tests)
- [ ] TEST-031-007:
_autofix_xadd_dict()serializes{"key": {"nested": "val"}}to{"key": json.dumps({"nested": "val"})}in an xadd call - [ ] TEST-031-008:
_autofix_hset_dict()rewriteshset("name", mapping={"k": {"v": 1}})to use json.dumps on dict values - [ ] TEST-031-009:
_autofix_redis_decode()addsdecode_responses=Truetoredis.asyncio.Redis(host=h)constructor - [ ] TEST-031-010:
_autofix_redis_host()replacesredis.asyncio.Redis(host="localhost")withredis.asyncio.Redis(host=core.redis_factory.resolve_redis_host())(raises when unset — RUL-003)
Code Style Fixes (5 tests)
- [ ] TEST-031-011:
_autofix_relative_imports()rewritesfrom .models import Footofrom mypackage.models import Foousing package root detection - [ ] TEST-031-012:
_autofix_line_length()splits a 100-character function call into two lines without breaking semantics - [ ] TEST-031-013:
_autofix_import_order()reorders a file with local imports before stdlib to correct order - [ ] TEST-031-014:
_autofix_unused_imports()removesimport osfrom a file whereosis never referenced - [ ] TEST-031-015: Auto-fix pass runs across multiple .py files in workspace; each fixer touches only files with matching patterns
Review Gate Tests (12)
Gate 1: Syntax (3 tests)
- [ ] TEST-031-016:
_handle_review()returns CXP packet to U:Cd with subjectfix_issueswhen a workspace file has a SyntaxError - [ ] TEST-031-017: Bounce packet from Gate 1 failure has
gate_label"GATE 1 FAIL: Syntax errors" inreview_responsepayload field - [ ] TEST-031-018: Gate 1 pass (all files parse) proceeds to Gate 2 without bounce
Gate 2: Lint (3 tests)
- [ ] TEST-031-019:
_handle_review()returns CXP packet to U:Cd when a workspace file has an F821 (undefined name) flake8 error - [ ] TEST-031-020: Bounce packet from Gate 2 failure has
gate_label"GATE 2 FAIL: Lint/style errors" inreview_response - [ ] TEST-031-021: Gate 2 pass (no E9xx/F8xx errors) proceeds to Gate 3 without bounce
Gate 3: Checklist (3 tests)
- [ ] TEST-031-022:
_handle_review()returns bounce packet when a public function in workspace is missing a docstring (checklist violation) - [ ] TEST-031-023: Bounce packet from Gate 3 failure has
gate_label"GATE 3 FAIL: Checklist violations" inreview_response - [ ] TEST-031-024: All three gates pass for well-formed source code; pipeline proceeds to import validation phase
Bounce Packet Structure (3 tests)
- [ ] TEST-031-025:
_bounce_for_fix()returns a CXPPacket withfrom_agent="U:Qa",to_agent="U:Cd",subject="fix_issues" - [ ] TEST-031-026: Bounce packet payload contains
issues,fix_instructions,files_created,review_cycle,project_dir - [ ] TEST-031-027: Bounce packet
work_statusisWorkStatus.IN_PROGRESS
LLM Review Parsing Tests (8)
Verdict Extraction (3 tests)
- [ ] TEST-031-028:
_parse_review_verdict()returns "PASS" when response contains "REVIEW_VERDICT: PASS" - [ ] TEST-031-029:
_parse_review_verdict()returns "FAIL" when response contains "REVIEW_VERDICT: FAIL" - [ ] TEST-031-030:
_parse_review_verdict()returns "FAIL" as safe default when REVIEW_VERDICT line is absent
Issue Extraction (3 tests)
- [ ] TEST-031-031:
_parse_review_issues()extracts bullet items from the ISSUES: block when verdict is FAIL - [ ] TEST-031-032:
_parse_review_issues()returns empty list when verdict is PASS - [ ] TEST-031-033:
_parse_review_issues()handles malformed LLM output (missing ISSUES: section) without raising
CODE_REVIEW_PROMPT Completeness (2 tests)
- [ ] TEST-031-034: CODE_REVIEW_PROMPT contains exactly 31 numbered items (verified by counting "N. NAME:" patterns)
- [ ] TEST-031-035: CODE_REVIEW_PROMPT contains all 31 required check names: IMPORTS, NO_MOCKING, API_CORRECTNESS, FILE_COMPLETENESS, ENTRY_POINT, DEPENDENCY_DECLARATION, DESIGN, COMPLEXITY, NO_DUPLICATION, FUNCTION_LENGTH, FUNCTION_ARGS, NO_PLACEHOLDER, ERROR_HANDLING, EXCEPTIONS, RESOURCE_MANAGEMENT, NAMING, TYPE_HINTS, DEFAULT_VALUES, DOCSTRINGS, COMMENTS, LINE_LENGTH, FORMATTING, STRINGS, MUTABLE_GLOBAL_STATE, COMPREHENSIONS, TRUE_FALSE, ITERATORS, DECORATORS, CONCURRENCY, SECURITY, TESTS
Test Generation Tests (10)
QA_SYSTEM_PROMPT Rules (3 tests)
- [ ] TEST-031-036: QA_SYSTEM_PROMPT contains "ZERO mocking" or equivalent prohibition covering unittest.mock, MagicMock, patch, AsyncMock, Mock
- [ ] TEST-031-037: QA_SYSTEM_PROMPT contains prohibition on asyncio.Awaitable and asyncio.Coroutine
- [ ] TEST-031-038: QA_SYSTEM_PROMPT requires @traces decorator on every test function
Test File Extraction (4 tests)
- [ ] TEST-031-039:
_extract_and_write_tests()parses a response with a singleTEST_FILE: test_foo.pyblock and writes the file to workspace - [ ] TEST-031-040:
_extract_and_write_tests()parses a response with multiple TEST_FILE blocks and writes each file independently - [ ] TEST-031-041:
_extract_and_write_tests()returns list of written file paths - [ ] TEST-031-042:
_extract_and_write_tests()handles truncated LLM response (missing closing ```) without raising
Mock Detection and Retry (3 tests)
- [ ] TEST-031-043:
_validate_no_mocks()returns list of (line_number, pattern) tuples when test file containsfrom unittest.mock import patch - [ ] TEST-031-044:
_validate_no_mocks()returns empty list for a test file with zero mock usage - [ ] TEST-031-045:
_retry_without_mocks()is called when_validate_no_mocks()returns violations; result overwrites the test files in workspace
Escalation Context Tests (6)
Escalation Level Boundaries
- [ ] TEST-031-046:
_build_escalating_context()on cycle 1 returns only current issues list without history section - [ ] TEST-031-047:
_build_escalating_context()on cycle 3 includes "PREVIOUS FAILED ATTEMPTS" section with last attempt details - [ ] TEST-031-048:
_build_escalating_context()on cycle 5 includes "ROOT CAUSE ANALYSIS REQUIRED" section when same issue persists - [ ] TEST-031-049:
_build_escalating_context()on cycle 8 includes full file contents for files referenced in current issues
History Tracking
- [ ] TEST-031-050:
_fix_historyis reset to empty list when a new thread_id arrives in_handle_review() - [ ] TEST-031-051:
_fix_historyaccumulates one entry per_build_escalating_context()call within the same thread
Integration Tests (4)
Full Pipeline: Review Pass to U:Cp
- [ ] TEST-031-052: Given a workspace with syntactically valid, lint-clean, well-documented source code and passing tests,
_handle_review()returns a CXP packet to U:Cp with subjectcompliance_check
Full Pipeline: Gate Bounce
- [ ] TEST-031-053: Given a workspace file with a SyntaxError,
_handle_review()returns a packet to U:Cd with subjectfix_issuesafter the auto-fix pass fails to resolve the syntax issue
Full Pipeline: Test Failure Bounce
- [ ] TEST-031-054: Given a workspace where all review gates pass but generated tests fail,
_handle_review()returns a packet to U:Cd with subjectfix_issuesandfrom_test_fix=Truein payload
G226: No Cycle Cap
- [ ] TEST-031-055: QaVolk does not impose a maximum review_cycle or _test_fix_count limit; bounce packets are emitted on every failure regardless of cycle number (verified by confirming no
if review_cycle > N: breakguard in volk.py)
Other tracked files
specs/031-qa-volk/README.mdspecs/031-qa-volk/compliance-audit.md
Full spec text
Verbatim from specs/031-qa-volk/spec.md; headings are pushed down two levels.
SPEC-031: QA Volk (U:Qa)
Metadata
- Spec ID: 031-qa-volk
- Title: QA Volk -- Code Review and Test Generation Agent
- Author: Mohamed
- Status: Implemented
- Created: 2026-04-04
- Last Updated: 2026-04-09
- Priority: P0
- Version: 1.0.0
- Components: QaVolk, QA_SYSTEM_PROMPT, CODE_REVIEW_PROMPT, review_gate_syntax, review_gate_lint, review_gate_checklist, get_fix_instructions, _build_escalating_context
- Package: orchestrata-qa (2,915 LOC, 2 files)
- Dependencies: Python 3.14t, orchestrata-core, orchestrata-agents, orchestrata-codedirector (review_checks), SPEC-004 (CXP), SPEC-005 (Multi-Agent), SPEC-028 (LLM Client), SPEC-029 (CodeDirector)
Overview
What
The QA Volk (U:Qa) is the quality assurance agent in the Orchestrata multi-agent pipeline. It receives code artifacts from U:Cd (CodeDirector) and performs a full review-and-test pipeline: deterministic auto-fixing, three sequential review gates, LLM-based code review against a 31-item Google-style checklist, test generation, test execution, and fix delegation back to U:Cd on any failure. The cycle runs without a cap until all issues are resolved (G226), with escalating context on repeat failures (G229).
Why
- Code generated by LLMs contains predictable defects: wrong async idioms, aioredis API misuse, relative imports, hardcoded Redis hosts, missing stdlib imports. These must be corrected mechanically before any LLM review wastes tokens on avoidable issues.
- Structural quality gates (syntax, lint, checklist) must be deterministic -- not delegated to an LLM that may hallucinate a pass verdict.
- Test generation must be separate from code generation so that the same agent cannot mark its own work complete.
- Fix delegation must include escalating context: on cycles 3+, the history of failed attempts is injected into the bounce packet so U:Cd cannot repeat the same broken strategy.
- The pipeline must not terminate until tests pass, because a passing test suite is the only objective proof of correctness.
How
- Auto-fix pass -- 13 deterministic AST/regex fixers run on workspace files before any gate, eliminating known LLM-generated defects.
- Gate 1: Syntax -- every file in the workspace compiles under Python 3.13; failures bounce to U:Cd immediately.
- Gate 2: Lint -- flake8 critical codes (E9xx, F8xx) pass; failures bounce to U:Cd.
- Gate 3: Checklist -- deterministic traceability, import-order, docstring, and structural checks; failures bounce to U:Cd.
- Import validation -- each source module is imported in the workspace venv to catch hallucinated APIs.
- LLM code review -- CODE_REVIEW_PROMPT drives a 31-item structured review; FAIL verdict triggers bounce to U:Cd.
- Test generation -- QA_SYSTEM_PROMPT generates a pytest suite with zero mocking, @traces decorators, and real infrastructure fixtures.
- Test execution -- tests run in the workspace venv; failures trigger bounce to U:Cd with
from_test_fix=True. - Pass path -- all gates pass, tests pass, git commit, forward to U:Cp with
compliance_checksubject.
Terminology
| Term | Definition |
|---|---|
| QaVolk | The QA Volk implementation class; alias U:Qa, role "QA Engineer". Extends BaseVolk. |
| review_and_test | The CXP subject that triggers the full QA pipeline in process(). |
| Auto-fix pass | 13 deterministic fixers that rewrite known LLM defects in-place before gates run. |
| Gate 1 -- Syntax | AST compilation check: every .py file must parse without SyntaxError. |
| Gate 2 -- Lint | Flake8 critical-code check: E9xx (runtime errors) and F8xx (undefined names, imports) must be zero. |
| Gate 3 -- Checklist | Deterministic structural checks: traceability decorators, import order, docstrings, no relative imports. |
| review_gate_syntax | Function from orchestrata-codedirector review_checks.py; returns list of (code, filepath, description) tuples. |
| review_gate_lint | Function from orchestrata-codedirector review_checks.py; returns lint issues as tuples. |
| review_gate_checklist | Function from orchestrata-codedirector review_checks.py; returns structural quality issues. |
| get_fix_instructions | Function from orchestrata-codedirector review_checks.py; converts issues list to a structured fix prompt. |
| CODE_REVIEW_PROMPT | 31-item Google-style checklist prompt driving LLM-based code review. |
| QA_SYSTEM_PROMPT | System prompt for test generation: zero mocking, pytest only, @traces required, Python 3.13 idioms. |
| G226 | Governance rule: no cycle cap -- review loops until ALL issues resolved. |
| G229 | Governance rule: fix attempt history tracked and injected into bounce packets for escalation context. |
| _build_escalating_context | Builds progressively richer fix context: issues only (cycles 1-2), history (cycles 3+), root-cause hints (cycles 5+), full file contents (cycles 8+). |
| _bounce_for_fix | Emits a CXP fix_issues packet to U:Cd with escalating context and gate label. |
| from_test_fix | Payload flag set on bounce packets after test failures; causes QA to skip re-generation and rerun existing tests (G100). |
| compliance_check | CXP subject sent to U:Cp (Compliance Volk) when all review gates pass and tests pass. |
| fix_issues | CXP subject sent to U:Cd when any review gate or test suite fails. |
| _test_fix_count | Counter of test-fix cycles in the current thread; used for escalation context. |
| review_cycle | Counter of full review cycles in the current thread; printed in status messages. |
| WORKSPACE_DIR | The filesystem path of the generated project being reviewed; configurable from packet payload. |
User Stories
US-031-001: Deterministic Auto-Fix Before Review
As a QA Volk receiving generated source code, I want known LLM-generated defects corrected automatically before any gates run, So that review cycles are not wasted on mechanical, predictable errors.
Acceptance Criteria:
- [ ]
_autofix_aioredis()rewritesimport aioredisandaioredis.from_url()toredis.asyncioequivalents - [ ]
_autofix_sync_redis()rewrites synchronousredis.Redis()calls to asyncredis.asyncio.Redis() - [ ]
_autofix_f821_datetime()adds missingfrom datetime import datetime, timedeltawhen datetime is used bare - [ ]
_autofix_xadd_dict()rewrites nested dict values inxaddcalls tojson.dumps()serialized flat strings - [ ]
_autofix_hset_dict()rewriteshset(name, mapping={...})dict values to JSON-serialized strings - [ ]
_autofix_redis_decode()ensures Redis client is created withdecode_responses=True - [ ]
_autofix_missing_stdlib_imports()adds missing stdlib imports detected by name patterns - [ ]
_autofix_missing_barename_imports()adds missing bare-name imports for known third-party modules - [ ]
_autofix_redis_host()replaces hardcoded"localhost"in Redis constructors withcore.redis_factory.resolve_redis_host()(raises when unset — RUL-003) - [ ]
_autofix_relative_imports()rewritesfrom .module importto absolute import paths - [ ]
_autofix_line_length()splits lines exceeding 80 characters at logical boundaries - [ ]
_autofix_import_order()reorders imports: stdlib, third-party, local (separated by blank lines) - [ ]
_autofix_unused_imports()removes imports that are never referenced in the file body - [ ] All auto-fixers operate on all
.pyfiles inself.workspace - [ ] Auto-fix pass runs before Gate 1
US-031-002: Three-Gate Sequential Review Pipeline
As a QA pipeline enforcing quality standards, I want source code to pass three deterministic gates in strict sequence before LLM review, So that structural defects are caught cheaply without spending LLM tokens on broken code.
Acceptance Criteria:
- [ ] Gate 1 (Syntax) runs first; any failure immediately bounces to U:Cd via
_bounce_for_fix() - [ ] Gate 2 (Lint) runs only when Gate 1 passes; any failure bounces to U:Cd
- [ ] Gate 3 (Checklist) runs only when Gate 2 passes; any failure bounces to U:Cd
- [ ] Each bounce packet carries the gate label ("GATE 1 FAIL: Syntax errors" etc.)
- [ ]
review_gate_syntax()returns list of (code, filepath, description) tuples for all syntax errors - [ ]
review_gate_lint()returns list of tuples for all E9xx/F8xx flake8 errors - [ ]
review_gate_checklist()returns list of tuples for all structural quality violations - [ ]
get_fix_instructions()converts issue tuples to a human-readable fix prompt - [ ] When no issues are found in all three gates, the pipeline continues to the next stage automatically
- [ ] Gate pass is logged to stdout: " [U:Qa] Gate N/3: PASS"
US-031-003: LLM-Based Code Review with 31-Item Checklist
As a QA Volk performing code review, I want to drive an LLM through a structured 31-item checklist, So that code is evaluated against Google engineering standards before test generation.
Acceptance Criteria:
- [ ] CODE_REVIEW_PROMPT contains exactly 31 numbered checklist items
- [ ] Checklist covers: Correctness (6 items: IMPORTS, NO_MOCKING, API_CORRECTNESS, FILE_COMPLETENESS, ENTRY_POINT, DEPENDENCY_DECLARATION)
- [ ] Checklist covers: Design (3 items: DESIGN, COMPLEXITY, NO_DUPLICATION)
- [ ] Checklist covers: Functions (3 items: FUNCTION_LENGTH, FUNCTION_ARGS, NO_PLACEHOLDER)
- [ ] Checklist covers: Error Handling (2 items: ERROR_HANDLING, EXCEPTIONS)
- [ ] Checklist covers: Resource Management (1 item: RESOURCE_MANAGEMENT)
- [ ] Checklist covers: Naming (1 item: NAMING)
- [ ] Checklist covers: Type Safety (2 items: TYPE_HINTS, DEFAULT_VALUES)
- [ ] Checklist covers: Documentation (2 items: DOCSTRINGS, COMMENTS)
- [ ] Checklist covers: Style (4 items: LINE_LENGTH, FORMATTING, STRINGS, STYLE)
- [ ] Checklist covers: Python Best Practices (5 items: MUTABLE_GLOBAL_STATE, COMPREHENSIONS, TRUE_FALSE, ITERATORS, DECORATORS, CONCURRENCY)
- [ ] Checklist covers: Security (1 item: SECURITY)
- [ ] Checklist covers: Tests (1 item: TESTS)
- [ ] Each checklist item produces a "PASS|FAIL -- explanation" line in the LLM response
- [ ]
_parse_review_verdict()extracts "PASS" or "FAIL" from the REVIEW_VERDICT: line - [ ]
_parse_review_issues()extracts actionable issues from the ISSUES: block on FAIL verdict - [ ] FAIL verdict triggers bounce to U:Cd with parsed issues and fix instructions
- [ ] LLM review uses temperature=0.0, volk="U:Qa", and injects
self._graph_context - [ ] Review runs on every code-change cycle, including test-fix returns (G226)
US-031-004: Test Generation with Zero-Mocking Policy
As a QA Volk generating test suites, I want to produce pytest suites that use zero mocking and real infrastructure, So that tests validate actual behavior rather than mock contracts.
Acceptance Criteria:
- [ ] QA_SYSTEM_PROMPT forbids: unittest.mock, MagicMock, patch, AsyncMock, Mock, and custom Mock/Fake/Stub/Dummy classes
- [ ] QA_SYSTEM_PROMPT requires pytest (not unittest)
- [ ] QA_SYSTEM_PROMPT forbids asyncio.Awaitable/asyncio.Coroutine; requires collections.abc.Awaitable
- [ ] QA_SYSTEM_PROMPT requires
@tracesdecorator on every test function - [ ] Generated tests use real Redis with the host from
core.redis_factory.resolve_redis_host()(raises when unset — RUL-003; endpoint from the active env profile) - [ ] Generated tests use db=15 for Redis isolation with flush before and after yield
- [ ] Test prompt includes 6-phase structure: Analyze, Plan, Infrastructure Rules, Source Code, Output Constraints, Traceability
- [ ] Test files named
test_<module>.pyand placed in workspace root - [ ] Each test file capped at MAX 120 lines; split into multiple files when needed
- [ ]
_extract_and_write_tests()parses TEST_FILE blocks and writes toself.workspace - [ ]
_validate_no_mocks()checks written test files for mock usage - [ ]
_retry_without_mocks()re-runs LLM generation with anti-mock instruction on mock detection - [ ] Target: 5-10 test files, 50-100+ test functions total
US-031-005: Test Execution and Fix Delegation
As a QA Volk running generated tests, I want to execute the test suite in the workspace and delegate failures to U:Cd, So that code is not forwarded to U:Cp until tests actually pass.
Acceptance Criteria:
- [ ]
_run_tests()executes pytest inself.workspaceusing the workspace venv Python - [ ] Test pass/fail is determined from pytest exit code
- [ ] Test summary line is extracted and printed from pytest output
- [ ] Failed test names are printed individually with "FAILED " prefix
- [ ] On test failure,
_extract_test_failures()extracts individual failure lines - [ ] Each failure triggers a
fix_issuesCXP packet to U:Cd withfrom_test_fix=True - [ ]
_test_fix_countis incremented on each test-fix cycle - [ ] G226: No cap on test-fix cycles -- loop continues until tests pass
- [ ] Fix packet includes
escalating_contextfrom_build_escalating_context() - [ ] Fix packet instructs U:Cd to fix source code, NOT test files
US-031-006: Escalating Fix Context (G229)
As a QA Volk managing multi-cycle fix loops, I want to inject progressively richer context into bounce packets on repeated failures, So that U:Cd receives the history of failed attempts and cannot repeat broken strategies.
Acceptance Criteria:
- [ ] Cycles 1-2: bounce packet contains only current issues and fix instructions
- [ ] Cycles 3+: bounce packet includes history of last 3 failed attempts (cycle, type, issue count, issues, files changed)
- [ ] Cycles 3+: narrative: "The above attempts FAILED. Do NOT repeat the same approach."
- [ ] Cycles 5+: root-cause analysis section identifies persistent issues across cycles (fuzzy match by check type)
- [ ] Cycles 5+: strategy change instructions: read entire file, trace data flow, consider rewriting from scratch
- [ ] Cycles 8+: full file contents for files referenced in current issues are appended
- [ ]
_fix_historylist is initialized on new thread and appended on each escalation call - [ ] History is reset when a new thread_id is received in
_handle_review() - [ ]
_build_escalating_context()returns a single formatted string in the bounce payload
US-031-007: Successful QA Handoff to Compliance
As a QA Volk completing a successful review-and-test cycle,
I want to commit the workspace and forward a compliance_check packet to U:Cp,
So that the pipeline continues with formal compliance verification.
Acceptance Criteria:
- [ ] On test pass,
_git_commit()is called with message "QA complete: tests PASS" - [ ] CXP packet emitted to U:Cp with subject
compliance_check - [ ] Payload includes:
test_passed,test_files,test_output,review,review_cycles,project_dir,task_summary - [ ]
work_statusis set toWorkStatus.IN_PROGRESS - [ ]
self.statusis set toWorkStatus.RESOLVED - [ ]
self.summaryincludes test result, file count, and review cycle count
Data Models
CXP Packet: review_and_test
{
"subject": "review_and_test",
"sender": "U:Cd",
"recipient": "U:Qa",
"payload": {
"workspace_dir": "/path/to/workspace",
"task_summary": "Build user authentication module",
"source_files": ["src/auth.py", "src/models.py"],
"thread_id": "thread-123"
}
}
CXP Packet: fix_issues
{
"subject": "fix_issues",
"sender": "U:Qa",
"recipient": "U:Cd",
"payload": {
"workspace_dir": "/path/to/workspace",
"from_test_fix": false,
"escalating_context": "Cycle 1 issues only...",
"gate_label": "GATE 1 FAIL: Syntax errors",
"issues": [{"code": "E902", "file": "src/auth.py", "description": "SyntaxError"}],
"fix_instructions": "Fix the following syntax errors..."
}
}
CXP Packet: compliance_check
{
"subject": "compliance_check",
"sender": "U:Qa",
"recipient": "U:Cp",
"payload": {
"test_passed": true,
"test_files": ["test_auth.py", "test_models.py"],
"test_output": "50 passed in 2.3s",
"review": {"verdict": "PASS", "issues": []},
"review_cycles": 1,
"project_dir": "/path/to/workspace",
"task_summary": "Build user authentication module"
}
}
ReviewGateResult
class ReviewGateResult:
gate_name: str # "Syntax", "Lint", "Checklist"
passed: bool
issues: list[tuple[str, str, str]] # (code, filepath, description)
fix_instructions: str
EscalatingContext Levels
| Cycle Range | Context Level | Content |
|---|---|---|
| 1-2 | Basic | Current issues + fix instructions |
| 3-7 | History | + Last 3 failed attempts |
| 5+ | Root Cause | + Persistent issue analysis |
| 8+ | Full Content | + Full file contents |
Functional Requirements
FR-001: QaVolk MUST extend BaseVolk with alias "U:Qa" and role "QA Engineer".
FR-002: QaVolk process() MUST route "review_and_test" subject to _handle_review() method.
FR-003: All 13 auto-fixers MUST run on every .py file in workspace before any review gate executes.
FR-004: Gate 1 (Syntax) MUST compile every .py file using Python AST; failures MUST bounce to U:Cd immediately.
FR-005: Gate 2 (Lint) MUST run flake8 with E9xx/F8xx codes; failures MUST bounce to U:Cd.
FR-006: Gate 3 (Checklist) MUST run deterministic structural checks; failures MUST bounce to U:Cd.
FR-007: Import validation MUST attempt to import each source module in workspace venv; import errors bounce to U:Cd.
FR-008: LLM code review MUST use CODE_REVIEW_PROMPT with exactly 31 checklist items.
FR-009: LLM review MUST parse REVIEW_VERDICT line and extract PASS/FAIL status.
FR-010: FAIL verdict MUST trigger bounce to U:Cd with parsed issues and fix instructions.
FR-011: Test generation MUST use QA_SYSTEM_PROMPT with zero-mocking enforcement.
FR-012: Generated tests MUST use pytest, @traces decorators, and real Redis infrastructure.
FR-013: Test execution MUST run pytest in workspace venv; failures MUST loop to U:Cd with from_test_fix=True.
FR-014: G226 MUST enforce no cycle cap; review loops MUST continue until all issues resolved.
FR-015: G229 MUST track fix history and inject escalating context into bounce packets.
FR-016: Cycles 3+ MUST include last 3 failed attempts in bounce packet with warning not to repeat strategies.
FR-017: Cycles 5+ MUST include root-cause analysis for persistent issues.
FR-018: Cycles 8+ MUST include full file contents for referenced files.
FR-019: On successful path, _git_commit() MUST be called with "QA complete: tests PASS" message.
FR-020: On success, compliance_check CXP packet MUST be emitted to U:Cp with complete test and review metadata.
FR-021: _test_fix_count MUST increment on each test-fix cycle within same thread.
FR-022: review_cycle counter MUST be printed in status messages.
Error Conditions
| ERR-ID | Condition | Handling |
|---|---|---|
| ERR-031-001 | SyntaxError in any .py file | Bounce to U:Cd via fix_issues with gate_label="GATE 1 FAIL: Syntax errors" |
| ERR-031-002 | Flake8 E9xx (runtime error) detected | Bounce to U:Cd via fix_issues with gate_label="GATE 2 FAIL: Runtime errors" |
| ERR-031-003 | Flake8 F8xx (undefined name/import) detected | Bounce to U:Cd via fix_issues with gate_label="GATE 2 FAIL: Undefined names" |
| ERR-031-004 | Checklist structural violation detected | Bounce to U:Cd via fix_issues with gate_label="GATE 3 FAIL: Structural violations" |
| ERR-031-005 | Import validation failure (module not found) | Bounce to U:Cd via fix_issues with gate_label="IMPORT VALIDATION FAIL" |
| ERR-031-006 | LLM review returns FAIL verdict | Bounce to U:Cd via fix_issues with parsed issues from LLM response |
| ERR-031-007 | Test execution returns non-zero exit code | Bounce to U:Cd via fix_issues with from_test_fix=True |
| ERR-031-008 | Generated tests contain mock usage | Re-run LLM generation with anti-mock instruction via _retry_without_mocks() |
| ERR-031-009 | Test file exceeds 120 line limit | Split into multiple test files automatically |
| ERR-031-010 | LLM client returns invalid JSON response | Retry request with temperature=0.0 and explicit format instructions |
| ERR-031-011 | Git commit fails | Log error, continue pipeline without commit |
| ERR-031-012 | CXP packet send fails | Log error, set work_status to WorkStatus.ERROR |
| ERR-031-013 | Workspace directory not accessible | Return error response with ERR_WORKSPACE_INACCESSIBLE |
| ERR-031-014 | Thread ID changes mid-review | Reset _fix_history and start fresh escalation context |
API Contracts
class QaVolk(BaseVolk)
Methods
init(self, llm_client, workspace_dir, thread_id=None)
- Parameters: llm_client (LLMClient), workspace_dir (str), thread_id (Optional[str])
- Returns: None
process(subject, payload)
- Parameters: subject (str), payload (dict)
- Routes: review_and_test -> _handle_review()
- Returns: CXP response dict
_handle_review(payload)
- Parameters: payload (dict)
- Runs: auto-fix -> Gate1 -> Gate2 -> Gate3 -> Import -> LLM Review -> Test Gen -> Test Exec
- Returns: None (emits CXP packets)
_autofix_aioredis()
- Rewrites aioredis imports to redis.asyncio
- Returns: None (modifies files in-place)
_autofix_sync_redis()
- Rewrites sync redis.Redis() to redis.asyncio.Redis()
- Returns: None (modifies files in-place)
_run_review_gates()
- Runs Gate1, Gate2, Gate3 sequentially
- Returns: tuple(gate_results: list[ReviewGateResult], all_passed: bool)
_llm_code_review(source_files)
- Parameters: source_files (list[str])
- Returns: dict with verdict, issues, full_review
_generate_tests()
- Uses QA_SYSTEM_PROMPT to generate pytest suite
- Returns: dict with test_files, test_count
_run_tests()
- Executes pytest in workspace venv
- Returns: dict with passed, failed, output
_bounce_for_fix(gate_label, issues, fix_instructions, from_test_fix=False)
- Parameters: gate_label (str), issues (list), fix_instructions (str), from_test_fix (bool)
- Emits: fix_issues CXP packet to U:Cd
- Returns: None
_build_escalating_context(issues, cycle)
- Parameters: issues (list), cycle (int)
- Returns: str with escalating context based on cycle level
_git_commit()
- Creates git commit with "QA complete: tests PASS"
- Returns: None
Non-Functional Requirements
Performance
- Auto-fix pass MUST complete within 30 seconds for workspaces up to 100 files.
- Each review gate MUST complete within 10 seconds.
- Test execution MUST timeout after 300 seconds.
Reliability
- G226 enforces infinite retry until all issues resolved.
- G229 prevents repeated failed strategies via escalating context.
- No state loss: _fix_history persists across cycles in same thread.
Maintainability
- 13 auto-fixers are modular and individually testable.
- Review gates delegate to orchestrata-codedirector review_checks.py.
- Clear separation between deterministic fixes and LLM-driven review.
Technical Design
Architecture
U:Cd (CodeDirector)
|
v
[review_and_test packet]
|
v
QaVolk._handle_review()
|
+---> [Auto-fix Pass: 13 deterministic fixers]
|
+---> [Gate 1: Syntax]
|
+---> [Gate 2: Lint]
|
+---> [Gate 3: Checklist]
|
+---> [Import Validation]
|
+---> [LLM Code Review: 31-item checklist]
|
+---> [Test Generation]
|
+---> [Test Execution]
|
v
[Pass] --> U:Cp (Compliance) [compliance_check]
[Fail] --> U:Cd (CodeDirector) [fix_issues]
Escalation Flow
- Cycle 1-2: issues only
- Cycle 3+: issues + history (last 3 attempts)
- Cycle 5+: + root cause analysis
- Cycle 8+: + full file contents
Examples
Example 1: Syntax Gate Failure
[U:Qa] Auto-fix: 13 fixers applied
[U:Qa] Gate 1/3: Syntax... FAILED
src/auth.py: SyntaxError: invalid syntax (line 42)
[U:Qa] Bouncing to U:Cd with escalating context (cycle 1)
Example 2: Successful Review Path
[U:Qa] Auto-fix: 13 fixers applied
[U:Qa] Gate 1/3: Syntax... PASS
[U:Qa] Gate 2/3: Lint... PASS
[U:Qa] Gate 3/3: Checklist... PASS
[U:Qa] Import validation... PASS
[U:Qa] LLM Code Review... PASS
[U:Qa] Generating tests...
[U:Qa] Running tests...
[U:Qa] Tests: 50 passed in 2.3s
[U:Qa] Git commit: QA complete: tests PASS
[U:Qa] Forwarding to U:Cp with compliance_check
Example 3: Escalating Context (Cycle 5)
[U:Qa] Test execution failed (cycle 5)
[U:Qa] Building escalating context:
- Current issues: test_auth.py::test_login fails
- History (last 3):
- Cycle 2: 3 test failures, same test_login
- Cycle 3: 2 test failures, test_login + test_logout
- Cycle 4: 1 test failure, test_login
- Root cause: test_login mocks Redis instead of using real instance
- Strategy: Read entire auth.py, trace data flow, rewrite without mocks
[U:Qa] Bouncing to U:Cd with full escalation
Security
- Input validation: All CXP packet payloads validated before processing.
- Workspace isolation: Each review operates on isolated workspace directory.
- No credential exposure: Redis credentials passed via environment variables only.
- Audit logging: All review gates logged with timestamp, thread_id, and results.
Governance
- G100: Test-fix cycles skip re-generation, re-run existing tests only.
- G226: No cycle cap -- review loops until ALL issues resolved.
- G229: Fix attempt history tracked and injected into bounce packets.
- G227: Auto-fix pass runs before every review cycle.
Visual Architecture
Class Diagram
Diagram source shown as text: Mermaid could not parse it (Error: Parse error on line 15:).
classDiagram-direction LR
class ArchitectAgent {
$agent_type: ClassVar[str] = 'U:Ar'
---
+__init__(model: str = 'claude-3-5-haiku', agent_name: str = '')
+async analyze_impact(file_path: str, old_string: str, new_string: str, context: dict[str, Any] | None = None): dict[str, Any]
+async design_solution(requirements: dict[str, Any]): dict[str, Any]
+async review_architecture(architecture: dict[str, Any]): dict[str, Any]
}
class BaseAgent <<pydantic>> {
-model: str = Field(default='claude-3-5-haiku', description='Model identifier for the agent', min_length=1, strict=True)
-agent_id: str = Field(default='', description='Unique agent identifier', strict=True)
-agent_name: str = Field(default='', description='Human-readable agent name', strict=True)
$agent_type: ClassVar[str] = 'U:Base'
$_instance_counters: ClassVar[dict[str, int]] = {}
---
{@classmethod} +validate_model(v: str): str
+__init__(**data: Any): None
#_generate_unique_id(): str
+model_post_init(__context: Any): None
+async receive_message(message: Any, sender: str | None = None): Any
}
class CodeDirectorAgent {
$agent_type: ClassVar[str] = 'U:Cd'
---
+__init__(model: str = 'claude-3-5-sonnet', agent_name: str = '')
+async execute_edit(file_path: str, old_string: str, new_string: str, context: dict[str, Any] | None = None): dict[str, Any]
+async review_code(code: str, requirements: dict[str, Any]): dict[str, Any]
+async implement_feature(spec: dict[str, Any]): dict[str, Any]
}
class QualityAssuranceAgent {
$agent_type: ClassVar[str] = 'U:Qa'
---
+__init__(model: str = 'claude-3-5-sonnet', agent_name: str = '')
+async review_edit(file_path: str, old_string: str, new_string: str, context: dict[str, Any] | None = None): dict[str, Any]
+async run_tests(test_suite: str): dict[str, Any]
+async audit_security(code: str): dict[str, Any]
}
class UserExperienceAgent {
$agent_type: ClassVar[str] = 'U:Ux'
---
+__init__(model: str = 'claude-3-5-haiku', agent_name: str = '')
+async review_ux(file_path: str, old_string: str, new_string: str, context: dict[str, Any] | None = None): dict[str, Any]
+async design_ui(requirements: dict[str, Any]): dict[str, Any]
+async evaluate_accessibility(ui: dict[str, Any]): dict[str, Any]
}
BaseAgent <|-- ArchitectAgent
BaseModel <|-- BaseAgent
BaseAgent <|-- CodeDirectorAgent
BaseAgent <|-- QualityAssuranceAgent
BaseAgent <|-- UserExperienceAgent
Unit Tests
- Test each auto-fixer independently on sample files.
- Test gate functions with known error inputs.
- Test escalating context builder for all cycle levels.
Integration Tests
- Test full review pipeline with mock workspace.
- Test CXP packet routing between U:Cd, U:Qa, U:Cp.
- Test infinite retry loop with simulated failures.
Coverage Targets
- Auto-fixers: 100% coverage
- Review gates: 100% coverage
- Escalation logic: 100% coverage
Integration Points
U:Cd (CodeDirector)
- Receives: fix_issues packets with escalating_context
- Sends: review_and_test packets
U:Cp (Compliance Volk)
- Receives: compliance_check packets with test metadata
orchestrata-codedirector
- Provides: review_gate_syntax, review_gate_lint, review_gate_checklist, get_fix_instructions
orchestrata-llm (SPEC-028)
- Provides: LLM client for code review and test generation
Success Criteria
- [ ] QaVolk extends BaseVolk with alias "U:Qa"
- [ ] process() routes review_and_test to _handle_review()
- [ ] 13 auto-fixers run before all gates
- [ ] Three review gates execute sequentially
- [ ] Import validation after gates
- [ ] LLM review with 31-item checklist
- [ ] Zero-mocking test generation
- [ ] G226: Infinite retry until tests pass
- [ ] G229: Escalating context in bounce packets
- [ ] Successful path: git commit + compliance_check to U:Cp
Observability
Logging Requirements
- Component Logging
- Log all major operations with appropriate log levels
- Include correlation IDs for request tracing
- Log performance metrics for critical operations
- Log errors with full context for debugging
Metrics Requirements
- Performance Metrics
- Operation duration histograms
- Request/error rate counters
- Resource utilization gauges
- Business metrics relevant to domain
Tracing Requirements
- Distributed Tracing
- Trace propagation across component boundaries
- Span attributes for domain-specific context
- Trace sampling based on operational needs
Alerting Requirements
- Critical Alerts
- Error rate spikes
- Performance degradation
- Resource exhaustion
- Business metric anomalies
Dashboard Requirements
- Operational Dashboard
- Real-time system health
- Performance trends
- Error analysis
- Resource monitoring
Revision History
| Version | Date | Author | Changes |
|---|---|---|---|
| 1.0.0 | 2026-04-04 | Mohamed | Initial spec |
| 1.0.1 | 2026-04-09 | Mohamed | Added missing sections per SPEC_STANDARD.md: Data Models, Functional Requirements (FR-001-022), Error Conditions (ERR-031-001 to ERR-031-014), API Contracts, Non-Functional Requirements, Technical Design, Examples, Security, Governance, Dependencies, Testing, Integration Points, Success Criteria, Revision History |
Acceptance Criteria Summary
- [ ] QaVolk extends BaseVolk with alias "U:Qa" and role "QA Engineer"
- [ ]
process()routesreview_and_testsubject to_handle_review() - [ ] 13 auto-fixers run on all workspace .py files before all gates on every cycle
- [ ] Three review gates run sequentially; any failure bounces to U:Cd
- [ ] Import validation runs after all three gates pass
- [ ] LLM code review uses CODE_REVIEW_PROMPT with 31-item Google-style checklist
- [ ] Test generation uses QA_SYSTEM_PROMPT with zero-mocking policy and @traces requirement
- [ ] Tests run in workspace venv; failures loop back to U:Cd indefinitely (G226)
- [ ] Bounce packets carry escalating context: history on cycles 3+, root-cause on 5+, file contents on 8+ (G229)
- [ ] Successful path: git commit + compliance_check packet to U:Cp
- [ ] 2,915 LOC across 2 files in orchestrata-qa package