diff --git a/docs/quota-allocation.md b/docs/quota-allocation.md index 16cb1a44f1..ca193f0edd 100644 --- a/docs/quota-allocation.md +++ b/docs/quota-allocation.md @@ -1205,7 +1205,10 @@ an external-evidence observation, or a due `continuous_monitor` todo selected by `work_lane_contract.obligation=attempt_due_monitor`. For due monitor todos, pass `--todo-id` or `--target-key` plus a public `--result-hash`; unchanged polls update `last_checked_at`, `next_due_at`, and -`consecutive_no_change` without appending `quota_slot_spent`: +`consecutive_no_change` without appending `quota_slot_spent`. +For an `attempt_due_monitor` lane, a target key identifies the selected Todo. +To observe another due Monitor claimed by the same Agent, supply its exact +`--todo-id`. Existing User gates and Turn bindings still apply. ```bash loopx quota monitor-poll --goal-id \ diff --git a/examples/control_plane/monitor-poll-writeback-smoke.py b/examples/control_plane/monitor-poll-writeback-smoke.py index e51408d496..4daf1cc89f 100644 --- a/examples/control_plane/monitor-poll-writeback-smoke.py +++ b/examples/control_plane/monitor-poll-writeback-smoke.py @@ -824,6 +824,28 @@ def assert_target_key_cannot_hijack_selected_due_monitor() -> None: assert other["result_hash"] == "old", other assert monitor_poll_records(registry_path) == [], run_index_records(registry_path) + explicit = run_cli( + registry_path, + "quota", + "monitor-poll", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + "--todo-id", + other["todo_id"], + "--target-key", + OTHER_TARGET_KEY, + "--result-hash", + "old", + "--execute", + ) + assert explicit["todo_writeback"]["todo_id"] == other["todo_id"], explicit + assert find_todo(state_file, TODO_ID) == selected + assert find_todo(state_file, other["todo_id"])["consecutive_no_change"] == "2" + assert len(monitor_poll_records(registry_path)) == 1 + assert not any(r["classification"] == "quota_slot_spent" for r in run_index_records(registry_path)) + def assert_compacted_auxiliary_due_monitor_can_write_back() -> None: with tempfile.TemporaryDirectory(prefix="loopx-monitor-poll-compacted-due-") as tmp: @@ -1282,21 +1304,23 @@ def fake_print_payload(payload: dict, _fmt: str, _renderer: object) -> None: ) original_collect_status = quota_command.collect_status original_record_monitor_poll = quota_command.record_quota_monitor_poll - try: - quota_command.collect_status = fake_collect_status - quota_command.record_quota_monitor_poll = fake_record_quota_monitor_poll - rc = quota_command.handle_quota_command( - args, - registry_path=REPO_ROOT / ".loopx" / "registry.json", - runtime_root_arg=None, - print_payload=fake_print_payload, - append_cli_rollout_event=lambda **_: {}, - ) - finally: - quota_command.collect_status = original_collect_status - quota_command.record_quota_monitor_poll = original_record_monitor_poll - - assert rc == 0, rc + with tempfile.TemporaryDirectory(prefix="loopx-monitor-poll-lookback-") as tmp: + registry_path, _ = write_fixture(Path(tmp)) + try: + quota_command.collect_status = fake_collect_status + quota_command.record_quota_monitor_poll = fake_record_quota_monitor_poll + rc = quota_command.handle_quota_command( + args, + registry_path=registry_path, + runtime_root_arg=None, + print_payload=fake_print_payload, + append_cli_rollout_event=lambda **_: {}, + ) + finally: + quota_command.collect_status = original_collect_status + quota_command.record_quota_monitor_poll = original_record_monitor_poll + + assert rc == 0, (rc, seen.get("payload")) assert seen["limit"] == AUTONOMOUS_REPLAN_PERIODIC_LOOKBACK, seen assert seen["record_kwargs"]["available_capabilities"] == ["network"], seen scheduler_context = seen["record_kwargs"]["scheduler_execution_context"] diff --git a/loopx/control_plane/quota/monitor_poll.py b/loopx/control_plane/quota/monitor_poll.py index 60858e69bf..daeb9e406d 100644 --- a/loopx/control_plane/quota/monitor_poll.py +++ b/loopx/control_plane/quota/monitor_poll.py @@ -50,10 +50,6 @@ def __init__(self, message: str, *, diagnostic_code: str) -> None: self.diagnostic_code = diagnostic_code -def _now_local() -> str: - return now_local_iso() - - def _mapping(value: object) -> Payload: return {str(key): entry for key, entry in value.items()} if isinstance(value, Mapping) else {} @@ -254,6 +250,7 @@ def _decision_packet( registry_path: Path | None = None, runtime_root: Path | None = None, authorized_due_monitor_poll: bool | None = None, + todo_id_explicit: bool = False, ) -> Payload: before_dict = _mapping(before) agent_id = quota_decision_agent_id(before_dict) @@ -266,6 +263,8 @@ def _decision_packet( todo_id=todo_id, target_key=target_key, ) + if registry_due: + registry_due["todo_id_explicit"] = todo_id_explicit and todo_id is not None if authorized_due_monitor_poll is False: due_candidates = [] registry_due = {} @@ -477,7 +476,7 @@ def build_quota_monitor_poll_event( runtime_root=None, goal_id=goal_id, source=source, - generated_at=generated_at or _now_local(), + generated_at=generated_at or now_local_iso(), execute=False, expected_index_digest=None, turn_instance_id=normalized_turn_id, @@ -804,7 +803,7 @@ def record_quota_monitor_poll_for_decision( *, goal_id: str, after_decision: Callable[[Payload], PayloadView], - render_markdown: Callable[[Payload], str], + render_markdown: Callable[[Payload], str] | None = None, # Retained for existing callers. registry_path: Path | None = None, execute: bool = False, source: str = DEFAULT_SLOT_SPEND_SOURCE, @@ -838,8 +837,8 @@ def record_quota_monitor_poll_for_decision( status_reloader: Callable[[], PayloadView] | None = None, goal_ref: PayloadView | None = None, recovery_effect_id: str | None = None, + todo_id_explicit: bool = True, ) -> Payload: - del render_markdown safe_todo_id, safe_target_key, safe_result_hash, normalized_turn_id = _normalized_poll_targets( todo_id=todo_id, target_key=target_key, result_hash=result_hash, turn_instance_id=turn_instance_id, @@ -896,6 +895,7 @@ def record_quota_monitor_poll_for_decision( target_key=safe_target_key, registry_path=registry_path, runtime_root=runtime_root, + todo_id_explicit=todo_id_explicit, ) if auxiliary_settlement_todo is not None: decision["auxiliary_settlement_todo"] = { @@ -928,7 +928,7 @@ def record_quota_monitor_poll_for_decision( task_lease_idempotency_key=task_lease_idempotency_key, task_lease_expected_version=task_lease_expected_version, ) - generated_at = _now_local() + generated_at = now_local_iso() def failure(reason: str, *, include_capability_retry: bool = False) -> Payload: payload = _monitor_poll_failure( diff --git a/loopx/control_plane/quota/monitor_poll_admission.ts b/loopx/control_plane/quota/monitor_poll_admission.ts index 7ce319ae3f..9635baf565 100644 --- a/loopx/control_plane/quota/monitor_poll_admission.ts +++ b/loopx/control_plane/quota/monitor_poll_admission.ts @@ -66,6 +66,7 @@ function dueMonitorAllowed( decision: MonitorDecision, observation: MonitorObservation, facts: MonitorLaneFacts, + historicalAdmission: boolean, ): boolean { if (!facts.must_attempt_work) return false; const candidate = decision.due_monitor_candidates.find((item) => candidateMatches(item, observation)); @@ -73,7 +74,11 @@ function dueMonitorAllowed( const registryAllowed = registry.due === true && registry.claimed_by === decision.agent_id && candidateMatches(registry, observation); if (facts.obligation === "attempt_due_monitor") { - return Boolean(candidate) || (!decision.requires_user_action && registryAllowed); + // A key lookup establishes observation identity. Only an explicit Todo can + // select another due Monitor. Older frozen admissions keep their basis. + const explicitRegistryTarget = (observation.todo_id !== null && registry.todo_id_explicit === true) || + (historicalAdmission && registry.todo_id_explicit === undefined); + return Boolean(candidate) || (!decision.requires_user_action && registryAllowed && explicitRegistryTarget); } if (facts.reason_codes.has("due_monitor_context") && candidate) return true; return facts.reason_codes.has("due_monitor_context") && registryAllowed; @@ -157,7 +162,7 @@ async function auxiliaryMonitorAllowed( // Retain ordinary quota/due-work admission and capability/gate projections; // lifecycle lookup must not become a second should-run bypass. return monitorGateAllowsObservation(decision) && - dueMonitorAllowed(decision, observation, monitorLaneFacts(decision)) && + dueMonitorAllowed(decision, observation, monitorLaneFacts(decision), historicalAdmission) && monitor.due === true && candidateMatches(monitor, observation) && (monitor.claimed_by == null || monitor.claimed_by === decision.agent_id); } @@ -188,7 +193,7 @@ export async function admission( const blocked = blockedSuccessorAllowed(request.decision); const external = externalMonitorAllowed(request.decision, laneFacts); const auxiliary = await auxiliaryMonitorAllowed(request, historicalAdmission); - const due = auxiliary ?? dueMonitorAllowed(request.decision, request.observation, laneFacts); + const due = auxiliary ?? dueMonitorAllowed(request.decision, observation, laneFacts, historicalAdmission); if (auxiliary === false) { throw new EffectRuntimeRequestError( "auxiliary monitor-poll requires its own due Monitor target", "monitor_poll_admission_rejected", diff --git a/loopx/quota.py b/loopx/quota.py index b59adbeb1e..e3477dc065 100644 --- a/loopx/quota.py +++ b/loopx/quota.py @@ -73,7 +73,6 @@ ) from .execution_profile import execution_profile_outcome_floor, outcome_floor_threshold from .presentation.renderers.quota_event_markdown import ( - render_quota_monitor_poll_markdown as _render_quota_monitor_poll_markdown, render_quota_slot_preview_markdown as render_quota_slot_preview_markdown, ) from .presentation.renderers.quota_markdown import ( @@ -1151,7 +1150,7 @@ def should_run(current_status: dict[str, object]) -> dict[str, object]: ).get("todo") effective_todo_id = normalized_observation_todo_id or (normalized_receipt_todo_id if not target_key else None) result: dict[str, object] = record_quota_monitor_poll_for_decision( - before, status_payload, goal_id=safe_goal_id, render_markdown=_render_quota_monitor_poll_markdown, + before, status_payload, goal_id=safe_goal_id, after_decision=should_run, registry_path=registry_path, execute=execute, source=source, reason_summary=reason_summary, agent_id=agent_id, settlement_todo_id=normalized_receipt_todo_id, auxiliary_settlement_todo=auxiliary_settlement_todo, todo_id=effective_todo_id, @@ -1166,6 +1165,7 @@ def should_run(current_status: dict[str, object]) -> dict[str, object]: task_lease_expected_version=task_lease_expected_version, use_current_task_lease=use_current_task_lease, turn_instance_id=turn_instance_id, status_reloader=status_reloader, goal_ref=goal_ref, recovery_effect_id=recovery_effect_id, + todo_id_explicit=normalized_requested_todo_id is not None, ) continuation = result.get("turn_continuation") if ( diff --git a/tests/control_plane/test_native_monitor_poll.py b/tests/control_plane/test_native_monitor_poll.py index d1f30f791c..ea25438183 100644 --- a/tests/control_plane/test_native_monitor_poll.py +++ b/tests/control_plane/test_native_monitor_poll.py @@ -1,16 +1,17 @@ """Actual CLI -> quota -> canonical transaction -> projection -> quota receipt.""" from __future__ import annotations -import pytest import hashlib import json +import pytest + from canonical_authority_fixture import initialize_canonical_authority, isolate_sqlite_runtime -from test_monitor_followthrough_contract import _write_fixture, GOAL_ID, AGENT_ID +from test_monitor_followthrough_contract import _add_monitor, _write_fixture, GOAL_ID, AGENT_ID from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection from loopx.control_plane.coordination.local_authority import read_canonical_todos_if_promoted from loopx.control_plane.scheduler.monitor_poll_writeback import write_monitor_poll_todo_state -from loopx.control_plane.testing.canary_harness import run_json_cli +from loopx.control_plane.testing.canary_harness import run_json_cli, run_json_cli_result def _canonical( @@ -84,6 +85,47 @@ def test_public_cli_native_monitor_settles_with_independent_successor(tmp_path, assert state.exists() +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_due_monitor_key_cannot_replace_selected_todo(tmp_path, monkeypatch, provider): + isolate_sqlite_runtime(tmp_path, monkeypatch) + registry, runtime, _state, first = _canonical(tmp_path, native=True, provider=provider) + second_key = "secondary-watch" + second = _add_monitor( + registry, text="Observe a second public target", target_key=second_key, + next_due_at="2001-01-01T00:00:00Z", + ) + route = ("--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--runtime-profile", "generic_cli") + lookup = {"registry_path": registry, "runtime_root": runtime} + guard = run_json_cli("quota", "should-run", *route, **lookup) + assert guard["work_lane_contract"]["obligation"] == "attempt_due_monitor" + targets = {first["todo_id"]: first["target_key"], second["todo_id"]: second_key} + selected_id = guard["selected_todo"]["todo_id"] + selected_key = targets.pop(selected_id) + alternate_id, alternate_key = next(iter(targets.items())) + + def snapshot(): + return read_canonical_todos_if_promoted(runtime_root=runtime, goal_id=GOAL_ID) + + before = snapshot() + poll = ("quota", "monitor-poll", *route, "--result-hash", "observed-revision", "--execute") + code, rejected = run_json_cli_result(*poll, "--target-key", alternate_key, **lookup) + assert code != 0 and not rejected["ok"], rejected + assert "monitor-poll requires" in rejected["reason"] + assert snapshot() == before + + admitted = run_json_cli( + *poll, "--todo-id", alternate_id, "--target-key", alternate_key, **lookup, + ) + assert admitted["todo_writeback"]["todo_id"] == alternate_id + after = snapshot() + assert int(after["cursor"]) == int(before["cursor"]) + 1 + prior_selected = next(row for row in before["todos"] if row["todo_id"] == selected_id) + assert next(row for row in after["todos"] if row["todo_id"] == selected_id) == prior_selected + + matching_key = run_json_cli(*poll, "--target-key", selected_key, **lookup) + assert matching_key["todo_writeback"]["todo_id"] == selected_id + + @pytest.mark.parametrize("provider", ["file", "sqlite"]) def test_native_monitor_retry_and_projection_failure_do_not_repeat_business(tmp_path, monkeypatch, provider): isolate_sqlite_runtime(tmp_path, monkeypatch) diff --git a/tests/control_plane_ts/quota_monitor_poll_commit.test.ts b/tests/control_plane_ts/quota_monitor_poll_commit.test.ts index 62e85380e7..69407b7b11 100644 --- a/tests/control_plane_ts/quota_monitor_poll_commit.test.ts +++ b/tests/control_plane_ts/quota_monitor_poll_commit.test.ts @@ -291,13 +291,14 @@ test("admission revalidates due, external, and exact blocked-wait modes", async ); }); -test("attempt_due_monitor admits secondary claimed due monitors via registry_due_monitor unless user gate applies", async () => { +test("attempt_due_monitor admits an explicit secondary due Todo unless a user gate applies", async t => { const secondaryCandidate = { todo_id: "todo_secondary_monitor", target_key: "secondary-watch", task_class: "continuous_monitor", claimed_by: "codex-main-control", due: true, + todo_id_explicit: true, }; const baseDecision = (overrides: Record = {}) => decision({ should_run: true, @@ -333,6 +334,8 @@ test("attempt_due_monitor admits secondary claimed due monitors via registry_due { requires_user_action: true }, { registry_due_monitor: { ...secondaryCandidate, due: false } }, { registry_due_monitor: { ...secondaryCandidate, claimed_by: "other-agent" } }, + { registry_due_monitor: { ...secondaryCandidate, todo_id_explicit: false } }, + { registry_due_monitor: { ...secondaryCandidate, todo_id_explicit: undefined } }, ]) { await assert.rejects( () => evaluateQuotaMonitorPollCommit(request({ @@ -350,6 +353,30 @@ test("attempt_due_monitor admits secondary claimed due monitors via registry_due }, ); } + + const runtime = await tempRuntime(t); + const effect = "previously-admitted-secondary"; + const params = request({ + phase: "preflight", runtime_root: runtime, execute: true, effect_id: effect, + decision: baseDecision(), + observation: observation({ + todo_id: "todo_secondary_monitor", + target_key: "secondary-watch", + result_hash: "unchanged-secondary", + }), + }); + const initial = await evaluateQuotaMonitorPollCommit(params); + assert.equal(initial.status, "provider_required"); + const token = createHash("sha256").update(effect).digest("hex").slice(0, 24); + const receiptPath = join(runtime, "goals", goalId, "runs", ".transactions", "quota-monitor-poll", `${token}.json`); + const historical = JSON.parse(await readFile(receiptPath, "utf8")); + delete historical.admitted_decision.registry_due_monitor.todo_id_explicit; + await writeFile(receiptPath, JSON.stringify(historical)); + const recovered = await evaluateQuotaMonitorPollCommit({ + ...params, + decision: baseDecision({registry_due_monitor: null}), + }); + assert.deepEqual(recovered.provider_plan, initial.provider_plan); }); test("Todo preflight rejects invalid admission before journaling provider intent", async (t) => {