fix(company): stop/resume identity truth, failure-path closure, quota park

OBS-11 — stop/resume killed pure-native runs over a phantom external pin.
Role templates' preferred_external_agent leaked into execution identity even
when the user requested native and execution actually ran native; on resume
the availability gate trusted the pin and failed every non-terminal item.
Root fixes across the whole chain:
- Staffing card per-role defaults are now the RESOLVED backend (explicit
  session agent choice > runnable template preference > native), never a
  hardcoded external default; seat enrichment and the dispatch selector's
  locked branch downgrade provably unavailable externals to native and
  record the wish in execution_agent_unavailable.
- The resume availability gate fails closed only when a resumable external
  session actually exists; a bare pin heals to native (snapshot AND task
  durable identity) and the run resumes — mirroring dispatch fallback.
- Suspend-checkpoint replies: force_resume (chat/headless spelling) is
  recognized alongside ui_force_resume, and bare continuation tokens
  (English and Chinese spellings) take the plain-resume path instead of
  being routed to the final decider as content, which reopened the
  already-approved intake card.

OBS-5 — failed runs never closed and dropped new input. The dispatcher's
convergence exit now settles terminally-failed runs (status=failed,
lifecycle=closed_failed, run_failure metadata) and emits a
company_run_failure_review card whose replies never swallow messages:
dismiss acknowledges, content falls through so normal routing starts a
fresh run. _maybe_resume_existing_company_runtime no longer re-executes a
terminally-failed tree: control replies get an honest closed status,
content-bearing input starts a new run.

OBS-6 — provider quota exhaustion terminally failed work items. Rate-limit
rejections are classified (LLMProvider.is_rate_limit_error, covering
status codes, exception types, and English/Chinese provider error text),
the agent runtime raises typed ProviderQuotaExhaustedError instead of
burning conversation-feedback retries, and the company dispatcher parks:
the item returns to READY (attempt interrupted, no terminal failure), the
member session idles, and claiming backs off exponentially (60s doubling
to a 900s cap; a quiet 30min resets the streak) before resuming
automatically.

Verified end-to-end on the real minimax-m3 campaign: same goal, same 300s
stop point, same run shape that previously killed the whole tree within
90s now resumes cleanly and completes with all items approved; staffing
defaults native for all 11 roles.

Tests: test_stop_resume_native_pin (10), test_run_failure_settlement (6),
test_provider_quota_park (9); attempt-ledger, recruiter, and
suspend-resume suites updated to the new contracts (their old assertions
pinned the defective behaviors).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
LZH-YS1998
2026-07-28 16:59:56 +08:00
parent 14ee8806de
commit d14f3920e0
10 changed files with 1185 additions and 39 deletions
+29 -16
View File
@@ -420,7 +420,12 @@ class ResumeAvailabilityGateTests(unittest.IsolatedAsyncioTestCase):
)
return engine
async def test_resume_fails_closed_when_pinned_agent_unavailable(self) -> None:
async def test_resume_heals_pin_to_native_when_agent_unavailable(self) -> None:
"""A pin to a disabled external agent with NO resumable external
session heals to native and resumes (OBS-11): dispatch would fall
back to native anyway, so failing the item punished runs — including
fully native ones whose metadata inherited a template preference —
for an availability gap that does not block execution."""
store = await self._store()
task = await self._seed(store, external_agent="codex")
engine = self._engine(store, available=["opencode"]) # codex disabled
@@ -449,19 +454,25 @@ class ResumeAvailabilityGateTests(unittest.IsolatedAsyncioTestCase):
self.assertIsNotNone(response)
refreshed_item = await store.get_delegation_work_item("work-item-1")
assert refreshed_item is not None
self.assertEqual(refreshed_item.phase, Phase.FAILED)
self.assertIn("codex", str(refreshed_item.blocked_reason or ""))
refreshed_task = await store.get_task(task.id)
assert refreshed_task is not None
self.assertEqual(refreshed_task.status, TaskStatus.FAILED)
self.assertEqual(refreshed_item.phase, Phase.RUNNING)
self.assertIn("tasks", executed)
resumed_task = executed["tasks"][0]
self.assertIsNone(resumed_task.assigned_external_agent)
self.assertEqual(
refreshed_task.metadata.get("resume_unavailable_external_agent"),
resumed_task.metadata.get("selected_execution_agent"), "native"
)
self.assertEqual(
resumed_task.metadata.get("resume_execution_agent_healed_from"),
"codex",
)
# The runtime still executed (the rest of the org resumes normally).
self.assertIn("tasks", executed)
pin = dict(
resumed_task.metadata.get(
"_company_runtime_resume_execution_agent_pin", {}
)
)
self.assertEqual(pin.get("selected_execution_agent"), "native")
async def test_plain_message_after_gate_failure_converges_without_revival(self) -> None:
async def test_plain_message_after_terminal_failure_converges_without_revival(self) -> None:
"""A plain text follow-up (final-decider routing path) on a run whose
decider card failed terminally must drain the checkpoint and must not
clobber the FAILED task back to PENDING (InvalidPhaseTransition crash
@@ -480,12 +491,14 @@ class ResumeAvailabilityGateTests(unittest.IsolatedAsyncioTestCase):
return "runtime resumed"
engine.company_executor = DummyCompanyExecutor()
# First resume: gate fails the codex-pinned decider card closed.
await engine._maybe_resume_checkpoint(
"continue",
"sess-parent",
reply_metadata={"ui_force_resume": True},
)
# The decider card failed terminally after the suspend (the resume
# gate no longer fails pins without external sessions — OBS-11 — so
# the terminal failure is seeded directly).
await store.update_delegation_work_item("work-item-1", phase=Phase.FAILED)
failed_task = await store.get_task(task.id)
assert failed_task is not None
failed_task.status = TaskStatus.FAILED
await store.save_task(failed_task)
refreshed_item = await store.get_delegation_work_item("work-item-1")
assert refreshed_item is not None
self.assertEqual(refreshed_item.phase, Phase.FAILED)
+42 -4
View File
@@ -411,7 +411,19 @@ class CompanyRecruiterFlowTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(checkpoint.payload["recommended_action"], "auto_recruit")
self.assertEqual(checkpoint.payload["staffing_defaults"]["source"], "system")
self.assertTrue(all(role["default_selection"]["kind"] == "fallback" for role in checkpoint.payload["staffing_roles"]))
self.assertTrue(all(role["selected_agent"] == "codex" for role in checkpoint.payload["staffing_roles"]))
# Card defaults become per-role overrides on approve, so they must
# reflect what will actually run (OBS-11): the role template's
# external preference when it can run, native otherwise.
agents_by_role = {
role["role_id"]: role["selected_agent"]
for role in checkpoint.payload["staffing_roles"]
}
self.assertTrue(all(
role["selected_agent"] == role["default_agent"]
for role in checkpoint.payload["staffing_roles"]
))
self.assertEqual(agents_by_role.get("ceo"), "native")
self.assertEqual(agents_by_role.get("senior_engineer"), "codex")
self.assertEqual(llm.calls, [])
self.assertEqual(tasks, [])
await store.close()
@@ -634,7 +646,21 @@ class CompanyRecruiterFlowTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(checkpoint.payload["staffing_pool"]["employees"], [])
self.assertGreater(len(checkpoint.payload["staffing_roles"]), 0)
self.assertTrue(all(role["default_selection"]["kind"] == "fallback" for role in checkpoint.payload["staffing_roles"]))
self.assertTrue(all(role["selected_agent"] == "codex" for role in checkpoint.payload["staffing_roles"]))
# Card defaults become per-role overrides on approve, so they must
# reflect what will actually run (OBS-11): the role template's
# external preference when it can run, native otherwise.
agents_by_role = {
role["role_id"]: role["selected_agent"]
for role in checkpoint.payload["staffing_roles"]
}
self.assertTrue(all(
role["selected_agent"] == role["default_agent"]
for role in checkpoint.payload["staffing_roles"]
))
# decision.preferred_agent="opencode" is an explicit session-level
# choice and outranks role template preferences.
self.assertEqual(agents_by_role.get("ceo"), "opencode")
self.assertEqual(agents_by_role.get("senior_engineer"), "opencode")
template_ids = {item["template_id"] for item in checkpoint.payload["staffing_pool"]["templates"]}
self.assertIn("engineering-frontend-developer", template_ids)
self.assertEqual(llm.calls, [])
@@ -744,7 +770,7 @@ class CompanyRecruiterFlowTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(senior_role["selected_agent"], "opencode")
ceo_role = next(role for role in payload["staffing_roles"] if role["role_id"] == "ceo")
self.assertEqual(ceo_role["default_selection"], {"kind": "fallback", "id": ""})
self.assertEqual(ceo_role["selected_agent"], "codex")
self.assertEqual(ceo_role["selected_agent"], "native")
await store.close()
async def test_confirmed_session_reuses_staffing_defaults_without_recruiter_llm(self) -> None:
@@ -1476,7 +1502,19 @@ class CompanyRecruiterFlowTests(unittest.IsolatedAsyncioTestCase):
self.assertIsNotNone(checkpoint)
self.assertEqual(checkpoint.checkpoint_type, "company_staffing_selection")
self.assertEqual(checkpoint.payload["staffing_defaults"]["source"], "system")
self.assertTrue(all(role["selected_agent"] == "codex" for role in checkpoint.payload["staffing_roles"]))
# Card defaults become per-role overrides on approve, so they must
# reflect what will actually run (OBS-11): the role template's
# external preference when it can run, native otherwise.
agents_by_role = {
role["role_id"]: role["selected_agent"]
for role in checkpoint.payload["staffing_roles"]
}
self.assertTrue(all(
role["selected_agent"] == role["default_agent"]
for role in checkpoint.payload["staffing_roles"]
))
self.assertEqual(agents_by_role.get("ceo"), "native")
self.assertEqual(agents_by_role.get("senior_engineer"), "codex")
await store.close()
async def test_deny_recruitment_cancels_execution(self) -> None:
+11 -7
View File
@@ -1146,8 +1146,12 @@ class CompanyRuntimeSuspendResumeTests(unittest.IsolatedAsyncioTestCase):
engine.company_executor = DummyCompanyExecutor()
# A bare "continue" is a control reply and takes the plain-resume
# path (OBS-11); only content-bearing text routes to the final
# decider as a follow-up.
followup_text = "Additional requirement: add a risk-analysis section to the report"
response = await engine._maybe_resume_checkpoint(
"continue",
followup_text,
"sess-parent",
)
checkpoints = await store.get_pending_checkpoints(
@@ -1161,18 +1165,18 @@ class CompanyRuntimeSuspendResumeTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(response, "ceo handled follow-up")
self.assertEqual(captured["plan"].metadata["final_decider_role_id"], "executor")
self.assertEqual(routed_task.status, TaskStatus.PENDING)
self.assertEqual(routed_task.context_snapshot["user_supplied_input"], "continue")
self.assertEqual(routed_task.metadata["latest_user_directive"], "continue")
self.assertEqual(routed_task.metadata["manager_mutation_user_input"], "continue")
self.assertEqual(routed_task.context_snapshot["user_supplied_input"], followup_text)
self.assertEqual(routed_task.metadata["latest_user_directive"], followup_text)
self.assertEqual(routed_task.metadata["manager_mutation_user_input"], followup_text)
self.assertTrue(routed_task.metadata["followup_routed_to_final_decider"])
self.assertEqual(checkpoints, [])
assert refreshed_item is not None
self.assertEqual(refreshed_item.phase, Phase.READY)
self.assertEqual(refreshed_item.metadata.get("dispatch_hold"), "")
self.assertEqual(refreshed_item.metadata.get("resume_source"), "primary_session_followup")
self.assertEqual(refreshed_item.metadata.get("resume_user_reply"), "continue")
self.assertEqual(refreshed_item.metadata.get("latest_user_directive"), "continue")
self.assertEqual(refreshed_item.metadata.get("manager_mutation_user_input"), "continue")
self.assertEqual(refreshed_item.metadata.get("resume_user_reply"), followup_text)
self.assertEqual(refreshed_item.metadata.get("latest_user_directive"), followup_text)
self.assertEqual(refreshed_item.metadata.get("manager_mutation_user_input"), followup_text)
self.assertEqual(refreshed_item.metadata.get("current_turn_mode"), "dispatch_required")
self.assertTrue(refreshed_item.metadata.get("followup_routed_to_final_decider"))
+187
View File
@@ -0,0 +1,187 @@
"""Regression: provider quota exhaustion parks work instead of failing it (OBS-6).
Quota/rate-limit rejections never reach the model, so in-place retries can
only fail; the previous behavior burned retries and terminally failed the
work item (killing intake and the whole run during a quota window). The fix:
``LLMProvider.is_rate_limit_error`` classifies these rejections, the agent
runtime raises typed ``ProviderQuotaExhaustedError``, and the company
dispatcher returns the item to READY with exponential dispatch backoff.
"""
from __future__ import annotations
import time
import unittest
from types import SimpleNamespace
from unittest.mock import AsyncMock
from opc.core.config import LLMConfig
from opc.core.models import CompanyMemberSession, Task
from opc.layer2_organization.company_mode import CompanyWorkItemExecutor
from opc.llm.provider import LLMProvider, ProviderQuotaExhaustedError
class RateLimitClassifierTests(unittest.TestCase):
def setUp(self) -> None:
self.llm = LLMProvider(LLMConfig())
def test_text_shapes_classify_as_rate_limit(self) -> None:
for message in (
"Error code: 429 - rate limit reached for requests",
"RateLimitError: too many requests, retry later",
"insufficient_quota: you exceeded your quota",
# localized error text from Chinese providers must classify too
"请求过于频繁,请稍后再试",
"当前 API 配额已用完",
):
self.assertTrue(
self.llm.is_rate_limit_error(RuntimeError(message)), message
)
def test_type_name_classifies(self) -> None:
class FakeRateLimitError(Exception):
pass
self.assertTrue(self.llm.is_rate_limit_error(FakeRateLimitError("nope")))
def test_status_code_classifies(self) -> None:
error = RuntimeError("throttled")
error.status_code = 429 # type: ignore[attr-defined]
self.assertTrue(self.llm.is_rate_limit_error(error))
def test_ordinary_errors_do_not_classify(self) -> None:
for message in (
"maximum context length exceeded",
"connection reset by peer",
"tool call arguments malformed",
"prompt tokens: 14290",
):
self.assertFalse(
self.llm.is_rate_limit_error(RuntimeError(message)), message
)
class QuotaExceptionChainTests(unittest.TestCase):
def _executor(self) -> CompanyWorkItemExecutor:
return CompanyWorkItemExecutor.__new__(CompanyWorkItemExecutor)
def test_direct_and_chained_detection(self) -> None:
executor = self._executor()
direct = ProviderQuotaExhaustedError("quota")
wrapped = RuntimeError("turn failed")
wrapped.__cause__ = ProviderQuotaExhaustedError("quota")
unrelated = RuntimeError("boom")
self.assertTrue(executor._exception_is_provider_quota(direct))
self.assertTrue(executor._exception_is_provider_quota(wrapped))
self.assertFalse(executor._exception_is_provider_quota(unrelated))
self.assertFalse(executor._exception_is_provider_quota(None))
class QuotaParkTests(unittest.IsolatedAsyncioTestCase):
def _executor(self) -> CompanyWorkItemExecutor:
executor = CompanyWorkItemExecutor.__new__(CompanyWorkItemExecutor)
executor.store = None
executor.runtime = SimpleNamespace(
_claimed_task_ids={"task-1"},
_claimed_work_item_ids=set(),
)
executor._quota_park_until = 0.0
executor._quota_park_streak = 0
executor._quota_last_park_at = 0.0
executor._emit_progress = AsyncMock()
executor._projection_id_for_task = lambda task: "cto::execute::x"
# Keep the unit test at the park-accounting level: the durable READY
# transition is exercised by the claim-release invariant suite.
executor._claimed_work_item_needs_cleanup = lambda member, task: False
return executor
def _session(self) -> CompanyMemberSession:
session = CompanyMemberSession.__new__(CompanyMemberSession)
session.status = "running"
session.resident_status = "running"
session.current_task_id = "task-1"
session.focused_work_item_id = "wi-1"
session.current_work_item = {"id": "wi-1"}
session.current_assignment = {"id": "wi-1"}
return session
async def test_park_backs_off_exponentially_and_idles_session(self) -> None:
executor = self._executor()
session = self._session()
task = Task(id="task-1", title="t", project_id="p", session_id="s")
await executor._handle_claimed_work_item_exception(
session, task, ProviderQuotaExhaustedError("429 rate limit")
)
now = time.monotonic()
self.assertEqual(executor._quota_park_streak, 1)
self.assertAlmostEqual(executor._quota_park_until - now, 60, delta=5)
self.assertEqual(session.status, "idle")
self.assertEqual(session.current_task_id, "")
self.assertNotIn("task-1", executor.runtime._claimed_task_ids)
# No terminal failure was recorded on the task.
self.assertNotIn("claimed_work_item_exception", dict(task.metadata or {}))
await executor._handle_claimed_work_item_exception(
session, task, ProviderQuotaExhaustedError("429 again")
)
self.assertEqual(executor._quota_park_streak, 2)
self.assertAlmostEqual(
executor._quota_park_until - time.monotonic(), 120, delta=5
)
async def test_streak_resets_after_a_quiet_period(self) -> None:
executor = self._executor()
executor._quota_park_streak = 5
executor._quota_last_park_at = time.monotonic() - 3600
session = self._session()
task = Task(id="task-1", title="t", project_id="p", session_id="s")
await executor._handle_claimed_work_item_exception(
session, task, ProviderQuotaExhaustedError("429")
)
self.assertEqual(executor._quota_park_streak, 1)
async def test_backoff_caps_at_fifteen_minutes(self) -> None:
executor = self._executor()
executor._quota_park_streak = 9
executor._quota_last_park_at = time.monotonic()
session = self._session()
task = Task(id="task-1", title="t", project_id="p", session_id="s")
await executor._handle_claimed_work_item_exception(
session, task, ProviderQuotaExhaustedError("429")
)
self.assertLessEqual(executor._quota_park_until - time.monotonic(), 900 + 5)
async def test_non_quota_exception_still_fails_terminally(self) -> None:
executor = self._executor()
session = self._session()
task = Task(id="task-1", title="t", project_id="p", session_id="s")
failed: dict = {}
async def _fake_fail(member_session, failed_task, exc) -> None: # noqa: ANN001
failed["exc"] = exc
# Route the non-quota path into a probe: the real body needs a store.
original = CompanyWorkItemExecutor._handle_claimed_work_item_exception
async def _probe(self, member_session, failed_task, exc): # noqa: ANN001
if self._exception_is_provider_quota(exc):
await self._park_claimed_work_item_for_quota(member_session, failed_task, exc)
return
await _fake_fail(member_session, failed_task, exc)
try:
CompanyWorkItemExecutor._handle_claimed_work_item_exception = _probe
await executor._handle_claimed_work_item_exception(
session, task, RuntimeError("real crash")
)
finally:
CompanyWorkItemExecutor._handle_claimed_work_item_exception = original
self.assertIsInstance(failed.get("exc"), RuntimeError)
self.assertEqual(executor._quota_park_streak, 0)
if __name__ == "__main__":
unittest.main()
+185
View File
@@ -0,0 +1,185 @@
"""Regression: failure-path run closure and post-failure input routing (OBS-5).
A run whose intake/delivery failed used to stay running/active forever: no
closure signal, no card, and a new message was routed into re-executing the
dead run (dropping the user's content). The fix closes the run at dispatcher
convergence, emits a ``company_run_failure_review`` card, and the card's
resume handler never swallows ordinary messages — content-bearing replies
fall through so normal routing starts a fresh run.
"""
from __future__ import annotations
import unittest
from datetime import datetime
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import AsyncMock
from opc.core.models import (
DelegationRun,
DelegationWorkItem,
ExecutionCheckpoint,
Task,
TaskStatus,
)
from opc.database.store import OPCStore
from opc.engine import OPCEngine
from opc.layer2_organization.company_mode import CompanyWorkItemExecutor
from opc.layer2_organization.phase import Phase
class RunFailureSettlementTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self) -> None:
self._tmp = TemporaryDirectory()
self.store = OPCStore(Path(self._tmp.name) / "tasks.db")
await self.store.initialize()
self.executor = CompanyWorkItemExecutor.__new__(CompanyWorkItemExecutor)
self.executor.store = self.store
self.captured_checkpoints: list[dict] = []
async def _capture(payload: dict) -> None:
self.captured_checkpoints.append(payload)
self.executor.checkpoint_callback = _capture
self.executor._emit_progress = AsyncMock()
async def asyncTearDown(self) -> None:
await self.store.close()
self._tmp.cleanup()
async def _seed_run(self, *, fail_intake: bool) -> list[Task]:
run = DelegationRun(run_id="run-1", project_id="p", session_id="s")
run.status = "running"
run.lifecycle_status = "active"
await self.store.save_delegation_run(run)
intake = DelegationWorkItem(
work_item_id="wi-intake",
run_id="run-1",
role_id="ceo",
kind="intake",
title="CEO Intake",
phase=Phase.READY,
)
execute = DelegationWorkItem(
work_item_id="wi-exec",
run_id="run-1",
role_id="cto",
kind="execute",
title="survey",
phase=Phase.READY,
)
await self.store.save_delegation_work_item(intake)
await self.store.save_delegation_work_item(execute)
if fail_intake:
await self.store.update_delegation_work_item("wi-intake", phase=Phase.FAILED)
await self.store.update_delegation_work_item("wi-exec", phase=Phase.FAILED)
else:
await self.store.update_delegation_work_item("wi-intake", phase=Phase.RUNNING)
await self.store.update_delegation_work_item("wi-intake", phase=Phase.APPROVED)
await self.store.update_delegation_work_item("wi-exec", phase=Phase.RUNNING)
await self.store.update_delegation_work_item("wi-exec", phase=Phase.APPROVED)
task = Task(
id="task-1",
title="CEO Intake",
project_id="p",
session_id="s",
metadata={
"delegation_run_id": "run-1",
"original_request": "Research multi-agent architectures",
},
)
await self.store.save_task(task)
return [task]
async def test_terminal_failure_closes_run_and_emits_card(self) -> None:
tasks = await self._seed_run(fail_intake=True)
await self.executor._settle_run_lifecycle_on_convergence(tasks)
run = await self.store.get_delegation_run("run-1")
self.assertEqual(run.status, "failed")
self.assertEqual(run.lifecycle_status, "closed_failed")
self.assertTrue(run.metadata.get("run_failure", {}).get("failed_items"))
self.assertEqual(len(self.captured_checkpoints), 1)
card = self.captured_checkpoints[0]
self.assertEqual(card["checkpoint_type"], "company_run_failure_review")
self.assertEqual(card["payload"]["run_id"], "run-1")
self.assertEqual(card["payload"]["original_request"], "Research multi-agent architectures")
async def test_successful_convergence_leaves_run_untouched(self) -> None:
tasks = await self._seed_run(fail_intake=False)
await self.executor._settle_run_lifecycle_on_convergence(tasks)
run = await self.store.get_delegation_run("run-1")
self.assertEqual(run.lifecycle_status, "active")
self.assertEqual(self.captured_checkpoints, [])
async def test_settlement_is_idempotent(self) -> None:
tasks = await self._seed_run(fail_intake=True)
await self.executor._settle_run_lifecycle_on_convergence(tasks)
await self.executor._settle_run_lifecycle_on_convergence(tasks)
self.assertEqual(len(self.captured_checkpoints), 1)
class FailureReviewCheckpointReplyTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self) -> None:
self._tmp = TemporaryDirectory()
self.store = OPCStore(Path(self._tmp.name) / "tasks.db")
await self.store.initialize()
self.engine = OPCEngine(project_id="p")
self.engine.store = self.store
checkpoint = ExecutionCheckpoint(
checkpoint_id="ckpt-fail-1",
project_id="p",
session_id="s",
checkpoint_type="company_run_failure_review",
task_id="task-1",
status="pending",
payload={
"run_id": "run-1",
"session_id": "s",
"prompt": "run closed",
},
created_at=datetime.now(),
)
await self.store.save_execution_checkpoint(checkpoint)
self.checkpoint = checkpoint
async def asyncTearDown(self) -> None:
await self.store.close()
self._tmp.cleanup()
async def _checkpoint_status(self) -> str:
loaded = await self.engine._load_execution_checkpoint_by_id("ckpt-fail-1")
return str(getattr(loaded, "status", "") or "")
async def test_untargeted_message_is_never_swallowed(self) -> None:
reply = await self.engine._maybe_resume_checkpoint(
"Please run a fresh research task for me",
session_id="s",
)
self.assertIsNone(reply)
self.assertEqual(await self._checkpoint_status(), "pending")
async def test_dismiss_resolves_with_acknowledgement(self) -> None:
reply = await self.engine._maybe_resume_checkpoint(
"dismiss",
session_id="s",
reply_metadata={"response_to_checkpoint_id": "ckpt-fail-1"},
)
self.assertEqual(reply, "Company run closure acknowledged.")
self.assertEqual(await self._checkpoint_status(), "resolved")
async def test_content_reply_resolves_and_falls_through(self) -> None:
reply = await self.engine._maybe_resume_checkpoint(
"Redo the research, focused on open-source frameworks this time",
session_id="s",
reply_metadata={"response_to_checkpoint_id": "ckpt-fail-1"},
)
self.assertIsNone(reply)
self.assertEqual(await self._checkpoint_status(), "resolved")
if __name__ == "__main__":
unittest.main()
+237
View File
@@ -0,0 +1,237 @@
"""Regression: stop/resume must not kill runs over an unavailable agent pin.
OBS-11: a corporate role template's ``preferred_external_agent: codex`` was
stamped into execution identity even when the run was requested and executed
as native. On resume, the availability gate trusted that pin and failed every
non-terminal work item closed. These tests pin the four legs of the fix:
1. identity truth — seat enrichment and the dispatch selector record the
backend that actually runs (native fallback when the external agent is
provably unavailable),
2. resume gate symmetry — a pin without a resumable external session heals
to native instead of failing the item,
3. control/content separation — a bare "continue" (or force_resume metadata,
in either spelling) resumes the runtime instead of being routed to the
final decider as a follow-up.
"""
from __future__ import annotations
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from types import SimpleNamespace
from opc.core.models import DelegationWorkItem, Task, TaskStatus
from opc.database.store import OPCStore
from opc.engine import OPCEngine
from opc.layer2_organization.phase import Phase
from opc.layer2_organization.work_item_links import set_linked_work_item_id
class _AdapterRegistryStub:
def __init__(self, available: list[str]):
self._available = list(available)
def list_available(self) -> list[str]:
return list(self._available)
def get(self, name: str):
return object() if name in self._available else None
def get_ordered_available(self):
return [(name, object()) for name in self._available]
class PlainResumeControlReplyTests(unittest.TestCase):
def test_control_tokens_are_plain_resume(self) -> None:
# includes the Chinese continuation spellings the product accepts
for reply in ("continue", " Resume ", "proceed", "ok", "y", "继续", "恢复", ""):
self.assertTrue(OPCEngine._is_plain_resume_control_reply(reply), reply)
def test_content_is_not_plain_resume(self) -> None:
# the Chinese sample starts with a control word but carries content,
# so it must NOT be treated as a bare control reply
for reply in ("make a ppt outline", "继续,但先修复报告第3节", "deny"):
self.assertFalse(OPCEngine._is_plain_resume_control_reply(reply), reply)
def test_force_resume_metadata_both_spellings(self) -> None:
self.assertTrue(OPCEngine._reply_metadata_requests_force_resume({"ui_force_resume": True}))
self.assertTrue(OPCEngine._reply_metadata_requests_force_resume({"force_resume": True}))
self.assertFalse(OPCEngine._reply_metadata_requests_force_resume({"other": True}))
self.assertFalse(OPCEngine._reply_metadata_requests_force_resume(None))
class LockedAgentAvailabilityFallbackTests(unittest.IsolatedAsyncioTestCase):
def _engine(self, available: list[str]) -> OPCEngine:
engine = OPCEngine(project_id="p")
engine.org_engine = SimpleNamespace()
engine.adapter_registry = _AdapterRegistryStub(available)
return engine
async def test_locked_unavailable_external_falls_back_to_native(self) -> None:
engine = self._engine(available=[])
task = Task(id="t1", title="t", project_id="p", session_id="s")
task.metadata["execution_agent_locked"] = True
task.metadata["selected_execution_agent"] = "codex"
selected = await engine._assign_task_execution_agent(task)
self.assertIsNone(selected)
self.assertIsNone(task.assigned_external_agent)
self.assertEqual(task.metadata["selected_execution_agent"], "native")
self.assertEqual(task.metadata["execution_agent_unavailable"], "codex")
self.assertEqual(
task.metadata["agent_selection"]["decision_reason"],
"locked_external_agent_unavailable_native_fallback",
)
async def test_locked_available_external_is_kept(self) -> None:
engine = self._engine(available=["codex"])
task = Task(id="t2", title="t", project_id="p", session_id="s")
task.metadata["execution_agent_locked"] = True
task.metadata["selected_execution_agent"] = "codex"
selected = await engine._assign_task_execution_agent(task)
self.assertEqual(selected, "codex")
self.assertEqual(task.assigned_external_agent, "codex")
class SeatEnrichmentIdentityTruthTests(unittest.TestCase):
def _engine(self, available: list[str], role_preferred: str | None) -> OPCEngine:
engine = OPCEngine(project_id="p")
engine.adapter_registry = _AdapterRegistryStub(available)
role = SimpleNamespace(preferred_external_agent=role_preferred)
engine.org_engine = SimpleNamespace(
get_agent=lambda role_id: role,
get_employee=lambda employee_id: None,
get_default_employee_for_role=lambda role_id: None,
list_employees=lambda role_id=None: [],
ensure_fallback_employee_for_role=lambda role_id, persist=False: None,
)
return engine
def _enrich(self, engine: OPCEngine, preferred_agent: str | None) -> dict:
decision = SimpleNamespace(preferred_agent=preferred_agent)
topology = {"seats": [{"role_id": "cto", "seat_id": "seat-cto"}]}
enriched = engine._enrich_runtime_delegation_topology(
runtime_topology=topology,
decision=decision,
project_id="p",
)
return enriched["seats"][0]
def test_explicit_native_wins_over_role_preference(self) -> None:
engine = self._engine(available=["codex"], role_preferred="codex")
seat = self._enrich(engine, preferred_agent="native")
self.assertEqual(seat["selected_execution_agent"], "native")
self.assertTrue(seat["force_native_execution"])
def test_unavailable_role_preference_resolves_to_native(self) -> None:
engine = self._engine(available=[], role_preferred="codex")
seat = self._enrich(engine, preferred_agent=None)
self.assertEqual(seat["selected_execution_agent"], "native")
self.assertEqual(seat["execution_agent_unavailable"], "codex")
def test_available_role_preference_is_kept(self) -> None:
engine = self._engine(available=["codex"], role_preferred="codex")
seat = self._enrich(engine, preferred_agent=None)
self.assertEqual(seat["selected_execution_agent"], "codex")
self.assertEqual(seat["execution_agent_unavailable"], "")
class ResumeGateHealTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self) -> None:
self._tmp = TemporaryDirectory()
self.store = OPCStore(Path(self._tmp.name) / "tasks.db")
await self.store.initialize()
self.engine = OPCEngine(project_id="p")
self.engine.store = self.store
self.engine.adapter_registry = _AdapterRegistryStub([])
async def asyncTearDown(self) -> None:
await self.store.close()
self._tmp.cleanup()
async def _seed(self) -> Task:
item = DelegationWorkItem(
work_item_id="wi-1",
run_id="run-1",
role_id="cto",
kind="execute",
title="survey",
phase=Phase.READY,
)
await self.store.save_delegation_work_item(item)
task = Task(
id="task-1",
title="survey",
project_id="p",
session_id="s",
status=TaskStatus.RUNNING,
metadata={"delegation_run_id": "run-1"},
)
set_linked_work_item_id(task, "wi-1")
await self.store.save_task(task)
return task
def _payload(self, task: Task, external_sessions: dict) -> dict:
return {
"checkpoint_id": "ckpt-1",
"task_snapshots": [
{
"task_id": task.id,
"execution_identity": {
"selected_execution_agent": "codex",
"assigned_external_agent": "codex",
},
"work_item": {"work_item_id": "wi-1"},
}
],
"active_work_items": [{"work_item_id": "wi-1", "phase": "ready"}],
"external_sessions": external_sessions,
"native_runtime_resume": {},
}
async def test_pin_without_external_session_heals_to_native(self) -> None:
task = await self._seed()
payload = self._payload(task, external_sessions={})
refreshed = await self.engine._prepare_company_runtime_tasks_for_resume(
[task], payload
)
prepared = refreshed[0]
self.assertIsNone(prepared.assigned_external_agent)
self.assertEqual(prepared.metadata.get("selected_execution_agent"), "native")
self.assertEqual(
prepared.metadata.get("resume_execution_agent_healed_from"), "codex"
)
pin = dict(prepared.metadata.get("_company_runtime_resume_execution_agent_pin", {}))
self.assertEqual(pin.get("selected_execution_agent"), "native")
self.assertEqual(pin.get("assigned_external_agent", ""), "")
item = await self.store.get_delegation_work_item("wi-1")
self.assertEqual(item.phase, Phase.READY)
async def test_pin_with_live_external_session_still_fails_closed(self) -> None:
task = await self._seed()
payload = self._payload(
task,
external_sessions={
task.id: {
"status": "active",
"agent_type": "codex",
"resume_session_id": "sess-1",
}
},
)
await self.engine._prepare_company_runtime_tasks_for_resume([task], payload)
item = await self.store.get_delegation_work_item("wi-1")
self.assertEqual(item.phase, Phase.FAILED)
self.assertIn("pinned to external agent", str(item.blocked_reason or ""))
if __name__ == "__main__":
unittest.main()