Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/quota-allocation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <GOAL_ID> \
Expand Down
54 changes: 39 additions & 15 deletions examples/control_plane/monitor-poll-writeback-smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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"]
Expand Down
16 changes: 8 additions & 8 deletions loopx/control_plane/quota/monitor_poll.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}

Expand Down Expand Up @@ -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)
Expand All @@ -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 = {}
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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"] = {
Expand Down Expand Up @@ -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(
Expand Down
11 changes: 8 additions & 3 deletions loopx/control_plane/quota/monitor_poll_admission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,19 @@ 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));
const registry = decision.registry_due_monitor;
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;
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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",
Expand Down
4 changes: 2 additions & 2 deletions loopx/quota.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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,
Expand All @@ -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 (
Expand Down
48 changes: 45 additions & 3 deletions tests/control_plane/test_native_monitor_poll.py
Original file line number Diff line number Diff line change
@@ -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(
Expand Down Expand Up @@ -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)
Expand Down
29 changes: 28 additions & 1 deletion tests/control_plane_ts/quota_monitor_poll_commit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> = {}) => decision({
should_run: true,
Expand Down Expand Up @@ -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({
Expand All @@ -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) => {
Expand Down
Loading