Add threading.RLock to InvariantService to protect shared state
(_invariants dict, _enforcement_records list) from concurrent access
by multiple threads during parallel plan execution. Prevents
RuntimeError: dictionary changed size during iteration and data
corruption in multi-threaded environments.
Changes:
- Added self._lock = RLock() in __init__
- Wrapped all public methods (add_invariant, list_invariants,
remove_invariant, get_effective_invariants, enforce_invariants)
with lock acquisition via context managers
- Added helper read methods: get_enforcement_records(), get_invariant(),
get_invariants_snapshot() -- all thread-safe
- Added BDD tests for concurrent access patterns
- Updated CHANGELOG.md and CONTRIBUTORS.md
ISSUES CLOSED: #7524
Fix a critical concurrency bug in A2aEventQueue.publish() where the method
iterates over _subscriptions without holding a lock. This causes RuntimeError:
dictionary changed size during iteration when subscribe_local/unsubscribe are
called concurrently from other threads.
The fix introduces a threading.Lock to protect all state mutations and
dictionary access in the A2aEventQueue class, while carefully ensuring callbacks
are invoked outside the lock to prevent potential deadlocks.
Changes:
- src/cleveragents/a2a/events.py: Added _lock attribute, protected
__init__, is_closed, publish, subscribe_local, unsubscribe, get_events,
and close methods with threading.Lock snapshot pattern for callbacks.
- features/a2a_event_queue_concurrency.feature: BDD feature file with 6
scenarios covering concurrent publish/subscribe/unsubscribe safety.
- features/steps/a2a_event_queue_concurrency_steps.py: Step definitions
implementing multi-threaded concurrency test harness.
ISSUES CLOSED: #7604
The DEFAULT_MAX_TOKENS_HOT was 8000 (should be 16000),
DEFAULT_MAX_DECISIONS_WARM was 500 (should be 100), and
DEFAULT_MAX_DECISIONS_COLD was 5000 (should be 500). These values in context_tier_settings.py did not match the canonical defaults defined in TierBudget model (tiers.py) or Settings class defaults, causing incorrect budget enforcement when settings were None.
ISSUES CLOSED: #1443
- Fix 2-space -> 4-space indentation on _handle_session_close in
facade.py; this single error caused every CI gate to fail
(lint, typecheck, unit_tests, integration_tests, e2e_tests, security)
- Add @tdd_issue @tdd_issue_9250 tags to the three session_id
validation scenarios in a2a_facade_coverage.feature per the mandatory
bug-fix TDD workflow requirement
- Fix CONTRIBUTORS.md entry: was PR #11053 / issue #9094, corrected to
PR #11098 / issue #9250
ISSUES CLOSED: #9250
The _handle_session_close handler in the A2A local facade previously validated
session_id only after checking whether a session service was wired. When no
session service was available, _cleanup_session_devcontainers() was invoked
with an empty or missing session_id, risking incorrect container lifecycle
operations on unknown sessions. This fix moves validation to the top of
_handle_session_close so it applies uniformly across both code paths.
Updated BDD tests in features/a2a_facade_wiring.feature and
features/a2a_facade_coverage.feature to reflect the new validation behavior.
PR-CLOSED: #9250
Add `command="agents plan tree"` parameter to the `format_output()` call for
the `plan tree` CLI command, so that JSON and YAML output conforms to the
spec's Output Rendering Framework. The output is now a proper envelope with
`command`, `status`, `exit_code`, `data`, `timing`, and `messages` fields.
Update BDD step definitions to validate envelope structure and update feature
scenarios for spec-compliant assertions. Remove `@tdd_expected_fail` tag from
the previously-failing JSON tree format test (issue #4254).
ISSUES CLOSED: #11041
- Add CHANGELOG.md [Unreleased] entry for the three new module guides
- Add CONTRIBUTORS.md entry for HAL9000 authoring the module guides
- Fix InvariantReconciliationActor DI container snippet in
invariant-reconciliation.md: replace incorrect event_bus/audit_service
params with the actual constructor params (invariant_service,
decision_service) as defined in src/cleveragents/actor/reconciliation.py
ISSUES CLOSED: #4848
Implemented the TuiMaterializer class that bridges the Output Rendering
Framework to Textual UI widgets, enabling all CLI command producers to
render in the TUI without modification. Split the module into three files
to stay under the 500-line file limit: main materializer.py (TuiMaterializer
class), _tui_events.py (event type constants and event model), and
_tui_renderers.py (all rendering helper functions).
The TuiMaterializer implements the MaterializationStrategy protocol and
maps ElementHandle events (Panel, Table, Status, Progress, Tree, Code,
Diff, Separator, ActionHint, Text) to plain-text renderings for TUI display.
Supports real-time streaming updates and A2A event routing for
PermissionRequest and ThoughtBlock events. Thread-safe with lock guards on
all shared state mutations.
Added comprehensive Behave BDD test suite covering all element types,
callback invocation, rendered output accumulation, A2A routing logic, and
concurrent thread safety verification.
ISSUES CLOSED: #5326
Add comprehensive BDD test coverage validating the ACP to A2A module rename:
- features/a2a_module_rename_standardization.feature — 3 scenarios:
1. All 22 __all__ symbols exported and importable from cleveragents.a2a
2. Zero legacy ACP references found in a2a module source files
3. Documentation strings use A2A naming per ADR-047
- features/steps/a2a_module_rename_standardization_steps.py — step definitions
with recursive ACP reference scanning and symbol completeness checks
- Updated CHANGELOG.md under ### Added section
- Updated CONTRIBUTORS.md with contribution entry
ISSUES CLOSED: #8615
- Fix step definitions: remove unused imports (sys, Any, Dict), move
all imports to module level, drop noqa suppressor, fix docstring step
to use context.text, use packaging.version for correct semver check
- Upgrade version floor from 6.0.2 to 6.0.3 in step text and feature
file to match pyproject.toml constraint and issue requirement
- Fix CONTRIBUTORS.md: correct PR number (#11012 -> #11017), issue
reference (#13605 -> #11012), and version string (6.0.2 -> 6.0.3)
ISSUES CLOSED: #11012
Add pyyaml>=6.0.2 as explicit runtime dependency in pyproject.toml to
mitigate CVE-2025-8045 (arbitrary code execution via crafted YAML
payloads). PyYAML was previously only transitive, used at runtime by
src/cleveragents/actor/yaml_loader.py for actor configuration YAML loading.
This change:
- Declares pyyaml>=6.0.2 as a direct runtime dependency with security comment
- Updates uv.lock to resolve the new explicit dependency constraint (requires-dist)
- Adds CHANGELOG.md entry under [Unreleased] -> Security section
- Updates CONTRIBUTORS.md with HAL 9000 contribution details
- Adds BDD/Behave test (features/pyyaml_runtime_dependency.feature) verifying
PyYAML availability and version compliance at runtime
- Adds corresponding step definitions for BDD scenarios
ISSUES CLOSED: #13605
Add a verified CLI showcase for the version, info, and diagnostics commands,
register in examples.json and update CHANGELOG/CONTRIBUTORS.
ISSUES CLOSED: #7592
The provider registry's FALLBACK_ORDER was missing ProviderType.GEMINI,
which meant Gemini-only configured installations could not select the
Gemini provider as default via the fallback chain.
This fix adds GEMINI right after GOOGLE in the priority order, consistent
with how it appears in DEFAULT_CAPABILITIES, DEFAULT_MODELS, and
PROVIDER_KEY_ATTRS - all of which already support Gemini.
Includes BDD regression coverage in features/fallback_gemini_provider.feature.
ISSUES CLOSED: #10906
Signed-off-by: HAL 9000 <hal9000@cleverthis.com>
The `agents plan apply --format json` command was returning a raw
plan dictionary instead of the spec-required JSON envelope. This fix
introduces a dedicated `_apply_output_dict()` helper that wraps the
non-rich format output in the proper envelope structure with
`command`, `status`, `exit_code`, `data`, `timing`, and `messages`
fields.
The `data` field contains structured information about artifacts,
changes, project, applied_at, validation (test/lint/type_check),
sandbox_cleanup, and lifecycle metrics. Other commands (plan status,
plan cancel, plan use) remain unaffected — they continue using
`_plan_spec_dict`.
Tests: 16 Behave scenarios + 15 Robot Framework integration tests
added covering envelope structure, field presence, sandbox cleanup
state derivation from actual plan state, legacy fallback, cost
metadata, and command isolation.
ISSUES CLOSED: #9449
Document HAL 9000's contribution of the broad exception suppression
Semgrep guard (PR #9185, issue #9103) in CONTRIBUTORS.md per the
PR compliance checklist requirement.
Add BDD/Behave test scenarios for the existing --format/-f flag on `agents session tell`,
and update CHANGELOG.md and CONTRIBUTORS.md.
The implementation of --format on session tell exists in the codebase (commit 87a7ce35d),
but lacks dedicated BDD test coverage. This PR adds:
- 6 new Behave scenarios in features/session_cli.feature testing JSON, YAML, plain, table,
short flag (-f), and Rich output regression paths
- 6 corresponding step definitions in features/steps/session_cli_steps.py verifying
spec-compliant JSON envelopes, valid YAML/JSON output, ASCII table output, and Rich console
content preservation
- CHANGELOG.md entry under [Unreleased] documenting the --format flag feature
- CONTRIBUTORS.md entry crediting Jeffrey Phillips Freeman
Quality gates: lint ✓, typecheck ✓ (only pre-existing warnings about optional provider imports)
ISSUES CLOSED: #10466
Removed unconditional session.rollback() calls within exception handlers in:
- ProjectRepository.create()
- NamespacedProjectRepository.create() (IntegrityError handler)
- NamespacedProjectRepository.create() (OperationalError handler)
- NamespacedProjectRepository.update()
- NamespacedProjectRepository.delete()
The Unit of Work pattern already handles transaction rollback at the outer layer
via its except Exception: session.rollback() handler, making these inner rollbacks
redundant. SQLAlchemy automatically invalidates the transaction state when exceptions
occur after flush(), preventing partial data from being committed.
Removing the redundant rollbacks improves clarity, eliminates potential issues related
to exception chaining across retry boundary layers, and aligns repository implementations
with explicit transaction boundaries.
ISSUES CLOSED: #8179
Issue references corrected from #264 to #691 throughout all documentation.
The A2A stdio transport feature is tracked by issue #691, not #264 (which was
about resource registry tables in v3.0.0).
CHANGELOG.md: Updated issue reference and added .py path routing fix entry under
BDD tests: Added command construction assertions for all three connect scenarios
(module, .py script, executable) to verify subprocess.Popen receives correct args:
- Module paths (cleveragents.X): [python, -m, module]
- .py file paths: [python, file.py]
- Executable paths: [executable_path]
The connect() method in A2aStdioTransport incorrectly routed literal .py
script paths (e.g. "agent.py") through `python -m` which expects Python
module names. Fixed to use `python agent_path` for direct script execution
while keeping module paths (cleveragents.*) via `-m` and executables unchanged.
Also resolved merge conflict markers in CONTRIBUTORS.md and added changelog
entry for the A2A stdio transport feature under [Unreleased]. Added BDD
test coverage entry.
ISSUES CLOSED: #264
Replaced insecure str.startswith(root + "/") path containment checks in
tool/path_mapper.py (_is_under) and application/services/llm_actors.py
(_write_to_sandbox) with semantic os.path.relpath comparisons to prevent
sibling-directory prefix-collision path traversal attacks.
The string-prefix approach was vulnerable: a sandbox root of /tmp/sandbox
would incorrectly allow access to /tmp/sandboxmalicious/file.txt because
"/tmp/sandboxmalicious/file" starts with "/tmp/sandbox".
Security specification mandates all path containment checks use
Path.is_relative_to() or equivalent semantic comparison.
Added BDD test coverage in features/path_containment_security.feature
with @tdd_issue_7478 tags for the prefix-collision attack scenarios.
ISSUES CLOSED: #7478
CHANGELOG.md and CONTRIBUTORS.md both referenced #10590, which is an
open PR not an issue. The correct issue is #8616. Also removed the
duplicate ### Added heading in CHANGELOG.md that preceded the entry.
CONTRIBUTORS.md now references PR #11106 / issue #8616.
ISSUES CLOSED: #8616
Implement the ContextStrategy Protocol for pluggable context assembly strategies
in the ACMS pipeline. Includes six built-in strategies, a StrategyRegistry service
with plugin discovery support, thread-safe operations, and comprehensive BDD tests.
ISSUES CLOSED: #10590
ACMSExecutePhaseContextAssembler previously instantiated the plain
ACMSPipeline when no pipeline was explicitly provided, missing production
Phase 1 optimizations including confidence-weighted strategy selection,
proportional budget allocation with min-budget enforcement, parallel
strategy execution with circuit breaking, and per-stage timing instrumentation.
The default is now ContextAssemblyPipeline which provides all of these
capabilities while remaining a drop-in replacement for ACMSPipeline.
ISSUES CLOSED: #10027
Epic #8477: added ExecutePhaseDecisionHook as the Execute-phase mirror of
StrategizeDecisionHook. Provides six recording methods for implementation
choices, tool invocations, error recovery, validation responses, subplan
spawn, and resource selection during execution contexts. Captures full
context snapshots with SHA-256 hashes and persists decisions atomically
via DecisionService. Includes comprehensive Behave test coverage.
ISSUES CLOSED: #8477
This PR implements the Invariant data model and database schema for the
v3.2.0 milestone. The Invariant feature enables the system to define, store,
and manage invariant rules that can be evaluated against system state.
- Alembic migration m3_001_invariants_table creates the invariants table
with columns: id (UUID), description (text), created_at (timestamp),
is_active (bool, default True), with index on is_active for efficiency
- SQLAlchemy ORM InvariantModel in
cleveragents.infrastructure.database.models.InvariantModel
- M3 merge migration to resolve Alembic head conflict
- BDD Behave scenarios (10 test cases) in features/invariant_model.feature
- Robot Framework integration tests in robot/invariant_model.robot
- Updated CHANGELOG.md and CONTRIBUTORS.md
- Restored status-check CI aggregation job
ISSUES CLOSED: #8524
When subprocess.Popen() fails during LSP server initialization (e.g.
FileNotFoundError for missing command or general OSError), partially-allocated
pipe resources and internal file descriptors could be left in an inconsistent
state. This was caused by _process potentially containing a stale reference if
an exception occurred between pipe allocation and the Popen object being fully
returned.
Fix: Add explicit self._process = None resets in three places:
1) Before subprocess.Popen() — ensures clean initial state even across retries
2) In FileNotFoundError handler — guards against intermediate error states
3) In OSError handler — general safety net for all subprocess failures
This prevents:
- Orphaned child processes never terminated (zombie processes)
- File descriptor leaks from partially-allocated pipes
- Transports stuck in ambiguous 'started but not live' state
Tests added: Two new Behave scenarios verify _process is None after both
FileNotFoundError and OSError during start().
ISSUES CLOSED: #10597
Implemented cache invalidation for CleanupService to fix stale sandbox paths
being reported after purge() completes. The _sandbox_dirs_cache is now
invalidated after _purge_sandboxes() so subsequent scan() calls re-read the
filesystem instead of returning already-deleted paths.
Changes:
- Added self._sandbox_dirs_cache = None at end of _purge_sandboxes()
- Updated docstring to document cache invalidation behavior
- Created comprehensive BDD test coverage with 5 scenarios under new
features/cleanup_service_cache_invalidation.feature and step definitions
- Updated CHANGELOG.md with bug fix entry
- Updated CONTRIBUTORS.md with PR #8257
ISSUES CLOSED: #7527
- Move Gherkin scenario tags from inline to separate lines before Scenario keywords in feature spec
- Remove HAL 9000 prose contribution entry from name list in CONTRIBUTORS.md per project conventions
- Add commit footer: ISSUES CLOSED: #7112
ISSUES CLOSED: #7112
Adds SandboxDirsCache to track filesystem paths of sandbox-created directories indexed by plan_id. Cache is purged in cleanup_all(), cleanup_abandoned(), clear_sandbox_dirs_cache(), and the at-exit handler matching the existing clear_boundary_cache() invalidation.
Add _state == McpClientState.STARTING guard inside the threading.RLock in
start() and _ensure_started() so that concurrent callers see the in-progress
state and return immediately, preventing double initialisation of the MCP
server connection.
- Move _CountingTransport test double from inline step file to dedicated
features/mocks/counting_mcp_transport.py per CONTRIBUTING.md mock placement rules
- Updated step definitions to import CountingMCPTransport from new location
- Added Race condition entry to CHANGELOG under [Unreleased] -> Fixed
- Added contributor credit for McpClient race condition fix
ISSUES CLOSED: #10438
Align the resource and skill management showcase with review feedback: consistent resource type counts (101), explicit save-to-disk instructions before each skill registration command, metadata callouts for non-obvious behaviors (Config: unknown, capability summary zeros, local/linear-tracker 0-tool count), and README framing to acknowledge platform feature walkthroughs.
Remove obsolete tdd_issue tags from coverage threshold Robot tests now that the noxfile enforces COVERAGE_THRESHOLD = 97.
Harden the Skip If No LLM Keys E2E helper with per-key regex validation and log-level suppression to prevent credential leakage in CI logs. Restore the Resolve LLM Actor keyword that was inadvertently removed from common_e2e.resource.
Update CHANGELOG.md and CONTRIBUTORS.md per project requirements.
ISSUES CLOSED: #4470
- Remove duplicate @then decorator on step_verify_peak_concurrency_limit
(caused AmbiguousStep error crashing all 8 unit test feature files)
- Rename "the subplans should have been executed in order" to
"the subplans should have been executed in sequential order" to
avoid conflict with pre-existing step in subplan_execution_steps.py
- Remove 13 additional @then step definitions that duplicated steps in
subplan_execution_steps.py; alias context.exec_result and
context.validation_error in @when steps so pre-existing steps work
- Replace two # type: ignore comments (lines 438, 453) with typed
Any variables per zero-tolerance policy
- Apply ruff format to fix formatting (long import wrapping, list comps)
- Add CHANGELOG entry and CONTRIBUTORS entry for #9555
ISSUES CLOSED: #9609
Applied ruff format fix to tui_permissions_screen_steps.py and corrected the step text mismatch in execution_environment.feature where 'it should not contain' was not updated to 'the container types should not contain' when the step definition was renamed.
ISSUES CLOSED: #10488
- Extract FakeEmbeddings, RelevanceScoringStrategy, AdaptiveContextSelector,
ContextFusionStrategy, and _pack_budget from features/steps/ into new
features/mocks/advanced_context_strategies_mocks.py per mock-placement rules
- Remove sys.path manipulation from robot/helper_advanced_context_strategies.py;
import directly from features.mocks instead of features/steps
- Add None guard before selected.assemble() in step_assemble_context_query
- Add explicit ValueError for unknown strategy types in step_load_yaml_strategy
and load_strategy_from_yaml_impl
ISSUES CLOSED: #7574
Implemented spec-compliant JSON, YAML, plain, and rich outputs for `agents project context set`. Added BDD coverage verifying the new output structure across formats.\n\nISSUES CLOSED: #6319
The CHANGELOG.md and CONTRIBUTORS.md entries from db048dd2 claimed this
PR adds `features/pure_graph_coverage.feature`. That standalone file
was intentionally not added (and an earlier draft was removed) because
the PureGraph scenarios already live in
`features/consolidated_langgraph.feature` — adding a standalone file
would have created duplicate Behave scenarios against the same step
definitions and broken `unit_tests` CI.
Reword both entries to accurately describe what this PR delivers:
- the previously orphaned `features/steps/pure_graph_coverage_steps.py`
is now driven through the existing consolidated feature file
- Robot Framework integration tests in `robot/langgraph/pure_graph.robot`
backed by `robot/langgraph/pure_graph_lib.py`
- ASV benchmarks in `benchmarks/pure_graph_bench.py`
ISSUES CLOSED: #9531