源码快照 @ 2026-09-01 (source-only, 剔除非源码素材)
Creator App Tests / PR Spam Gate (push) Skipped
Frontend Tests / PR Spam Gate (push) Skipped
NPM Format (website & console) / PR Spam Gate (push) Skipped
Pre-commit Checks / PR Spam Gate (push) Skipped
QwenPaw Creator Plugin Release / check-version (push) Canceled after 0s
QwenPaw Creator Plugin Release / upload-oss (push) Canceled after 0s
Tests / PR Spam Gate (push) Skipped
CodeQL / CodeQL (python) (push) Canceled after 0s
CodeQL / CodeQL (typescript) (push) Canceled after 0s
Creator App Tests / Creator Backend Tests (push) Canceled after 0s
Creator App Tests / Creator UI Build & Tests (push) Canceled after 0s
E2E Smoke Tests / Playwright UI Smoke (push) Canceled after 0s
Frontend Tests / Detect console changes (push) Canceled after 0s
NPM Format (website & console) / website format check (push) Canceled after 0s
NPM Format (website & console) / console format check (push) Canceled after 0s
Pre-commit Checks / Pre-commit (push) Canceled after 0s
QwenPaw Data Plugin Release / check-version (push) Canceled after 0s
Tests / Detect code changes (push) Canceled after 0s
Frontend Tests / Vitest Unit Tests (push) Canceled after 0s
Frontend Tests / Frontend Summary (push) Canceled after 0s
QwenPaw Data Plugin Release / upload-oss (push) Canceled after 0s
Tests / Maintainer Approval (push) Canceled after 0s
Tests / Unit Tests - py3.11 - macos-latest (push) Canceled after 0s
Tests / Unit Tests - py3.11 - ubuntu-latest (push) Canceled after 0s
Tests / Unit Tests - py3.13 - ubuntu-latest (push) Canceled after 0s
Tests / Unit Tests - py3.11 - windows-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - macos-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - ubuntu-latest (push) Canceled after 0s
Tests / Contract Tests - py3.13 - ubuntu-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - windows-latest (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - fallback (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p2 (push) Canceled after 0s
Tests / Coverage Report (push) Canceled after 0s
Tests / Test Summary (push) Canceled after 0s
Creator App Tests / PR Spam Gate (push) Skipped
Frontend Tests / PR Spam Gate (push) Skipped
NPM Format (website & console) / PR Spam Gate (push) Skipped
Pre-commit Checks / PR Spam Gate (push) Skipped
QwenPaw Creator Plugin Release / check-version (push) Canceled after 0s
QwenPaw Creator Plugin Release / upload-oss (push) Canceled after 0s
Tests / PR Spam Gate (push) Skipped
CodeQL / CodeQL (python) (push) Canceled after 0s
CodeQL / CodeQL (typescript) (push) Canceled after 0s
Creator App Tests / Creator Backend Tests (push) Canceled after 0s
Creator App Tests / Creator UI Build & Tests (push) Canceled after 0s
E2E Smoke Tests / Playwright UI Smoke (push) Canceled after 0s
Frontend Tests / Detect console changes (push) Canceled after 0s
NPM Format (website & console) / website format check (push) Canceled after 0s
NPM Format (website & console) / console format check (push) Canceled after 0s
Pre-commit Checks / Pre-commit (push) Canceled after 0s
QwenPaw Data Plugin Release / check-version (push) Canceled after 0s
Tests / Detect code changes (push) Canceled after 0s
Frontend Tests / Vitest Unit Tests (push) Canceled after 0s
Frontend Tests / Frontend Summary (push) Canceled after 0s
QwenPaw Data Plugin Release / upload-oss (push) Canceled after 0s
Tests / Maintainer Approval (push) Canceled after 0s
Tests / Unit Tests - py3.11 - macos-latest (push) Canceled after 0s
Tests / Unit Tests - py3.11 - ubuntu-latest (push) Canceled after 0s
Tests / Unit Tests - py3.13 - ubuntu-latest (push) Canceled after 0s
Tests / Unit Tests - py3.11 - windows-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - macos-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - ubuntu-latest (push) Canceled after 0s
Tests / Contract Tests - py3.13 - ubuntu-latest (push) Canceled after 0s
Tests / Contract Tests - py3.11 - windows-latest (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - macos-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - fallback (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - ubuntu-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.13 - ubuntu-latest - p2 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p0 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p1 (push) Canceled after 0s
Tests / Integrated Tests - py3.11 - windows-latest - p2 (push) Canceled after 0s
Tests / Coverage Report (push) Canceled after 0s
Tests / Test Summary (push) Canceled after 0s
This commit is contained in:
commit
1a3a4ccde1
4652 files changed
+1891610
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,572 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Tests for declarative custom loop modes."""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from agentscope.message import Msg, TextBlock
|
||||
from pydantic import ValidationError
|
||||
|
||||
from qwenpaw.config.config import (
|
||||
CustomLoopModeConfig,
|
||||
GateInstanceConfig,
|
||||
LoopConfig,
|
||||
_sanitize_custom_loop_modes,
|
||||
_sanitize_loop_config,
|
||||
)
|
||||
from qwenpaw.loop.catalog import CompletionRubricParams, get_gate_catalog
|
||||
from qwenpaw.loop.compiler import compile_loop_mode
|
||||
from qwenpaw.loop.gates import (
|
||||
CompletionRubricGate,
|
||||
QualitativeRubricGate,
|
||||
StopAction,
|
||||
)
|
||||
from qwenpaw.loop.gates.limits import (
|
||||
TimeoutGate,
|
||||
TokenBudgetGate,
|
||||
ToolCallBudgetGate,
|
||||
)
|
||||
from qwenpaw.modes.custom_loop import (
|
||||
CustomLoopController,
|
||||
DeclarativeLoopMode,
|
||||
LoopModeActivationStore,
|
||||
load_custom_loop_modes,
|
||||
)
|
||||
from qwenpaw.app.workspace.workspace_plugins import WorkspacePlugins
|
||||
from qwenpaw.runtime.slash_command_registry import SlashCommandRegistry
|
||||
|
||||
|
||||
def _gate(
|
||||
gate_id: str,
|
||||
gate_type: str,
|
||||
params: dict | None = None,
|
||||
) -> GateInstanceConfig:
|
||||
return GateInstanceConfig(
|
||||
id=gate_id,
|
||||
type=gate_type,
|
||||
params=params or {},
|
||||
)
|
||||
|
||||
|
||||
def _mode(*gates: GateInstanceConfig) -> CustomLoopModeConfig:
|
||||
return CustomLoopModeConfig(
|
||||
id="quality",
|
||||
name="Quality",
|
||||
slash_command="quality",
|
||||
enabled=True,
|
||||
gates=list(gates),
|
||||
)
|
||||
|
||||
|
||||
def test_completion_rubric_defaults_require_continued_work() -> None:
|
||||
params = CompletionRubricParams()
|
||||
|
||||
assert "work must continue" in params.prompt
|
||||
|
||||
|
||||
def test_loop_config_rejects_duplicate_normalized_names() -> None:
|
||||
"""Display names stay unambiguous for user-facing mode pickers."""
|
||||
with pytest.raises(
|
||||
ValidationError,
|
||||
match="Custom loop mode names must be unique",
|
||||
):
|
||||
LoopConfig(
|
||||
custom_modes=[
|
||||
_mode(_gate("limit", "iteration")),
|
||||
CustomLoopModeConfig(
|
||||
id="quality-copy",
|
||||
name=" quality ",
|
||||
slash_command="quality-copy",
|
||||
enabled=False,
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_loop_config_rejects_unicode_casefold_names() -> None:
|
||||
"""Save validation and reload sanitization use one normalization."""
|
||||
with pytest.raises(
|
||||
ValidationError,
|
||||
match="Custom loop mode names must be unique",
|
||||
):
|
||||
LoopConfig(
|
||||
custom_modes=[
|
||||
CustomLoopModeConfig(
|
||||
id="street",
|
||||
name="Straße",
|
||||
slash_command="street",
|
||||
),
|
||||
CustomLoopModeConfig(
|
||||
id="street-copy",
|
||||
name="STRASSE",
|
||||
slash_command="street-copy",
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_loop_config_rejects_gate_outside_builtin_catalog() -> None:
|
||||
with pytest.raises(ValidationError, match="Unknown built-in gate type"):
|
||||
LoopConfig(
|
||||
custom_modes=[
|
||||
CustomLoopModeConfig(
|
||||
id="unsafe",
|
||||
name="Unsafe",
|
||||
slash_command="unsafe",
|
||||
enabled=False,
|
||||
gates=[
|
||||
GateInstanceConfig(
|
||||
id="python",
|
||||
type="python_gate",
|
||||
enabled=False,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_invalid_saved_custom_modes_do_not_block_loop_config(caplog) -> None:
|
||||
"""Stale optional modes are skipped while valid Loop data still loads."""
|
||||
valid = _mode(_gate("limit", "iteration")).model_dump()
|
||||
stale_retry = {
|
||||
**valid,
|
||||
"id": "stale-retry",
|
||||
"name": "Stale retry",
|
||||
"slash_command": "stale-retry",
|
||||
"gates": [
|
||||
{
|
||||
"id": "retry",
|
||||
"type": "text_response_retry",
|
||||
"enabled": True,
|
||||
"params": {"max_interventions": 1},
|
||||
},
|
||||
],
|
||||
}
|
||||
stale_completion = {
|
||||
**valid,
|
||||
"id": "stale-completion",
|
||||
"name": "Stale completion",
|
||||
"slash_command": "stale-completion",
|
||||
"gates": [
|
||||
{
|
||||
"id": "completion",
|
||||
"type": "completion_rubric",
|
||||
"enabled": True,
|
||||
"params": {"criteria": []},
|
||||
},
|
||||
],
|
||||
}
|
||||
data = {
|
||||
"running": {
|
||||
"loop": {
|
||||
"custom_modes": [
|
||||
valid,
|
||||
stale_retry,
|
||||
stale_completion,
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_sanitize_custom_loop_modes(data, "default")
|
||||
loop = LoopConfig.model_validate(data["running"]["loop"])
|
||||
|
||||
assert [mode.id for mode in loop.custom_modes] == ["quality"]
|
||||
assert "text_response_retry" in caplog.text
|
||||
assert "criteria" in caplog.text
|
||||
|
||||
|
||||
def test_invalid_builtin_loop_data_falls_back_to_defaults(caplog) -> None:
|
||||
"""Invalid built-in Loop values must not block the Agent profile."""
|
||||
data = {
|
||||
"running": {
|
||||
"loop": {
|
||||
"iteration": {
|
||||
"enabled": True,
|
||||
"max_iterations": 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_sanitize_loop_config(data, "default")
|
||||
loop = LoopConfig.model_validate(data["running"]["loop"])
|
||||
|
||||
assert loop == LoopConfig()
|
||||
assert "using defaults" in caplog.text
|
||||
|
||||
|
||||
def test_custom_mode_rejects_conflicting_completion_gates() -> None:
|
||||
with pytest.raises(ValidationError, match="exclusive group"):
|
||||
_mode(
|
||||
_gate("qualitative", "qualitative_rubric"),
|
||||
_gate(
|
||||
"rubric",
|
||||
"completion_rubric",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def test_compiler_preserves_pipeline_order() -> None:
|
||||
handler = compile_loop_mode(
|
||||
_mode(
|
||||
_gate("tools", "tool_call_budget", {"max_calls": 5}),
|
||||
_gate("limit", "iteration", {"max_iterations": 10}),
|
||||
),
|
||||
)
|
||||
|
||||
assert [gate.name for gate in handler.gates] == ["tools", "limit"]
|
||||
assert [gate.priority for gate in handler.gates] == [0, 10]
|
||||
|
||||
|
||||
def test_catalog_contains_only_seven_builtin_gates() -> None:
|
||||
entries = get_gate_catalog().describe()
|
||||
|
||||
assert {entry["type"] for entry in entries} == {
|
||||
"iteration",
|
||||
"doom_loop",
|
||||
"token_budget",
|
||||
"timeout",
|
||||
"tool_call_budget",
|
||||
"qualitative_rubric",
|
||||
"completion_rubric",
|
||||
}
|
||||
groups = {entry["type"]: entry["exclusive_group"] for entry in entries}
|
||||
assert groups["qualitative_rubric"] == "completion_rubric"
|
||||
assert groups["completion_rubric"] == "completion_rubric"
|
||||
assert groups["iteration"] is None
|
||||
|
||||
|
||||
def _rubric_context() -> tuple[dict, Msg]:
|
||||
state = SimpleNamespace(
|
||||
context=[
|
||||
Msg(
|
||||
name="user",
|
||||
role="user",
|
||||
content=[TextBlock(type="text", text="Finish the task")],
|
||||
),
|
||||
],
|
||||
)
|
||||
agent = SimpleNamespace(state=state)
|
||||
final = Msg(
|
||||
name="assistant",
|
||||
role="assistant",
|
||||
content=[TextBlock(type="text", text="Completed")],
|
||||
)
|
||||
return (
|
||||
{
|
||||
"agent": agent,
|
||||
"final_msg": final,
|
||||
"has_tool_calls": False,
|
||||
"iteration": 1,
|
||||
},
|
||||
final,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_qualitative_rubric_only_revises_text_responses() -> None:
|
||||
gate = QualitativeRubricGate(
|
||||
rubric="Check every explicit requirement.",
|
||||
max_evaluations=1,
|
||||
)
|
||||
gate.reset_turn()
|
||||
context, _candidate = _rubric_context()
|
||||
|
||||
context["has_tool_calls"] = True
|
||||
tool_result = await gate.check(context)
|
||||
context["has_tool_calls"] = False
|
||||
revision = await gate.check(context)
|
||||
finished = await gate.check(context)
|
||||
still_finished = await gate.check(context)
|
||||
|
||||
assert tool_result.action == StopAction.BYPASS
|
||||
assert revision.action == StopAction.INTERRUPT_AND_CONTINUE
|
||||
assert gate.build_continuation() == "Check every explicit requirement."
|
||||
assert finished.action == StopAction.BYPASS
|
||||
assert still_finished.action == StopAction.BYPASS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_completion_rubric_accepts_configured_signal() -> None:
|
||||
gate = CompletionRubricGate(
|
||||
prompt="The request is complete.",
|
||||
completion_signal="DONE",
|
||||
)
|
||||
gate.reset_turn()
|
||||
context, candidate = _rubric_context()
|
||||
|
||||
request = await gate.check(context)
|
||||
context["final_msg"] = Msg(
|
||||
name="assistant",
|
||||
role="assistant",
|
||||
content=[
|
||||
TextBlock(
|
||||
type="text",
|
||||
text=" done \n",
|
||||
),
|
||||
],
|
||||
)
|
||||
result = await gate.check(context)
|
||||
|
||||
assert request.action == StopAction.INTERRUPT_AND_CONTINUE
|
||||
assert result.action == StopAction.TERMINATE
|
||||
assert result.final_message is candidate
|
||||
assert "passed" in result.reason
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_completion_rubric_requests_bounded_revision() -> None:
|
||||
gate = CompletionRubricGate(
|
||||
prompt="The request is complete.",
|
||||
max_evaluations=2,
|
||||
)
|
||||
gate.reset_turn()
|
||||
context, _candidate = _rubric_context()
|
||||
|
||||
await gate.check(context)
|
||||
evaluation_prompt = gate.build_continuation()
|
||||
assert "Do not merely report" in evaluation_prompt
|
||||
|
||||
context["final_msg"] = Msg(
|
||||
name="assistant",
|
||||
role="assistant",
|
||||
content=[
|
||||
TextBlock(
|
||||
type="text",
|
||||
text="NOT COMPLETED",
|
||||
),
|
||||
],
|
||||
)
|
||||
revision = await gate.check(context)
|
||||
assert gate.build_continuation() == evaluation_prompt
|
||||
|
||||
context["has_tool_calls"] = True
|
||||
tool_result = await gate.check(context)
|
||||
context["has_tool_calls"] = False
|
||||
context["final_msg"] = Msg(
|
||||
name="assistant",
|
||||
role="assistant",
|
||||
content=[
|
||||
TextBlock(
|
||||
type="text",
|
||||
text="Task is still incomplete",
|
||||
),
|
||||
],
|
||||
)
|
||||
stopped = await gate.check(context)
|
||||
|
||||
assert revision.action == StopAction.INTERRUPT_AND_CONTINUE
|
||||
assert tool_result.action == StopAction.BYPASS
|
||||
assert stopped.action == StopAction.TERMINATE
|
||||
assert "2 evaluations" in stopped.reason
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_custom_mode_command_activates_current_session() -> None:
|
||||
config = _mode(_gate("limit", "iteration"))
|
||||
store = LoopModeActivationStore()
|
||||
mode = DeclarativeLoopMode(config, store)
|
||||
plugins = SimpleNamespace(
|
||||
slash_command_registry=SlashCommandRegistry(),
|
||||
stop_handlers=[],
|
||||
modes=[mode],
|
||||
)
|
||||
workspace = SimpleNamespace(plugins=plugins)
|
||||
mode.setup(workspace)
|
||||
message = Msg(
|
||||
name="user",
|
||||
role="user",
|
||||
content=[TextBlock(type="text", text="/quality verify it")],
|
||||
)
|
||||
ctx = SimpleNamespace(
|
||||
session_id="session-a",
|
||||
input_msgs=[message],
|
||||
workspace=workspace,
|
||||
)
|
||||
|
||||
response = await mode.commands()[0].handler(ctx, "verify it")
|
||||
|
||||
assert response is None
|
||||
assert store.current("session-a") == "quality"
|
||||
assert message.content[0].text == "verify it"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_switching_custom_mode_requires_explicit_exit() -> None:
|
||||
store = LoopModeActivationStore()
|
||||
quality = DeclarativeLoopMode(
|
||||
_mode(_gate("quality-limit", "iteration")),
|
||||
store,
|
||||
)
|
||||
research_config = CustomLoopModeConfig(
|
||||
id="research",
|
||||
name="Research",
|
||||
slash_command="research",
|
||||
enabled=True,
|
||||
gates=[_gate("research-limit", "iteration")],
|
||||
)
|
||||
research = DeclarativeLoopMode(research_config, store)
|
||||
quality.handler.reset_session = MagicMock()
|
||||
workspace = SimpleNamespace(
|
||||
plugins=SimpleNamespace(modes=[quality, research]),
|
||||
)
|
||||
ctx = SimpleNamespace(
|
||||
session_id="session-a",
|
||||
input_msgs=[],
|
||||
workspace=workspace,
|
||||
)
|
||||
|
||||
await quality.commands()[0].handler(ctx, "")
|
||||
await research.commands()[0].handler(ctx, "")
|
||||
|
||||
assert store.current("session-a") == "quality"
|
||||
quality.handler.reset_session.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mode_off_clears_activation_and_handler_state() -> None:
|
||||
store = LoopModeActivationStore()
|
||||
quality = DeclarativeLoopMode(
|
||||
_mode(_gate("quality-limit", "iteration")),
|
||||
store,
|
||||
)
|
||||
quality.handler.reset_session = MagicMock()
|
||||
controller = CustomLoopController(store)
|
||||
workspace = SimpleNamespace(
|
||||
plugins=SimpleNamespace(modes=[quality, controller]),
|
||||
)
|
||||
ctx = SimpleNamespace(
|
||||
session_id="session-a",
|
||||
input_msgs=[],
|
||||
workspace=workspace,
|
||||
)
|
||||
store.activate("session-a", "quality")
|
||||
|
||||
response = await controller.commands()[0].handler(ctx, "off")
|
||||
|
||||
assert store.current("session-a") is None
|
||||
assert "disabled" in response.content[0].text
|
||||
quality.handler.reset_session.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_custom_mode_rejects_active_builtin_mode() -> None:
|
||||
store = LoopModeActivationStore()
|
||||
custom = DeclarativeLoopMode(
|
||||
_mode(_gate("quality-limit", "iteration")),
|
||||
store,
|
||||
)
|
||||
goal = SimpleNamespace(
|
||||
name="goal",
|
||||
is_active=lambda ctx: True,
|
||||
)
|
||||
workspace = SimpleNamespace(
|
||||
plugins=SimpleNamespace(modes=[goal, custom]),
|
||||
)
|
||||
ctx = SimpleNamespace(
|
||||
session_id="session-a",
|
||||
input_msgs=[],
|
||||
workspace=workspace,
|
||||
)
|
||||
|
||||
response = await custom.commands()[0].handler(ctx, "verify it")
|
||||
|
||||
assert store.current("session-a") is None
|
||||
assert "End the active goal mode" in response.content[0].text
|
||||
|
||||
|
||||
def test_loader_registers_multiple_enabled_modes() -> None:
|
||||
quality = _mode(_gate("limit", "iteration"))
|
||||
research = CustomLoopModeConfig(
|
||||
id="research",
|
||||
name="Research",
|
||||
slash_command="research",
|
||||
enabled=True,
|
||||
gates=[_gate("tools", "tool_call_budget")],
|
||||
)
|
||||
disabled = CustomLoopModeConfig(
|
||||
id="draft",
|
||||
name="Draft",
|
||||
slash_command="draft",
|
||||
enabled=False,
|
||||
)
|
||||
config = SimpleNamespace(
|
||||
running=SimpleNamespace(
|
||||
loop=SimpleNamespace(
|
||||
custom_modes=[quality, research, disabled],
|
||||
),
|
||||
),
|
||||
)
|
||||
workspace = SimpleNamespace(
|
||||
config=config,
|
||||
plugins=WorkspacePlugins(),
|
||||
)
|
||||
|
||||
load_custom_loop_modes(workspace)
|
||||
|
||||
assert [mode.name for mode in workspace.plugins.modes] == [
|
||||
"custom:quality",
|
||||
"custom:research",
|
||||
"custom-loop-control",
|
||||
]
|
||||
assert workspace.plugins.slash_command_registry.names() == [
|
||||
"mode",
|
||||
"quality",
|
||||
"research",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_token_budget_accumulates_each_iteration(monkeypatch) -> None:
|
||||
gate = TokenBudgetGate(max_total_tokens=10)
|
||||
gate.reset_turn()
|
||||
monkeypatch.setattr(
|
||||
gate,
|
||||
"_current_usage",
|
||||
lambda: {"prompt_tokens": 4, "completion_tokens": 2},
|
||||
)
|
||||
|
||||
first = await gate.check({"iteration": 1})
|
||||
second = await gate.check({"iteration": 2})
|
||||
|
||||
assert first.action == StopAction.BYPASS
|
||||
assert second.action == StopAction.TERMINATE
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_timeout_gate_stops_only_when_boundary_is_checked(
|
||||
monkeypatch,
|
||||
) -> None:
|
||||
values = iter([15.0, 16.0])
|
||||
monkeypatch.setattr(
|
||||
"qwenpaw.loop.gates.limits.time",
|
||||
SimpleNamespace(monotonic=lambda: next(values)),
|
||||
)
|
||||
gate = TimeoutGate(max_seconds=2)
|
||||
gate.activate(SimpleNamespace(started_at=14.0))
|
||||
|
||||
before_limit = await gate.check({"iteration": 1})
|
||||
at_next_boundary = await gate.check({"iteration": 2})
|
||||
|
||||
assert before_limit.action == StopAction.BYPASS
|
||||
assert at_next_boundary.action == StopAction.TERMINATE
|
||||
assert "Loop time limit" in at_next_boundary.reason
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_tool_call_budget_enforces_per_tool_limit() -> None:
|
||||
gate = ToolCallBudgetGate(max_calls=10, per_tool={"search": 1})
|
||||
gate.reset_turn()
|
||||
message = SimpleNamespace(
|
||||
content=[{"type": "tool_call", "name": "search"}],
|
||||
)
|
||||
agent = SimpleNamespace(state=SimpleNamespace(context=[message]))
|
||||
|
||||
result = await gate.check({"iteration": 1, "agent": agent})
|
||||
|
||||
assert result.action == StopAction.TERMINATE
|
||||
assert "search" in result.reason
|
||||
@@ -0,0 +1,173 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# pylint: disable=protected-access
|
||||
"""Tests for DefaultMode gate ownership and lifecycle."""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from qwenpaw.loop.gates.doom_loop import DoomLoopGate
|
||||
from qwenpaw.loop.gates.iteration import IterationGate
|
||||
from qwenpaw.modes.default import DefaultMode
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _force_session_id():
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="test-session",
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
def _running_config(
|
||||
max_iters=100,
|
||||
doom_enabled=True,
|
||||
rubric_enabled=True,
|
||||
):
|
||||
doom_stage = SimpleNamespace(
|
||||
after=3,
|
||||
action="stop",
|
||||
prompt="doom",
|
||||
)
|
||||
doom = SimpleNamespace(
|
||||
enabled=doom_enabled,
|
||||
window_size=3,
|
||||
similarity_threshold=1.0,
|
||||
stages=[doom_stage],
|
||||
)
|
||||
iteration = SimpleNamespace(
|
||||
enabled=True,
|
||||
max_iterations=max_iters,
|
||||
)
|
||||
rubric = SimpleNamespace(
|
||||
enabled=rubric_enabled,
|
||||
prompt="continue working",
|
||||
max_interventions=1,
|
||||
)
|
||||
loop = SimpleNamespace(
|
||||
iteration=iteration,
|
||||
doom_loop=doom,
|
||||
rubric=rubric,
|
||||
)
|
||||
return SimpleNamespace(
|
||||
max_iters=max_iters,
|
||||
loop=loop,
|
||||
)
|
||||
|
||||
|
||||
def _workspace():
|
||||
plugins = SimpleNamespace(stop_handlers=[])
|
||||
return SimpleNamespace(plugins=plugins)
|
||||
|
||||
|
||||
def _context(config, agent=None):
|
||||
return SimpleNamespace(
|
||||
agent_config=SimpleNamespace(running=config),
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
|
||||
def _find_gate(mode, gate_type):
|
||||
return next(
|
||||
gate for gate in mode.handler.gates if isinstance(gate, gate_type)
|
||||
)
|
||||
|
||||
|
||||
def test_setup_registers_one_default_handler():
|
||||
"""Mode setup registers one default-scoped handler."""
|
||||
workspace = _workspace()
|
||||
mode = DefaultMode()
|
||||
|
||||
mode.setup(workspace)
|
||||
|
||||
assert len(workspace.plugins.stop_handlers) == 1
|
||||
registration = workspace.plugins.stop_handlers[0]
|
||||
assert registration.handler is mode.handler
|
||||
assert registration.scope == "default"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_turn_start_builds_configured_gates():
|
||||
"""First turn builds gates from the current running config."""
|
||||
mode = DefaultMode()
|
||||
|
||||
await mode.on_turn_start(_context(_running_config()))
|
||||
|
||||
assert len(mode.handler.gates) == 3
|
||||
assert _find_gate(mode, IterationGate)._state() is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_next_turn_resets_iteration_and_doom_state():
|
||||
"""A new turn resets current-session state without rebuilding gates."""
|
||||
mode = DefaultMode()
|
||||
ctx = _context(_running_config(max_iters=10))
|
||||
await mode.on_turn_start(ctx)
|
||||
iteration = _find_gate(mode, IterationGate)
|
||||
doom = _find_gate(mode, DoomLoopGate)
|
||||
|
||||
for _ in range(5):
|
||||
await iteration.check({})
|
||||
doom.record("tool_a", "hash")
|
||||
assert iteration._state().iteration == 5
|
||||
assert len(doom._state().history) == 1
|
||||
|
||||
await mode.on_turn_start(ctx)
|
||||
|
||||
assert iteration._state().iteration == 0
|
||||
assert len(doom._state().history) == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_next_turn_reactivates_exhausted_iteration_gate():
|
||||
"""A terminated iteration gate is active again on the next turn."""
|
||||
mode = DefaultMode()
|
||||
ctx = _context(_running_config(max_iters=1))
|
||||
await mode.on_turn_start(ctx)
|
||||
iteration = _find_gate(mode, IterationGate)
|
||||
|
||||
await iteration.check({})
|
||||
assert iteration._state() is None
|
||||
|
||||
await mode.on_turn_start(ctx)
|
||||
|
||||
assert iteration._state() is not None
|
||||
assert iteration._state().iteration == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_config_change_rebuilds_without_duplicate_registration():
|
||||
"""Hot-loaded config replaces gates on the existing handler."""
|
||||
workspace = _workspace()
|
||||
mode = DefaultMode()
|
||||
mode.setup(workspace)
|
||||
await mode.on_turn_start(_context(_running_config()))
|
||||
|
||||
await mode.on_turn_start(
|
||||
_context(
|
||||
_running_config(
|
||||
doom_enabled=False,
|
||||
rubric_enabled=False,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
assert len(mode.handler.gates) == 1
|
||||
assert len(workspace.plugins.stop_handlers) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_conversation_reset_clears_session_and_pending_state():
|
||||
"""Full reset tears down current gates and deferred decisions."""
|
||||
agent = SimpleNamespace(_gate_pending_stop=object())
|
||||
mode = DefaultMode()
|
||||
await mode.on_turn_start(_context(_running_config(), agent))
|
||||
iteration = _find_gate(mode, IterationGate)
|
||||
|
||||
await mode.on_conversation_reset(_context(_running_config(), agent))
|
||||
|
||||
assert iteration._state() is None
|
||||
assert agent._gate_pending_stop is None
|
||||
@@ -0,0 +1,147 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# pylint: disable=redefined-outer-name,protected-access
|
||||
"""Tests for DoomLoopGate reset behaviour."""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from qwenpaw.loop.gates.base import StopAction
|
||||
from qwenpaw.loop.gates.doom_loop import DoomLoopGate
|
||||
|
||||
|
||||
def _stage(after, action="stop", prompt="stop"):
|
||||
return SimpleNamespace(
|
||||
after=after,
|
||||
action=action,
|
||||
prompt=prompt,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _force_session_id():
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="test-session",
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def gate():
|
||||
g = DoomLoopGate(
|
||||
window_size=3,
|
||||
similarity_threshold=1.0,
|
||||
stages=[
|
||||
_stage(3, "modify_prompt", "warning"),
|
||||
_stage(6, "stop", "doom stop"),
|
||||
],
|
||||
)
|
||||
g.activate(None)
|
||||
g._ensure_state()
|
||||
return g
|
||||
|
||||
|
||||
def test_reset_clears_history(gate):
|
||||
"""reset() empties the history deque."""
|
||||
gate.record("tool_a", "hash1")
|
||||
gate.record("tool_a", "hash1")
|
||||
assert len(gate._ensure_state().history) == 2
|
||||
gate.reset_turn()
|
||||
assert len(gate._ensure_state().history) == 0
|
||||
|
||||
|
||||
def test_reset_clears_counters(gate):
|
||||
"""reset() zeroes consecutive_hits and prompt."""
|
||||
state = gate._ensure_state()
|
||||
state.consecutive_hits = 5
|
||||
state.prompt = "some warning"
|
||||
state.last_recorded_iter = 10
|
||||
gate.reset_turn()
|
||||
state = gate._ensure_state()
|
||||
assert state.consecutive_hits == 0
|
||||
assert state.prompt == ""
|
||||
assert state.last_recorded_iter == -1
|
||||
|
||||
|
||||
def test_reset_keeps_gate_active(gate):
|
||||
"""reset() does NOT deactivate the gate."""
|
||||
gate.reset_turn()
|
||||
assert gate._state() is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_false_positive_after_reset(gate):
|
||||
"""After reset, fresh calls don't trigger doom loop."""
|
||||
for _ in range(3):
|
||||
gate.record("tool_a", "hash1")
|
||||
gate.reset_turn()
|
||||
gate.record("tool_b", "hash2")
|
||||
result = await gate.check({"iteration": 0})
|
||||
assert result.action == StopAction.BYPASS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cross_request_no_bleed(gate):
|
||||
"""Simulates two user requests: reset prevents bleed."""
|
||||
for _ in range(3):
|
||||
gate.record("search", "abc")
|
||||
|
||||
result = await gate.check({"iteration": 3})
|
||||
assert result is not None
|
||||
|
||||
gate.reset_turn()
|
||||
gate.record("search", "abc")
|
||||
result = await gate.check({"iteration": 1})
|
||||
assert result.action == StopAction.BYPASS
|
||||
|
||||
|
||||
def test_reset_when_no_state():
|
||||
"""reset_turn() is a no-op when gate has no state."""
|
||||
g = DoomLoopGate(
|
||||
window_size=3,
|
||||
similarity_threshold=1.0,
|
||||
stages=[],
|
||||
)
|
||||
g.reset_turn()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_isolation():
|
||||
"""reset() only affects current session."""
|
||||
g = DoomLoopGate(
|
||||
window_size=3,
|
||||
similarity_threshold=1.0,
|
||||
stages=[
|
||||
_stage(3, "stop", "doom"),
|
||||
],
|
||||
)
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="s1",
|
||||
):
|
||||
g._ensure_state()
|
||||
g.record("t", "h")
|
||||
g.record("t", "h")
|
||||
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="s2",
|
||||
):
|
||||
g._ensure_state()
|
||||
g.record("t", "h")
|
||||
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="s1",
|
||||
):
|
||||
g.reset_turn()
|
||||
assert len(g._state().history) == 0
|
||||
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="s2",
|
||||
):
|
||||
assert len(g._state().history) == 1
|
||||
@@ -0,0 +1,180 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Tests for StopHandler peer-gate reset on continuation."""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional, cast
|
||||
|
||||
import pytest
|
||||
|
||||
from qwenpaw.loop.gates.base import (
|
||||
StopAction,
|
||||
StopGate,
|
||||
StopHandlerResult,
|
||||
)
|
||||
from qwenpaw.loop.gates.handler import StopHandler
|
||||
|
||||
|
||||
class _AlwaysContinueGate(StopGate):
|
||||
"""Returns INTERRUPT_AND_CONTINUE with reset_peers."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
reset_peers: bool = False,
|
||||
):
|
||||
self._reset_peers = reset_peers
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "always-continue"
|
||||
|
||||
async def check(
|
||||
self,
|
||||
ctx: Any,
|
||||
) -> Optional[StopHandlerResult]:
|
||||
return StopHandlerResult(
|
||||
action=StopAction.INTERRUPT_AND_CONTINUE,
|
||||
reason="test",
|
||||
reset_peers=self._reset_peers,
|
||||
)
|
||||
|
||||
def build_continuation(self) -> str:
|
||||
return "keep going"
|
||||
|
||||
|
||||
class _ResettableGate(StopGate):
|
||||
"""Gate that tracks reset_turn() calls."""
|
||||
|
||||
def __init__(self, gate_name: str = "resettable"):
|
||||
self._name = gate_name
|
||||
self.reset_count = 0
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return self._name
|
||||
|
||||
async def check(
|
||||
self,
|
||||
ctx: Any,
|
||||
) -> Optional[StopHandlerResult]:
|
||||
return None
|
||||
|
||||
def reset_turn(self) -> None:
|
||||
self.reset_count += 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reset_peers_true_resets_others():
|
||||
"""CONTINUE with reset_peers=True resets other gates."""
|
||||
handler = StopHandler()
|
||||
trigger = _AlwaysContinueGate(reset_peers=True)
|
||||
peer = _ResettableGate("peer")
|
||||
handler.register(trigger)
|
||||
handler.register(peer)
|
||||
|
||||
await handler({})
|
||||
assert peer.reset_count == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reset_peers_true_skips_trigger():
|
||||
"""The triggering gate itself is NOT reset."""
|
||||
handler = StopHandler()
|
||||
|
||||
class _ContinueResettable(StopGate):
|
||||
def __init__(self):
|
||||
self.reset_count = 0
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return "trigger"
|
||||
|
||||
@property
|
||||
def priority(self):
|
||||
return 1
|
||||
|
||||
async def check(self, ctx):
|
||||
return StopHandlerResult(
|
||||
action=StopAction.INTERRUPT_AND_CONTINUE,
|
||||
reason="test",
|
||||
reset_peers=True,
|
||||
)
|
||||
|
||||
def build_continuation(self):
|
||||
return "go"
|
||||
|
||||
def reset_turn(self):
|
||||
self.reset_count += 1
|
||||
|
||||
trigger = _ContinueResettable()
|
||||
handler.register(trigger)
|
||||
|
||||
await handler({})
|
||||
assert trigger.reset_count == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reset_peers_false_no_reset():
|
||||
"""CONTINUE with reset_peers=False does NOT reset."""
|
||||
handler = StopHandler()
|
||||
trigger = _AlwaysContinueGate(reset_peers=False)
|
||||
peer = _ResettableGate("peer")
|
||||
handler.register(trigger)
|
||||
handler.register(peer)
|
||||
|
||||
await handler({})
|
||||
assert peer.reset_count == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_multiple_peers_all_reset():
|
||||
"""All peers (except trigger) are reset."""
|
||||
handler = StopHandler()
|
||||
trigger = _AlwaysContinueGate(reset_peers=True)
|
||||
p1 = _ResettableGate("p1")
|
||||
p2 = _ResettableGate("p2")
|
||||
handler.register(trigger)
|
||||
handler.register(p1)
|
||||
handler.register(p2)
|
||||
|
||||
await handler({})
|
||||
assert p1.reset_count == 1
|
||||
assert p2.reset_count == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_gate_without_reset_method_skipped():
|
||||
"""Default no-op reset_turn() is accepted."""
|
||||
handler = StopHandler()
|
||||
trigger = _AlwaysContinueGate(reset_peers=True)
|
||||
|
||||
class _NoResetGate(StopGate):
|
||||
@property
|
||||
def name(self):
|
||||
return "no-reset"
|
||||
|
||||
async def check(self, ctx):
|
||||
return None
|
||||
|
||||
handler.register(trigger)
|
||||
handler.register(_NoResetGate())
|
||||
|
||||
result = await handler({})
|
||||
assert result.action == StopAction.INTERRUPT_AND_CONTINUE
|
||||
|
||||
|
||||
def test_reset_turn_skips_legacy_gate_without_reset_method():
|
||||
"""A legacy gate does not prevent later gates from resetting."""
|
||||
handler = StopHandler()
|
||||
peer = _ResettableGate("peer")
|
||||
|
||||
class _LegacyGate:
|
||||
name = "legacy"
|
||||
priority = 1
|
||||
|
||||
handler.register(cast(StopGate, _LegacyGate()))
|
||||
handler.register(peer)
|
||||
|
||||
handler.reset_turn()
|
||||
|
||||
assert peer.reset_count == 1
|
||||
@@ -0,0 +1,141 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# pylint: disable=redefined-outer-name,protected-access
|
||||
"""Tests for IterationGate reset behaviour."""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from qwenpaw.loop.gates.base import StopAction
|
||||
from qwenpaw.loop.gates.iteration import IterationGate
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _force_session_id():
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="test-session",
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def gate():
|
||||
g = IterationGate(max_iterations=5)
|
||||
g.activate()
|
||||
return g
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_check_increments(gate):
|
||||
"""check() increments the counter each call."""
|
||||
for _ in range(4):
|
||||
result = await gate.check({})
|
||||
assert result.action == StopAction.BYPASS
|
||||
result = await gate.check({})
|
||||
assert result.action == StopAction.TERMINATE
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reset_clears_counter(gate):
|
||||
"""reset_turn() sets iteration back to 0."""
|
||||
for _ in range(3):
|
||||
await gate.check({})
|
||||
gate.reset_turn()
|
||||
state = gate._state()
|
||||
assert state is not None
|
||||
assert state.iteration == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reset_preserves_max(gate):
|
||||
"""reset_turn() keeps max_iterations unchanged."""
|
||||
gate.reset_turn()
|
||||
state = gate._state()
|
||||
assert state.max_iterations == 5
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reset_allows_full_budget(gate):
|
||||
"""After reset the full iteration budget is available."""
|
||||
for _ in range(3):
|
||||
await gate.check({})
|
||||
gate.reset_turn()
|
||||
for _ in range(4):
|
||||
result = await gate.check({})
|
||||
assert result.action == StopAction.BYPASS
|
||||
result = await gate.check({})
|
||||
assert result.action == StopAction.TERMINATE
|
||||
|
||||
|
||||
def test_reset_when_inactive():
|
||||
"""reset_turn() activates a fresh session state."""
|
||||
g = IterationGate(max_iterations=5)
|
||||
g.reset_turn()
|
||||
assert g._state() is not None
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def gate_pair():
|
||||
"""Instance with state in two sessions."""
|
||||
g = IterationGate(max_iterations=5)
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="session-a",
|
||||
):
|
||||
g.activate()
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="session-b",
|
||||
):
|
||||
g.activate()
|
||||
return g
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reset_session_isolation(gate_pair):
|
||||
"""reset_turn() only affects the current session."""
|
||||
g = gate_pair
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="session-a",
|
||||
):
|
||||
for _ in range(3):
|
||||
await g.check({})
|
||||
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="session-b",
|
||||
):
|
||||
for _ in range(2):
|
||||
await g.check({})
|
||||
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="session-a",
|
||||
):
|
||||
g.reset_turn()
|
||||
assert g._state().iteration == 0
|
||||
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="session-b",
|
||||
):
|
||||
assert g._state().iteration == 2
|
||||
|
||||
|
||||
def test_reset_session_removes_only_current_session(gate_pair):
|
||||
"""reset_session() removes only the current conversation state."""
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="session-a",
|
||||
):
|
||||
gate_pair.reset_session()
|
||||
assert gate_pair._state() is None
|
||||
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="session-b",
|
||||
):
|
||||
assert gate_pair._state() is not None
|
||||
@@ -0,0 +1,113 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Tests for user-editable Mission defaults."""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from qwenpaw.config.config import MissionLoopModeConfig
|
||||
from qwenpaw.modes.mission.handler import (
|
||||
parse_mission_args,
|
||||
start_mission,
|
||||
)
|
||||
from qwenpaw.modes.mission.prompts import build_master_prompt
|
||||
from qwenpaw.modes.mission.state import read_loop_config
|
||||
|
||||
|
||||
def test_mission_config_defaults_and_bounds() -> None:
|
||||
"""Mission settings expose conservative defaults with validation."""
|
||||
config = MissionLoopModeConfig()
|
||||
|
||||
assert config.max_iterations == 20
|
||||
assert config.max_retries_per_story == 3
|
||||
assert config.default_verification_instructions == ""
|
||||
assert config.default_verify_command == ""
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
MissionLoopModeConfig(max_retries_per_story=11)
|
||||
|
||||
|
||||
def test_mission_args_use_defaults_and_allow_command_override() -> None:
|
||||
"""Per-mission arguments override only values explicitly provided."""
|
||||
defaults = parse_mission_args(
|
||||
"implement the feature",
|
||||
default_max_iterations=12,
|
||||
default_verify_command="npm test",
|
||||
)
|
||||
override = parse_mission_args(
|
||||
"implement the feature --max-iterations 7 --verify pytest",
|
||||
default_max_iterations=12,
|
||||
default_verify_command="npm test",
|
||||
)
|
||||
|
||||
assert defaults["max_iterations"] == 12
|
||||
assert defaults["verify_commands"] == "npm test"
|
||||
assert override["max_iterations"] == 7
|
||||
assert override["verify_commands"] == "pytest"
|
||||
|
||||
|
||||
def test_master_prompt_uses_configured_story_retry_limit() -> None:
|
||||
"""Retry configuration replaces the previous hard-coded prompt value."""
|
||||
prompt = build_master_prompt(
|
||||
loop_dir="/tmp/mission",
|
||||
agent_id="agent",
|
||||
max_retries_per_story=6,
|
||||
)
|
||||
|
||||
assert "Max 6 retries per story" in prompt
|
||||
assert "Max 3 retries per story" not in prompt
|
||||
|
||||
|
||||
def test_master_prompt_includes_verification_instructions() -> None:
|
||||
"""Verifier receives natural-language guidance separately from commands."""
|
||||
prompt = build_master_prompt(
|
||||
loop_dir="/tmp/mission",
|
||||
agent_id="agent",
|
||||
verification_instructions=(
|
||||
"Check Windows path handling and inspect the rendered UI."
|
||||
),
|
||||
verify_commands="pytest -q",
|
||||
)
|
||||
|
||||
assert "Check Windows path handling" in prompt
|
||||
assert "**Verify command**: pytest -q" in prompt
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_start_mission_persists_editable_defaults(tmp_path) -> None:
|
||||
"""New missions persist settings used by the existing workflow."""
|
||||
git_context = {
|
||||
"git_installed": False,
|
||||
"is_git_repo": False,
|
||||
"default_branch": "",
|
||||
"repo_root": "",
|
||||
}
|
||||
with patch(
|
||||
"qwenpaw.modes.mission.handler.detect_git_context",
|
||||
new=AsyncMock(return_value=git_context),
|
||||
):
|
||||
_, loop_dir = await start_mission(
|
||||
task_text="Implement the approved feature",
|
||||
project_dir=tmp_path,
|
||||
agent_workspace_dir=tmp_path / "agent-workspace",
|
||||
agent_id="agent",
|
||||
session_id="session",
|
||||
verify_commands="pytest -q",
|
||||
verification_instructions="Check accessibility manually.",
|
||||
max_iterations=14,
|
||||
max_retries_per_story=5,
|
||||
)
|
||||
|
||||
config = read_loop_config(loop_dir)
|
||||
assert config["max_iterations"] == 14
|
||||
assert config["max_retries_per_story"] == 5
|
||||
assert config["verify_commands"] == "pytest -q"
|
||||
assert config["verification_instructions"] == (
|
||||
"Check accessibility manually."
|
||||
)
|
||||
assert loop_dir.parent == tmp_path / ".qwenpaw" / "missions"
|
||||
assert config["source_project_dir"] == str(tmp_path)
|
||||
assert config["workspace_dir"] == str(tmp_path / "agent-workspace")
|
||||
assert config["mission_run_dir"] == str(tmp_path)
|
||||
@@ -0,0 +1,227 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# pylint: disable=protected-access
|
||||
"""Tests for mode-owned handler selection and reset lifecycle."""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from qwenpaw.loop.gates.base import (
|
||||
StopAction,
|
||||
StopHandlerRegistration,
|
||||
)
|
||||
from qwenpaw.loop.gates.handler import StopHandler
|
||||
from qwenpaw.loop.gates.rubric import QualitativeRubricGate
|
||||
from qwenpaw.loop.gates.runner import _filter_by_scope
|
||||
from qwenpaw.modes.goal.goal_mode import GoalMode, GoalSession
|
||||
from qwenpaw.modes.mission import MissionMode
|
||||
from qwenpaw.modes.mission.gates import MissionGate
|
||||
from qwenpaw.modes.mission.state import write_loop_config
|
||||
from qwenpaw.runtime.runtime import Runtime
|
||||
|
||||
|
||||
def _registration(
|
||||
scope: str,
|
||||
*,
|
||||
is_active=None,
|
||||
) -> StopHandlerRegistration:
|
||||
return StopHandlerRegistration(
|
||||
plugin_id=f"test-{scope}",
|
||||
handler=StopHandler(),
|
||||
name=f"{scope}-handler",
|
||||
scope=scope,
|
||||
is_active=is_active,
|
||||
)
|
||||
|
||||
|
||||
def test_explicit_mode_scope_replaces_default_scope():
|
||||
"""An active mode handler suppresses the default handler."""
|
||||
default = _registration("default")
|
||||
goal = _registration("goal", is_active=lambda: True)
|
||||
|
||||
selected = _filter_by_scope([default, goal])
|
||||
|
||||
assert selected == [goal]
|
||||
|
||||
|
||||
def test_inactive_mode_scope_keeps_default_scope():
|
||||
"""An inactive mode handler leaves the default handler selected."""
|
||||
default = _registration("default")
|
||||
goal = _registration("goal", is_active=lambda: False)
|
||||
|
||||
selected = _filter_by_scope([default, goal])
|
||||
|
||||
assert selected == [default]
|
||||
|
||||
|
||||
def test_unscoped_plugin_handler_is_always_selected():
|
||||
"""Unscoped plugin handlers remain available with explicit modes."""
|
||||
plugin = _registration("")
|
||||
default = _registration("default")
|
||||
goal = _registration("goal", is_active=lambda: True)
|
||||
|
||||
selected = _filter_by_scope([plugin, default, goal])
|
||||
|
||||
assert selected == [plugin, goal]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_goal_reset_removes_only_current_session():
|
||||
"""Conversation reset does not clear another goal conversation."""
|
||||
mode = GoalMode()
|
||||
mode._sessions["session-a"] = GoalSession(goal="first")
|
||||
mode._sessions["session-b"] = GoalSession(goal="second")
|
||||
ctx = SimpleNamespace(session_id="session-a")
|
||||
|
||||
await mode.on_conversation_reset(ctx)
|
||||
|
||||
assert "session-a" not in mode._sessions
|
||||
assert "session-b" in mode._sessions
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_goal_activation_rejects_an_active_explicit_mode():
|
||||
"""A persistent session mode must be exited before another starts."""
|
||||
mode = GoalMode()
|
||||
active = SimpleNamespace(
|
||||
name="mission",
|
||||
is_active=lambda _ctx: True,
|
||||
)
|
||||
ctx = SimpleNamespace(
|
||||
session_id="session-a",
|
||||
workspace=SimpleNamespace(
|
||||
plugins=SimpleNamespace(modes=[active, mode]),
|
||||
),
|
||||
)
|
||||
|
||||
response = await mode.commands()[0].handler(ctx, "Fix the tests")
|
||||
|
||||
assert response is not None
|
||||
assert "active mission mode" in response.content[0].text
|
||||
assert mode.get_session("session-a") is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mission_turn_start_restores_persisted_session(tmp_path):
|
||||
"""Mission state is active before stop-handler scope selection."""
|
||||
mode = MissionMode()
|
||||
mode._gate = MissionGate()
|
||||
ctx = SimpleNamespace(
|
||||
mode_state={
|
||||
"mission": {
|
||||
"active": True,
|
||||
"loop_dir": str(tmp_path),
|
||||
"phase": "execution",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="mission-session",
|
||||
):
|
||||
await mode.on_turn_start(ctx)
|
||||
assert mode._is_gate_active()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mission_state_uses_session_lifecycle_and_reset(tmp_path):
|
||||
"""Stage 1 phase persists and reset clears the same mode_state."""
|
||||
write_loop_config(
|
||||
tmp_path,
|
||||
{"current_phase": "prd_generation"},
|
||||
)
|
||||
mode = MissionMode()
|
||||
mode._gate = MissionGate()
|
||||
ctx = SimpleNamespace(mode_state={})
|
||||
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="mission-session",
|
||||
):
|
||||
mode._gate.activate_for_mission(tmp_path)
|
||||
await mode.sync_persistent_state(ctx)
|
||||
|
||||
assert ctx.mode_state == {
|
||||
"mission": {
|
||||
"active": True,
|
||||
"loop_dir": str(tmp_path),
|
||||
"phase": "prd_generation",
|
||||
},
|
||||
}
|
||||
|
||||
write_loop_config(
|
||||
tmp_path,
|
||||
{"current_phase": "execution_confirmed"},
|
||||
)
|
||||
await mode.sync_persistent_state(ctx)
|
||||
|
||||
assert ctx.mode_state["mission"]["phase"] == "execution_confirmed"
|
||||
|
||||
await mode.on_conversation_reset(ctx)
|
||||
|
||||
assert ctx.mode_state == {}
|
||||
assert not mode._is_gate_active()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_runtime_awaits_mode_turn_start_callbacks():
|
||||
"""Runtime awaits each registered mode turn-start callback."""
|
||||
calls = []
|
||||
|
||||
class _Mode:
|
||||
name = "test"
|
||||
|
||||
async def on_turn_start(self, ctx):
|
||||
calls.append(ctx)
|
||||
|
||||
workspace = SimpleNamespace(
|
||||
plugins=SimpleNamespace(modes=[_Mode()]),
|
||||
)
|
||||
runtime = Runtime(workspace=workspace, app_services=None)
|
||||
ctx = SimpleNamespace()
|
||||
|
||||
await runtime._start_modes(ctx)
|
||||
|
||||
assert calls == [ctx]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_qualitative_rubric_state_is_session_isolated():
|
||||
"""Resetting one rubric session leaves another session untouched."""
|
||||
gate = QualitativeRubricGate(
|
||||
rubric="continue",
|
||||
max_evaluations=1,
|
||||
)
|
||||
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="session-a",
|
||||
):
|
||||
first_a = await gate.check({})
|
||||
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="session-b",
|
||||
):
|
||||
first_b = await gate.check({})
|
||||
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="session-a",
|
||||
):
|
||||
gate.reset_session()
|
||||
next_a = await gate.check({})
|
||||
|
||||
with patch(
|
||||
"qwenpaw.loop.gates.loop_gate._session_id",
|
||||
return_value="session-b",
|
||||
):
|
||||
next_b = await gate.check({})
|
||||
|
||||
assert first_a.action == StopAction.INTERRUPT_AND_CONTINUE
|
||||
assert first_b.action == StopAction.INTERRUPT_AND_CONTINUE
|
||||
assert next_a.action == StopAction.INTERRUPT_AND_CONTINUE
|
||||
assert next_b.action == StopAction.BYPASS
|
||||
@@ -0,0 +1,70 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Tests for stop-handler result application."""
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from qwenpaw.loop.gates.base import StopAction, StopHandlerResult
|
||||
from qwenpaw.loop.gates.handler import StopHandler
|
||||
from qwenpaw.loop.gates.runner import apply_stop_result, check_pending_gates
|
||||
from qwenpaw.modes.goal.gates import GoalTurnGate
|
||||
|
||||
|
||||
def _goal_handler() -> StopHandler:
|
||||
"""Build an active goal handler for continuation tests."""
|
||||
session = SimpleNamespace(
|
||||
active=True,
|
||||
goal="Ship the feature",
|
||||
iteration=0,
|
||||
last_verdict="",
|
||||
max_iterations=20,
|
||||
max_tokens=300000,
|
||||
tokens_used=0,
|
||||
)
|
||||
mode: Any = SimpleNamespace(session_by_ctx_var=lambda: session)
|
||||
handler = StopHandler()
|
||||
handler.register(GoalTurnGate(mode))
|
||||
return handler
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_goal_tool_call_does_not_defer_continuation() -> None:
|
||||
"""Tool calls continue naturally without an injected user prompt."""
|
||||
agent = SimpleNamespace(_gate_pending_stop=None)
|
||||
result = await _goal_handler()({"has_tool_calls": True})
|
||||
|
||||
assert result.action == StopAction.INTERRUPT_AND_CONTINUE
|
||||
assert result.continuation_message.startswith(
|
||||
"Continue working toward the active goal.",
|
||||
)
|
||||
|
||||
apply_stop_result(agent, result, is_tool_call=True)
|
||||
|
||||
assert vars(agent) == {"_gate_pending_stop": None}
|
||||
assert check_pending_gates(agent) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_goal_text_exit_keeps_continuation_prompt() -> None:
|
||||
"""A text-only exit still receives the active goal continuation."""
|
||||
result = await _goal_handler()({"has_tool_calls": False})
|
||||
|
||||
assert result.action == StopAction.INTERRUPT_AND_CONTINUE
|
||||
assert result.continuation_message.startswith(
|
||||
"Continue working toward the active goal.",
|
||||
)
|
||||
|
||||
|
||||
def test_tool_call_defers_termination() -> None:
|
||||
"""A terminating decision waits until tool results are processed."""
|
||||
agent = SimpleNamespace(_gate_pending_stop=None)
|
||||
result = StopHandlerResult(
|
||||
action=StopAction.TERMINATE,
|
||||
reason="Goal iteration limit reached",
|
||||
)
|
||||
|
||||
apply_stop_result(agent, result, is_tool_call=True)
|
||||
|
||||
assert check_pending_gates(agent) is result
|
||||
assert vars(agent)["_gate_pending_stop"] is None
|
||||
Reference in new issue
Block a user