diff --git a/loopx/cli_commands/quota.py b/loopx/cli_commands/quota.py index 9b10e7109a..ee96fa1c2e 100644 --- a/loopx/cli_commands/quota.py +++ b/loopx/cli_commands/quota.py @@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Any from ..control_plane.coordination.local_authority import CanonicalAuthorityRequired +from ..control_plane.effect_runtime import effect_runtime_request_scope from ..control_plane.quota.error_codes import ( CloseoutQueryUnavailableError, HeartbeatReceiptIdentityConflictError, @@ -406,6 +407,17 @@ def handle_quota_command( limit = getattr(args, "max_page_output_bytes", None) def execute() -> int: + if args.quota_command == "should-run": + with effect_runtime_request_scope(): + return _execute_quota_command( + args, + registry_path=registry_path, + runtime_root_arg=runtime_root_arg, + print_payload=print_payload, + append_cli_rollout_event=append_cli_rollout_event, + capture_directory=capture_directory, + retained_action_selection_todo_id=retained_action_selection_todo_id, + ) return _execute_quota_command( args, registry_path=registry_path, diff --git a/loopx/cli_commands/quota_should_run.py b/loopx/cli_commands/quota_should_run.py index 2418cf90c8..cfb93cf7f0 100644 --- a/loopx/cli_commands/quota_should_run.py +++ b/loopx/cli_commands/quota_should_run.py @@ -3,6 +3,7 @@ from __future__ import annotations import argparse +import inspect from collections.abc import Callable, Mapping from dataclasses import dataclass, field, replace from pathlib import Path @@ -26,6 +27,7 @@ has_orphaned_identity_upgrade_replan_guard, is_malformed_settlement_state_error, ) +from ..control_plane.todos.quota_selection import StaleCanonicalQuotaSourceError from ..control_plane.turn_driver.codex_context import context_delivery_for_arguments from ..file_lock import LockAcquireTimeoutError from ..rollout_event_log import ( @@ -518,8 +520,29 @@ def execute_quota_should_run( "context_navigation": outcome_navigation, "goal_ref": goal_ref, } + fresh_status = not bool(cache_metadata and cache_metadata.get("hit") is True) + decision_params = inspect.signature(decision_builder).parameters + accepts_reuse = "reuse_fresh_canonical_snapshot" in decision_params or any( + param.kind is inspect.Parameter.VAR_KEYWORD + for param in decision_params.values() + ) + if fresh_status and accepts_reuse: + decision_kwargs["reuse_fresh_canonical_snapshot"] = True try: payload = decision_builder(status_payload, **decision_kwargs) + except StaleCanonicalQuotaSourceError: + status_payload = export("collect_status")( + registry_path=registry_path, + runtime_root_override=runtime_root_arg, + limit=context.status_limit, + goal_id=context.status_goal_id, + available_capabilities=args.available_capabilities, + agent_lane_id=args.agent_id, + include_presentation_projections=False, + ) + execution.status_payload = status_payload + decision_kwargs.pop("reuse_fresh_canonical_snapshot", None) + payload = decision_builder(status_payload, **decision_kwargs) except (ValueError, EffectRuntimeRejected) as exc: if ( mutable_should_run diff --git a/loopx/control_plane/quota/live_decision.py b/loopx/control_plane/quota/live_decision.py index 171122a6e9..91b110c6a7 100644 --- a/loopx/control_plane/quota/live_decision.py +++ b/loopx/control_plane/quota/live_decision.py @@ -336,6 +336,7 @@ def build_live_quota_should_run_decision( goal_ref: Mapping[str, object] | None = None, inline_goal_source: bool = False, tolerate_malformed_settlement_history: bool = False, + reuse_fresh_canonical_snapshot: bool = False, ) -> dict[str, object]: """Build one live CLI decision while keeping host observation injectable.""" @@ -437,6 +438,7 @@ def observe_app_scheduler_state(readback: Mapping[str, object]) -> None: app_scheduler_state_observer=observe_app_scheduler_state, workspace_path=workspace_path, goal_ref=goal_ref, authoritative_fallback_todo_items=authoritative_fallback_todo_items, + reuse_fresh_canonical_snapshot=reuse_fresh_canonical_snapshot, ) _project_receipt_replan_settlement( payload, settlement_readback, diff --git a/loopx/control_plane/todos/read_projection.ts b/loopx/control_plane/todos/read_projection.ts index d7d9be0528..2ba6f00a34 100644 --- a/loopx/control_plane/todos/read_projection.ts +++ b/loopx/control_plane/todos/read_projection.ts @@ -283,26 +283,30 @@ export async function projectCanonicalTodoFields( ): Promise { if (!Array.isArray(input.todos)) throw new EffectRuntimeRequestError("canonical Todo read source must be an array"); const original = input.todos.map(value => requireJsonObject(value, "canonical Todo source")); - const decisions = original.filter(row => row.role === "user"); + const query = input.kind === "query" && input.selection == null ? object(input.query) : {}; + const singleRoleQuery = input.kind === "query" && input.selection == null + && (query.role === "user" || query.role === "agent"); + const targetRoles = singleRoleQuery ? [String(query.role)] : ["user", "agent"]; + const decisions = input.kind === "query" ? [] : original.filter(row => row.role === "user"); const standing = decisions.length ? projectStandingDecisions(decisions, false) : null; const all = input.presentation_ready === true ? original : canonicalTodoReadItems(original); const archived = new Set(all.filter(row => row.archive_state === "archive").map(row => row.todo_id)); const acceptance = object(input.goal_acceptance_contract), guards = object(input.goal_acceptance_work_guards); const checksConfigured = configuredGoalChecks(acceptance) !== null; const lineage = Array.isArray(input.lineage) ? input.lineage.map(value => requireJsonObject(value, "Todo lineage")) : all; - const lineageFacts = input.lineage_facts ?? lineage.map(successionFacts); + let cachedLineageFacts = input.lineage_facts; + const resolveLineageFacts = () => (cachedLineageFacts ??= lineage.map(successionFacts)); const includeArchived = input.include_archived === true || input.retained === true; - const query = input.kind === "query" && input.selection == null ? object(input.query) : {}; const includeAcceptance = includeTodoAcceptance(input, query); const detailId = query.agent_id == null && query.limit == null ? query.todo_id : null; const fields: JsonObject = {}, evaluations: JsonObject = {}; - for (const role of ["user", "agent"]) { + for (const role of targetRoles) { const section = role === "agent" ? "Agent Todo" : "User Todo / Owner Review Reading Queue"; const items = all.filter(row => (row.role === "user" ? "user" : "agent") === role && (includeArchived || !archived.has(row.todo_id))) .map(row => structureCanonicalTodo({...row, ...(input.retained !== true && checksConfigured && guards[text(row.todo_id)] ? {goal_acceptance_guard: guards[text(row.todo_id)]} : {})}, role, section, input.retained === true ? null : 500, input.retained !== true)); - const grouped = await projectTodoReadGroup({...input, items, lineage, lineage_facts: lineageFacts, evaluated: false, role, source_section: section, + const grouped = await projectTodoReadGroup({...input, items, lineage, lineage_facts: items.length > 0 || input.kind !== "query" ? resolveLineageFacts() : undefined, evaluated: false, role, source_section: section, selection: typeof detailId === "string" && detailId ? {role, todo_id: detailId, status: null, agent_id: null} : input.selection ?? null, item_limit: null, full_selection: true, resume_lineage: items.some(row => readResume(row.resume_when)) ? all.map(row => structureCanonicalTodo(row, row.role ?? null, row.source_section ?? section)) : []}, options); diff --git a/loopx/control_plane/work_items/planning_inventory.py b/loopx/control_plane/work_items/planning_inventory.py index 4365a5c5aa..5172c0ced1 100644 --- a/loopx/control_plane/work_items/planning_inventory.py +++ b/loopx/control_plane/work_items/planning_inventory.py @@ -22,21 +22,37 @@ ) -def compact_planning_candidates(values: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]: - texts: list[str | None] - sources, texts = [], [] +def _prepare_planning_candidates( + values: Sequence[Mapping[str, Any]], +) -> tuple[list[dict[str, Any]], list[str | None]]: + sources: list[dict[str, Any]] = [] + texts: list[str | None] = [] for value in values: todo_id = normalize_todo_id(value.get("todo_id")) text = protocol_action_text(value.get("text"), limit=500) if todo_id and text: sources.append(dict(value)) texts.append(text) - compacts = compact_todo_summary_items(sources, texts=texts) + return sources, texts + + +def _attach_candidate_metadata( + sources: Sequence[Mapping[str, Any]], + compacts: Sequence[dict[str, Any]], +) -> list[dict[str, Any]]: + result: list[dict[str, Any]] = [] for value, compact in zip(sources, compacts, strict=True): for field in ("source", "selected_by", "availability_reason"): if value.get(field) is not None: compact[field] = value[field] - return compacts + result.append(compact) + return result + + +def compact_planning_candidates(values: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]: + sources, texts = _prepare_planning_candidates(values) + compacts = compact_todo_summary_items(sources, texts=texts) + return _attach_candidate_metadata(sources, compacts) def compact_planning_candidate(value: Mapping[str, Any]) -> dict[str, Any] | None: @@ -44,13 +60,13 @@ def compact_planning_candidate(value: Mapping[str, Any]) -> dict[str, Any] | Non return compacts[0] if compacts else None -def quota_runnable_action_candidates( +def _raw_runnable_action_candidates( *, agent_id: str, agent_todo_summary: Mapping[str, Any] | None, capability_gate: Mapping[str, Any] | None, ) -> list[dict[str, Any]]: - """Adapt already-gated Python eligibility facts into inventory inputs.""" + """Adapt already-gated Python eligibility facts into raw inventory inputs.""" if not isinstance(agent_todo_summary, Mapping): return [] @@ -91,7 +107,23 @@ def quota_runnable_action_candidates( continue seen.add(todo_id) candidates.append(candidate) - return compact_planning_candidates(candidates) + return candidates + + +def quota_runnable_action_candidates( + *, + agent_id: str, + agent_todo_summary: Mapping[str, Any] | None, + capability_gate: Mapping[str, Any] | None, +) -> list[dict[str, Any]]: + """Adapt already-gated Python eligibility facts into inventory inputs.""" + return compact_planning_candidates( + _raw_runnable_action_candidates( + agent_id=agent_id, + agent_todo_summary=agent_todo_summary, + capability_gate=capability_gate, + ) + ) def _unavailable_reason(candidate: Mapping[str, Any]) -> str: @@ -113,7 +145,7 @@ def _unavailable_reason(candidate: Mapping[str, Any]) -> str: return "not_currently_executable" -def unavailable_higher_priority_candidates( +def _raw_unavailable_higher_priority_candidates( blocked_priority_fallback: Mapping[str, Any] | None, ) -> list[dict[str, Any]]: if not isinstance(blocked_priority_fallback, Mapping): @@ -126,7 +158,15 @@ def unavailable_higher_priority_candidates( candidate = dict(item) candidate["availability_reason"] = _unavailable_reason(candidate) unavailable.append(candidate) - return compact_planning_candidates(unavailable) + return unavailable + + +def unavailable_higher_priority_candidates( + blocked_priority_fallback: Mapping[str, Any] | None, +) -> list[dict[str, Any]]: + return compact_planning_candidates( + _raw_unavailable_higher_priority_candidates(blocked_priority_fallback) + ) def _source_context_count(summary: Mapping[str, Any] | None) -> int: @@ -149,25 +189,36 @@ def build_quota_planning_inventory_request( """Adapt Python Todo sources into one TypeScript inventory request.""" safe_agent_id = normalize_todo_claimed_by(agent_id) - compact_selected = ( - compact_planning_candidate(selected) if selected is not None else None + selected_sources, selected_texts = _prepare_planning_candidates( + [selected] if selected is not None else [] ) - if not goal_id or not safe_agent_id or compact_selected is None: + if not goal_id or not safe_agent_id or not selected_sources: return None - source_items = compact_planning_candidates(agent_todo_source_items) + source_sources, source_texts = _prepare_planning_candidates(agent_todo_source_items) + runnable_sources, runnable_texts = _prepare_planning_candidates( + _raw_runnable_action_candidates( + agent_id=safe_agent_id, + agent_todo_summary=agent_todo_summary, + capability_gate=capability_gate, + ) + ) + unavail_sources, unavail_texts = _prepare_planning_candidates( + _raw_unavailable_higher_priority_candidates(blocked_priority_fallback) + ) + all_sources = [*selected_sources, *source_sources, *runnable_sources, *unavail_sources] + all_texts = [*selected_texts, *source_texts, *runnable_texts, *unavail_texts] + all_compacts = compact_todo_summary_items(all_sources, texts=all_texts) + attached = _attach_candidate_metadata(all_sources, all_compacts) + n0 = len(selected_sources) + n1 = n0 + len(source_sources) + n2 = n1 + len(runnable_sources) return { "schema_version": TODO_PLANNING_INVENTORY_REQUEST_SCHEMA_VERSION, "goal_id": goal_id, "agent_id": safe_agent_id, - "selected_todo": compact_selected, - "source_items": source_items, - "runnable_candidates": quota_runnable_action_candidates( - agent_id=safe_agent_id, - agent_todo_summary=agent_todo_summary, - capability_gate=capability_gate, - ), - "unavailable_higher_priority": unavailable_higher_priority_candidates( - blocked_priority_fallback - ), + "selected_todo": attached[0], + "source_items": attached[n0:n1], + "runnable_candidates": attached[n1:n2], + "unavailable_higher_priority": attached[n2:], "source_context_todo_count": _source_context_count(agent_todo_summary), } diff --git a/tests/control_plane/test_quota_should_run_waterfall.py b/tests/control_plane/test_quota_should_run_waterfall.py new file mode 100644 index 0000000000..824284d0d6 --- /dev/null +++ b/tests/control_plane/test_quota_should_run_waterfall.py @@ -0,0 +1,339 @@ +"""Tests for quota should-run canonical snapshot reuse, stale recovery, and RPC coalescing.""" + +from __future__ import annotations + +from collections.abc import Mapping +import json +from pathlib import Path + +import pytest + +from canonical_authority_fixture import initialize_canonical_authority, isolate_sqlite_runtime +from loopx.cli import main +from loopx.control_plane import effect_runtime +from loopx.control_plane.coordination.authority_source_capture import build_todo_runtime_shadow_projection +from loopx.control_plane.coordination.local_authority import claim_canonical_todo_if_promoted +from loopx.control_plane.effect_runtime import effect_runtime_request_scope, restart_effect_runtime +from loopx.control_plane.quota import live_decision +from loopx.control_plane.todos.list_readback import list_goal_todos +from loopx.control_plane.work_items import planning_inventory + + +GOAL_ID = "waterfall-goal" +AGENT_ID = "antigravity" + + +def _write_waterfall_goal(tmp_path: Path, *, provider: str) -> tuple[Path, Path]: + project = tmp_path / f"project-{provider}" + runtime = tmp_path / f"runtime-{provider}" + project.mkdir(parents=True) + (project / "README.md").write_text("# Waterfall Goal\n", encoding="utf-8") + state_rel = f".codex/goals/{GOAL_ID}/ACTIVE_GOAL_STATE.md" + state_path = project / state_rel + state_path.parent.mkdir(parents=True, exist_ok=True) + state_path.write_text("# Waterfall Goal\n", encoding="utf-8") + records = [ + { + "schema_version": "todo_item_v0", + "todo_id": "todo_user_gate", + "index": 1, + "role": "user", + "status": "done", + "done": True, + "completed_at": "2026-11-27T01:00:00Z", + "no_followup": True, + "task_class": "user_gate", + "text": "[P0] Done cross-role user gate.", + "priority": "P0", + "archive_state": "active", + "source_section": "User Todo / Owner Review Reading Queue", + }, + { + "schema_version": "todo_item_v0", + "todo_id": "todo_user_open", + "index": 2, + "role": "user", + "status": "open", + "done": False, + "global_gate": False, + "bound_agent": "other-agent", + "task_class": "user_action", + "text": "[P1] Unrelated other agent user notice.", + "priority": "P1", + "archive_state": "active", + "source_section": "User Todo / Owner Review Reading Queue", + }, + { + "schema_version": "todo_item_v0", + "todo_id": "todo_agent_primary", + "index": 1, + "role": "agent", + "status": "open", + "done": False, + "claimed_by": AGENT_ID, + "resume_when": "todo_done:todo_user_gate", + "task_class": "advancement_task", + "text": "[P0] Primary claimed agent deliverable.", + "priority": "P0", + "archive_state": "active", + "source_section": "Agent Todo", + }, + { + "schema_version": "todo_item_v0", + "todo_id": "todo_agent_unclaimed", + "index": 2, + "role": "agent", + "status": "open", + "done": False, + "task_class": "advancement_task", + "text": "[P1] Secondary unclaimed deliverable for stale-claim test.", + "priority": "P1", + "archive_state": "active", + "source_section": "Agent Todo", + }, + ] + registry = project / ".loopx" / "registry.json" + registry.parent.mkdir(parents=True, exist_ok=True) + registry.write_text( + json.dumps( + { + "schema_version": 1, + "common_runtime_root": str(runtime), + "goals": [ + { + "id": GOAL_ID, + "domain": "waterfall-test", + "status": "active", + "repo": str(project), + "state_file": state_rel, + "adapter": {"kind": "fixture_connected_delivery_v0", "status": "connected-delivery"}, + "quota": {"compute": 1.0, "window_hours": 24}, + "coordination": { + "agent_model": "peer_v1", + "registered_agents": [AGENT_ID, "other-agent"], + "agent_profiles": { + AGENT_ID: { + "schema_version": "agent_profile_v1", + "profile_role": "quality", + "scope": "quality optimization", + }, + "other-agent": { + "schema_version": "agent_profile_v1", + "profile_role": "observer", + "scope": "read-only observation", + }, + }, + "write_scope": ["loopx/**"], + }, + } + ], + } + ) + + "\n", + encoding="utf-8", + ) + projection = build_todo_runtime_shadow_projection(goal_id=GOAL_ID, todos=records) + initialize_canonical_authority( + runtime, + GOAL_ID, + projection, + state_path=state_path, + provider=provider, + ) + return registry, runtime + + +def _run_should_run_cli( + registry: Path, + runtime: Path, + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, +) -> tuple[int, dict[str, object], list[tuple[str, object]]]: + calls: list[tuple[str, object]] = [] + orig = effect_runtime.effect_runtime_request + + def trace( + method: str, + params: Mapping[str, object], + *, + timeout: float = effect_runtime.DEFAULT_REQUEST_TIMEOUT_SECONDS, + retry_safe: bool = True, + large_local_snapshot: bool = False, + ) -> dict[str, object]: + kind = params.get("kind") or params.get("schema_version") + calls.append((method, kind)) + return orig( + method, + params, + timeout=timeout, + retry_safe=retry_safe, + large_local_snapshot=large_local_snapshot, + ) + + monkeypatch.setattr(effect_runtime, "effect_runtime_request", trace) + capsys.readouterr() + code = main( + [ + "--registry", + str(registry), + "--runtime-root", + str(runtime), + "--format", + "json", + "quota", + "should-run", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + "--dry-run", + ] + ) + payload = json.loads(capsys.readouterr().out) + return code, payload, calls + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_quota_should_run_uses_head_checked_canonical_reuse_and_single_role_parity( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, + provider: str, +) -> None: + if provider == "sqlite": + env_dir = tmp_path / "sqlite-env" + env_dir.mkdir(parents=True, exist_ok=True) + isolate_sqlite_runtime(env_dir, monkeypatch) + try: + registry, runtime = _write_waterfall_goal(tmp_path, provider=provider) + code, payload, calls = _run_should_run_cli(registry, runtime, capsys, monkeypatch) + assert code == 0 + assert payload["ok"] is True + + todo_read_kinds = [kind for method, kind in calls if method == "todo.read"] + assert "canonical_fields" in todo_read_kinds + assert "quota_projection" not in todo_read_kinds + assert ("todo.quota_planning.project", "todo_quota_planning_batch_v0") in calls + + # Verify single-role cross-role resume parity via list_goal_todos. + with effect_runtime_request_scope(): + exact = list_goal_todos( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + role="agent", + todo_id="todo_agent_primary", + ) + all_todos = list_goal_todos( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + ) + assert exact["todo"]["todo_id"] == "todo_agent_primary" + assert exact["todo"]["resume_ready"] is True + assert any(t["todo_id"] == "todo_agent_primary" for t in all_todos["agent_todos"]["items"]) + finally: + if provider == "sqlite": + restart_effect_runtime() + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_quota_should_run_recovers_from_stale_canonical_source_mutation( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, + provider: str, +) -> None: + if provider == "sqlite": + env_dir = tmp_path / "sqlite-env" + env_dir.mkdir(parents=True, exist_ok=True) + isolate_sqlite_runtime(env_dir, monkeypatch) + try: + registry, runtime = _write_waterfall_goal(tmp_path, provider=provider) + + orig_builder = live_decision.build_live_quota_should_run_decision + observed_flags: list[bool] = [] + mutated = False + + def wrap_builder(status_payload: dict[str, object], **kwargs: object) -> dict[str, object]: + nonlocal mutated + observed_flags.append(bool(kwargs.get("reuse_fresh_canonical_snapshot", False))) + if not mutated: + mutated = True + claim_canonical_todo_if_promoted( + registry_path=registry, + runtime_root=runtime, + goal_id=GOAL_ID, + todo_id="todo_agent_unclaimed", + role="agent", + claimed_by="other-agent", + actor_agent_id="other-agent", + dry_run=False, + task_lease_idempotency_key="stale-retry-lease-1", + task_lease_expected_version=0, + ) + return orig_builder(status_payload, **kwargs) + return orig_builder(status_payload, **kwargs) + + from loopx.cli_commands import quota as quota_cmd + + monkeypatch.setattr(quota_cmd, "build_live_quota_should_run_decision", wrap_builder) + capsys.readouterr() + code = main( + [ + "--registry", + str(registry), + "--runtime-root", + str(runtime), + "--format", + "json", + "quota", + "should-run", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + "--dry-run", + ] + ) + assert code == 0 + assert observed_flags == [True, False] + finally: + if provider == "sqlite": + restart_effect_runtime() + + +def test_planning_inventory_coalesces_compaction_into_single_rpc( + monkeypatch: pytest.MonkeyPatch, +) -> None: + item_sel = {"todo_id": "todo_sel", "text": "[P0] Selected work", "status": "open", "task_class": "advancement_task", "source": "selected"} + item_src = {"todo_id": "todo_src", "text": "[P1] Source item", "status": "open", "task_class": "advancement_task", "selected_by": "fallback"} + item_run = {"todo_id": "todo_run", "text": "[P1] Runnable item", "status": "open", "task_class": "advancement_task"} + item_blk = {"todo_id": "todo_blk", "text": "[P0] Blocked higher priority", "status": "blocked", "task_class": "advancement_task"} + + def fake_compact(items: list[dict[str, object]], *, texts: list[str | None] | None = None, strip_text: bool = False) -> list[dict[str, object]]: + return [{"todo_id": it["todo_id"], "text": (texts or [None] * len(items))[i] or it["text"]} for i, it in enumerate(items)] + + calls: list[int] = [] + orig = fake_compact + + def counted(items: list[dict[str, object]], *, texts: list[str | None] | None = None, strip_text: bool = False) -> list[dict[str, object]]: + calls.append(len(items)) + return orig(items, texts=texts, strip_text=strip_text) + + monkeypatch.setattr(planning_inventory, "compact_todo_summary_items", counted) + batched = planning_inventory.build_quota_planning_inventory_request( + goal_id=GOAL_ID, + selected=item_sel, + agent_id=AGENT_ID, + agent_todo_summary={"open_count": 3, "deferred_count": 1, "first_executable_items": [item_run]}, + agent_todo_source_items=[item_src], + capability_gate=None, + blocked_priority_fallback={"blocked_items": [item_blk]}, + ) + assert calls == [4] + assert batched is not None + assert batched["selected_todo"]["source"] == "selected" + assert batched["source_items"][0]["selected_by"] == "fallback" + assert batched["runnable_candidates"][0]["todo_id"] == "todo_run" + assert batched["unavailable_higher_priority"][0]["availability_reason"] == "status_blocked" diff --git a/tests/control_plane_ts/todo_read.test.ts b/tests/control_plane_ts/todo_read.test.ts index 5db7078dde..3edc6c650b 100644 --- a/tests/control_plane_ts/todo_read.test.ts +++ b/tests/control_plane_ts/todo_read.test.ts @@ -870,3 +870,125 @@ test("readTodoRuntime compresses >1 MiB canonical_fields responses cleanly", asy const decoded = JSON.parse(gunzipSync(Buffer.from(String(piece.data), "base64")).toString("utf8")); assert.deepEqual(decoded, plain); }); + +test("single-role todo.read query preserves cross-role lineage, full text, empty roles, and invalid role errors", async t => { + const todos: JsonObject[] = [ + row("todo_user_gate", { + role: "user", + status: "done", + done: true, + completed_at: now, + no_followup: true, + task_class: "user_gate", + source_section: "User Todo", + text: "[P0] Confirm user gate release window with complete unshortened details.", + }), + row("todo_user_open", { + role: "user", + status: "open", + done: false, + global_gate: true, + task_class: "user_gate", + source_section: "User Todo", + text: "[P0] Open user review item with full body retained for single-role query parity.", + }), + row("todo_agent_wait", { + role: "agent", + status: "open", + done: false, + claimed_by: "antigravity", + resume_when: "todo_done:todo_user_gate", + unblocks_todo_id: "todo_user_open", + text: "[P1] Agent item blocked until cross-role user gate finishes.", + }), + ]; + + const root = await mkdtemp(join(tmpdir(), "loopx-single-role-query-")); + t.after(() => rm(root, {recursive: true, force: true})); + const state = join(root, "state.md"), goal = "goal-single-role"; + await writeFile(state, "# Single Role Query Goal\n"); + const store = await openLocalAuthorityStore(root, goal); + const projection = authorityProjectionFixture(goal, todos, [], "native"); + const committed = await store.commitAuthority({ + expected_provider_revision: null, + operation_id: "seed-single-role", + events: [], + next_projection: projection, + receipts: [], + }); + assert.equal(committed.status, "applied"); + if (committed.status !== "applied") return; + const fence = await engageLegacyCoordinationWriterFence({ + schema_version: "loopx_legacy_coordination_writer_fence_engage_request_v0", + runtime_root: root, + goal_id: goal, + state_path: state, + fence: { + schema_version: "loopx_legacy_coordination_writer_fence_v0", + state: "engaged", + goal_id: goal, + fence_id: "single-role-fence", + source_version: "fixture", + source_projection_sha256: canonicalAuthoritySha256(projection), + expected_shadow_provider_revision: committed.provider_revision, + }, + }); + assert.equal(fence.status, "applied"); + + const makeQuery = (query: JsonObject) => ({ + schema_version: TODO_READ_REQUEST, + kind: "query", + source: {runtime_root: root, goal_id: goal}, + observed_at: Date.parse(now) / 1000, + evaluated_at: now, + query: {goal_id: goal, state_file: state, project: root, ...query}, + }); + + const userQuery = await readTodo(makeQuery({role: "user", status: "open", full_text: true})); + const userProjection = userQuery.payload as JsonObject; + const userList = userProjection.todos as JsonObject[]; + assert.equal(userList.length, 1); + assert.equal(userList[0].todo_id, "todo_user_open"); + assert.match(String(userList[0].text), /single-role query parity/); + assert.equal(userProjection.agent_todos, undefined); + + const agentQuery = await readTodo(makeQuery({role: "agent", todo_id: "todo_agent_wait"})); + const agentProjection = agentQuery.payload as JsonObject; + assert.equal((agentProjection.todo as JsonObject).todo_id, "todo_agent_wait"); + assert.equal((agentProjection.todo as JsonObject).resume_ready, true); + assert.equal((agentProjection.todo as JsonObject).unblocks_todo_id, "todo_user_open"); + + const emptyRoot = await mkdtemp(join(tmpdir(), "loopx-single-role-empty-")); + t.after(() => rm(emptyRoot, {recursive: true, force: true})); + const emptyState = join(emptyRoot, "state.md"); + await writeFile(emptyState, "# Empty Agent Role\n"); + const emptyStore = await openLocalAuthorityStore(emptyRoot, goal); + const emptyProj = authorityProjectionFixture(goal, [todos[1]], [], "native"); + const emptyCommit = await emptyStore.commitAuthority({ + expected_provider_revision: null, operation_id: "seed-empty-agent", + events: [], next_projection: emptyProj, receipts: [], + }); + assert.equal(emptyCommit.status, "applied"); + if (emptyCommit.status !== "applied") return; + await engageLegacyCoordinationWriterFence({ + schema_version: "loopx_legacy_coordination_writer_fence_engage_request_v0", + runtime_root: emptyRoot, goal_id: goal, state_path: emptyState, + fence: { + schema_version: "loopx_legacy_coordination_writer_fence_v0", state: "engaged", + goal_id: goal, fence_id: "empty-role-fence", source_version: "fixture", + source_projection_sha256: canonicalAuthoritySha256(emptyProj), + expected_shadow_provider_revision: emptyCommit.provider_revision, + }, + }); + const emptyAgent = await readTodo({ + schema_version: TODO_READ_REQUEST, kind: "query", source: {runtime_root: emptyRoot, goal_id: goal}, + observed_at: Date.parse(now) / 1000, evaluated_at: now, + query: {goal_id: goal, role: "agent", state_file: emptyState, project: emptyRoot}, + }); + assert.deepEqual((emptyAgent.payload as JsonObject).todos, []); + + await assert.rejects( + readTodo(makeQuery({role: "bogus"})), + /Todo read roles must be user or agent/, + ); +});