orchestrata_ultimate.core.standards
Reference › orchestrata_ultimate › core › standards
Holds the coding standards that are injected into the prompts of the Orchestrata volks (SPEC-001, the orchestration kernel). The module is data plus one accessor. A full text, CODING_STANDARDS, is a numbered checklist used for initial code generation; it is grouped under Correctness, Design, Functions, Error Handling, Resource Management and Naming. It covers rules such as absolute imports only, no mocking, no function over 40 lines of logic, at most five parameters, modules under 200 lines, a flat src layout and a thin cli.py. A smaller fix-cycle variant, about a third of the size, is used for repair prompts to save tokens. get_standards(fix_cycle=False) returns whichever of the two applies. The text is written as the checklist the generated code will be reviewed against.
At a glance
| Source | src/orchestrata_ultimate/core/standards.py |
| Lines of code | 240 |
| Classes | 0 |
| Functions | 1 |
| Imports (internal) | none |
| Imported by | orchestrata_ultimate.agents.prompt_builder, orchestrata_ultimate.agents.volks.architect.architect_prompts, orchestrata_ultimate.agents.volks.codedirector.implementation, orchestrata_ultimate.agents.volks.codedirector.review, orchestrata_ultimate.agents.volks.junior.volk |
| Tests that import it | tests/agents/test_prompt_builder.py, tests/core/test_standards.py, tests/generated_core/test_standards_generated.py, tests/generated_recovery/test_core_standards.py, tests/test_core.py |
Class diagram
No classes; see Functions.
Dependency diagram
API
Functions
| Function | Signature | Summary |
|---|---|---|
get_standards |
get_standards(fix_cycle: bool = False) -> str |
Return the appropriate coding standards string. |
Source
"""Canonical coding standards for all Orchestrata volks.
Full standards are used for initial code generation prompts.
Fix-cycle standards are a minimal subset (~3x smaller) used
for fix-cycle prompts to reduce token count.
Spec: 001 - Orchestration Kernel (core infrastructure)
"""
CODING_STANDARDS = """
=== MANDATORY CODING STANDARDS ===
Your code will be reviewed against this exact checklist. Every item must PASS.
--- Correctness ---
1. IMPORTS: All imports must resolve to real, existing modules. No hallucinated
packages. Absolute imports only — NO relative imports (no 'from orchestrata_ultimate.core. import').
Order: stdlib, third-party, local (separated by blank lines).
2. NO_MOCKING: ZERO usage of unittest.mock, MagicMock, patch, AsyncMock, Mock
anywhere in source or test code. This is an absolute rule — any mock usage
causes immediate FAIL.
3. API_CORRECTNESS: Function signatures, class constructors, and method calls
must match the actual library APIs. No invented APIs or wrong parameters.
4. FILE_COMPLETENESS: Every file referenced in imports must exist. No missing
modules. No circular imports.
5. ENTRY_POINT: Project must have a clear entry point (main function or CLI
script). Main code guarded by `if __name__ == '__main__'`.
CLI RULE: Keep cli.py under 80 lines. The CLI should be a thin wrapper
that parses args with argparse and delegates ALL logic to library
functions. Do NOT put business logic in cli.py. Use simple subcommands
(max 4-5). Each subcommand handler should be 5-10 lines max.
6. DEPENDENCY_DECLARATION: All third-party packages must be listed in
pyproject.toml dependencies. No undeclared dependencies.
6b. INIT_IMPORTS: The __init__.py file must NOT eagerly import all
submodules. Only import core data models and public API functions.
NEVER import CLI modules (cli.py) or entry-point scripts in
__init__.py — CLI modules are standalone entry points, not library
components. Keep __init__.py minimal to avoid cascading import
failures if any submodule has issues.
--- Design ---
7. No unnecessary coupling. No over-engineering or premature abstractions.
8. No unnecessarily complex code. Easy to understand by other developers.
9. No copy-pasted code blocks. Repeated logic extracted into functions.
9b. FILE SIZE: Each Python module MUST be under 200 lines. If a class or
module exceeds 200 lines, split it into focused sub-modules. Example:
storage.py (200 lines) -> storage_core.py + storage_queries.py.
This prevents token-limit truncation during code generation.
9c. PROJECT LAYOUT: Use FLAT src-layout. All source files go under
`src/<package_name>/`, tests under `tests/`. Do NOT nest a
package-named directory inside the project: NO `package_name/src/
package_name/`. The project directory IS the package root.
Correct: `src/async_task_queue/models.py`
Wrong: `async_task_queue/src/async_task_queue/models.py`
--- Functions ---
10. No function exceeds 40 lines of logic. Split into focused helpers.
11. No function has more than 5 parameters.
12. No `pass`, `TODO`, `NotImplementedError` in critical code paths.
--- Error Handling ---
13. Critical operations (file I/O, network, subprocess) have try/except.
No bare `except:`. Specific exception types. `with` for cleanup.
14. Custom exceptions inherit from appropriate bases. Names end in `Error`.
--- Resource Management ---
15. Files, sockets, connections explicitly closed. Use `with` statements.
--- Naming ---
16. snake_case for functions/variables/modules, PascalCase for classes,
UPPER_CASE for constants. Descriptive names, not abbreviated.
--- Type Safety ---
17. All public functions have parameter and return type annotations.
18. No mutable objects (list, dict, set) as default argument values.
--- Documentation ---
19. All public classes and functions have docstrings (Google style).
20. Comments explain "why", not "what". No commented-out code.
--- Style ---
21. Maximum 80 characters per line.
22. 4-space indentation, no tabs. No semicolons. One statement per line.
23. f-strings or format() for strings. No += in loops.
--- Python Best Practices ---
24. No mutable global variables. Constants use UPPER_CASE.
25. Simple comprehensions only. Complex ones rewritten as loops.
26. Implicit boolean evaluation (`if seq:` not `if len(seq):`).
27. Default iterators (`for key in adict:` not `for key in adict.keys():`).
28. No `staticmethod`. `classmethod` only for named constructors.
29. Proper locking for threading. No blocking in async without to_thread().
PYTHON 3.13 COMPAT: `asyncio.Awaitable`, `asyncio.Coroutine`,
`asyncio.Generator` were REMOVED in Python 3.13. Use
`from collections.abc import Awaitable, Coroutine` or
`from typing import Awaitable` instead.
Also: `asyncio.get_event_loop()` is DEPRECATED in Python 3.13 when
called outside an async context. Do NOT call it from synchronous code.
Also: `datetime.utcnow()` is DEPRECATED in Python 3.12+. Use
`datetime.now(datetime.timezone.utc)` instead.
PYTHON 3.14 COMPAT: `contextlib.AsyncContextManager` was REMOVED in
Python 3.14. Use `contextlib.AbstractAsyncContextManager` instead.
--- Configuration ---
30. Connection parameters (host, port, URL) for external services (Redis,
databases, APIs) MUST read from environment variables. NEVER hardcode IPs
or non-localhost hostnames. Endpoints come from the active
`ORCHESTRATA_ENV_PROFILE` (`env/{dev,test,prod}.env`, endpoint-only)
layered over secrets-only `.env` via each entrypoint's `_load_dotenv()`;
the test suite is hard-pinned to `env/test.env` by `tests/conftest.py`
(prod-subnet guard). Ordinary/optional config may carry a sensible
default (see 30c); REQUIRED infra endpoints must NOT (see 30d).
30a. CONSTRUCTOR CONSISTENCY: When multiple classes share connection
parameters, use identical parameter names: `host`, `port`, `db`.
30c. NO BARE os.environ SUBSCRIPT: NEVER read config with the subscript
form `os.environ["X"]` -- it raises KeyError when the variable is
unset (fresh checkout / CI). ALWAYS use `os.environ.get("X", default)`
so a fallback applies. Read env at call time (not as a module-level
constant captured at import) so runtime overrides take effect.
Enforced by review check `check_env_access` (CONFIG).
30d. NO LITERAL FALLBACK FOR REQUIRED INFRA ENDPOINTS (RUL-003): the keys
that select which live infra you talk to -- REDIS_HOST, REDIS_PORT,
KG_ROUTING_URI, KG_URI, KG_DATABASE, MEMGRAPH_URI, CXP_GRPC_PORT,
KG_GRPC_PORT -- MUST be read with NO default and RAISE when unset. A
`.get(KEY, default)` / `.setdefault(KEY, default)` on these (even
`"localhost"` / `""`) is FORBIDDEN: an unset key must fail loudly, never
silently connect to the wrong server (the classic bug: a default of the
PRODUCTION Redis/graph). This is the deliberate INVERSE of 30c for these
specific keys. Route through the raising seams
`core.graph_factory.resolve_uri` / `resolve_kg_database` and
`core.redis_factory.resolve_redis_host` / `resolve_redis_port`. The key
set + scanner live in `core.infra_env_rule`; enforced by review check
`check_infra_env_defaults` (CONFIG) and the `scripts/validate_ci.py` gate.
Optional/feature keys (MEMGRAPH_URIS, MEMGRAPH_HA_CONTROLLER_URL,
TEST_MEMGRAPH_URI, REDIS_DB, CXP_GRPC_HOST) are excluded -- a default is a
valid state there, not a wrong-server risk.
--- Redis API ---
30b. REDIS STREAMS: Stream IDs are strings in "timestamp-sequence" format
(e.g., "1678901234567-0"), NOT integer offsets. NEVER call int() on
a stream ID. Use "*" for auto-ID, "0" for start-of-stream.
BYTES: ALWAYS create Redis client with `decode_responses=True`.
HASH VALUES: All values in Redis hashes MUST be strings, bytes, int,
or float. NEVER pass dict, list, dataclass, or datetime objects to
hset/hmset. Serialize with json.dumps(), store datetimes as ISO
strings via .isoformat().
--- Security ---
31. No hardcoded secrets or API keys. No eval/exec with user input.
No SQL/shell injection via string concatenation.
--- Flask / Web ---
31b. FLASK JSON NULL: `request.get_json(silent=True)` returns `None` for
BOTH invalid JSON and JSON `null`. Check `request.is_json` first.
--- Tests ---
32. Tests present and correct. Clear assertions. No false positives.
NO MOCKING — test real behavior only.
32b. TEST CLEANUP: Use `tmp_path` pytest fixture for temporary files.
32c. NO MONKEY-PATCHING: Use real error conditions, not method replacement.
--- Traceability ---
33. TRACEABILITY: Every class and every public function MUST have a
@traces(spec=..., story=..., reqs=[...]) decorator. Implement this
decorator LOCALLY in a decorators.py file as a simple pass-through.
Do NOT import from orchestrata_ultimate.core.tracing.traceability in standalone projects.
--- Parallel Test Safety ---
34. PARALLEL TEST ISOLATION: Tests run concurrently against ONE shared
Memgraph database and Redis instance (per-worker isolation is by database
name, `orchkg_w<N>`, not by address). NEVER write a global teardown: no
unscoped `DETACH DELETE`, no `MATCH ()-[r]->() DELETE r`, no
`flushdb()`/`flushall()`. Scope every graph delete with a
`$param`/`test_id`/`project_id` filter and delete only this test's Redis
keys. A global wipe deletes rows a concurrent
test is mid-assertion on -- the #1 source of suite flakiness. Enforced
by scripts/gate_parallel_safety.py and review check 34
(verification.review.checks_safety.check_test_isolation).
35. ENV PROFILE PINNING: The active infrastructure fleet is selected by
`ORCHESTRATA_ENV_PROFILE` (default `test`) → `env/{dev,test,prod}.env`.
The pytest suite HARD-PINS to `env/test.env` (`tests/conftest.py`) and
refuses to run against `10.53.1.x` (prod) unless explicitly overridden.
Never rely on `.env` alone for infra endpoints in tests or CI.
36. TRUSTWORTHY TEST ATTRIBUTION: A parallel/batched test runner MUST
derive per-module pass/fail from authoritative reporting (pytest
JUnit XML / process exit codes), NEVER by scraping stdout. A module
absent from the report is a FAILURE, never a silent pass -- stdout
scraping hides timeouts and crashes (see
core.threading.test_executor._attribute_from_junit).
=== END CODING STANDARDS ===
"""
CODING_STANDARDS_FIX = """
=== FIX-CYCLE CODING STANDARDS (subset) ===
1. IMPORTS: Absolute imports only. Order: stdlib, third-party, local.
No relative imports. All imports must resolve to real modules.
2. NO_MOCKING: ZERO usage of unittest.mock, MagicMock, patch, AsyncMock,
Mock anywhere. Immediate FAIL.
3. FILE_COMPLETENESS: Every imported module must exist. No circular imports.
4. ENTRY_POINT: Main code guarded by `if __name__ == '__main__'`.
5. FUNCTIONS: Max 40 lines per function. Max 5 parameters.
No `pass`, `TODO`, `NotImplementedError` in critical paths.
6. ERROR_HANDLING: Critical ops (file I/O, network) use try/except.
No bare `except:`. Use `with` for cleanup.
7. TYPE_ANNOTATIONS: All public functions have param + return annotations.
No mutable defaults (list, dict, set).
8. LINE_LENGTH: Max 80 characters per line. 4-space indent.
9. PYTHON 3.13/3.14:
- `asyncio.Awaitable` REMOVED -> use `collections.abc.Awaitable`
- `asyncio.get_event_loop()` DEPRECATED in sync context
- `datetime.utcnow()` DEPRECATED -> `datetime.now(timezone.utc)`
- `contextlib.AsyncContextManager` REMOVED in 3.14
10. TESTS: No mocking. No monkey-patching. Real behavior only.
Use `tmp_path` for temp files.
11. SECURITY: No hardcoded secrets. No eval/exec with user input.
12. FILE_SIZE: Each module under 200 lines.
13. REDIS HASHES: All values in Redis hashes MUST be strings, bytes, int,
or float. Serialize with json.dumps() before storing. Use
`decode_responses=True` on the Redis client.
14. REDIS STREAMS: Stream IDs are strings like "1678901234567-0", NOT
integers. NEVER call int() on a stream ID.
15. TEST ISOLATION: No global DB teardown in tests. No unscoped
`DETACH DELETE`, no `MATCH ()-[r]->() DELETE r`, no `flushdb`/
`flushall`. Scope Neo4j deletes by test_id/$param; delete only this
test's Redis keys. Concurrent tests share one Neo4j DB + Redis.
=== END FIX-CYCLE STANDARDS ===
"""
def get_standards(fix_cycle: bool = False) -> str:
"""Return the appropriate coding standards string.
Args:
fix_cycle: If True, return the minimal fix-cycle subset.
Returns:
Coding standards string for LLM prompts.
"""
if fix_cycle:
return CODING_STANDARDS_FIX
return CODING_STANDARDS