Skip to content
Merged
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 loopx/control_plane/quota/live_decision.py
Original file line number Diff line number Diff line change
Expand Up @@ -777,7 +777,10 @@ def build_live_quota_should_run_decision(
):
from ..work_items.autonomous_replan_ack import load_receipt_replan_ack_candidates
decision_status_payload["receipt_bound_replan_ack_candidates"] = load_receipt_replan_ack_candidates(
runtime_root, goal_id=goal_id, agent_id=agent_id, obligation_id=receipt_bound_replan_obligation_id)
runtime_root, goal_id=goal_id, agent_id=agent_id,
obligation_id=receipt_bound_replan_obligation_id,
guard_recorded_at=receipt_bound_guard_fields["receipt_bound_guard_recorded_at"],
guard_turn_instance_id=receipt_bound_guard_fields["receipt_bound_guard_turn_instance_id"])
fresh_operator_inbox_read = _fresh_operator_inbox_read_required(
turn_start_hook_dispatch
)
Expand Down
193 changes: 191 additions & 2 deletions loopx/control_plane/work_items/autonomous_replan_ack.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,194 @@ def autonomous_replan_ack_candidates_for_obligation(
return candidates


def _event_details(event: dict[str, Any]) -> dict[str, Any]:
details = event.get("details")
return details if isinstance(details, dict) else {}


def _admission_event_index(
events: list[dict[str, Any]], *, goal_id: str, agent_id: str,
turn_instance_id: str, recorded_at: str,
) -> int | None:
if not turn_instance_id or not recorded_at:
return None
found: int | None = None
for index, event in enumerate(events):
if (
event.get("event_kind") == "quota_should_run"
and event.get("goal_id") == goal_id
and event.get("agent_id") == agent_id
and event.get("run_id") == turn_instance_id
and event.get("recorded_at") == recorded_at
):
found = index
return found


def _binding_text(value: Any) -> str:
return str(value or "").strip()


def _source_run(
runs: list[dict[str, Any]] | None, *, turn_instance_id: str, obligation_id: str,
) -> dict[str, Any]:
for run in runs or []:
if _binding_text(run.get("turn_instance_id")) != turn_instance_id:
continue
ack = run.get("autonomous_replan_ack")
delta = ack.get("semantic_delta") if isinstance(ack, dict) else None
if isinstance(delta, dict) and _binding_text(delta.get("obligation_id")) == obligation_id:
return run
return {}


def _expected_todo_receipt(
run: dict[str, Any], events: list[dict[str, Any]], *,
goal_id: str, agent_id: str, turn_instance_id: str,
) -> tuple[str, str]:
"""Todo settlement identity for this ACK, filled from its heartbeat receipt.

A historical index can omit the Todo and effect. The turn's existing
quota receipt still has that exact identity. An empty side is not a match.
"""

identity = run.get("settlement_identity")
identity = identity if isinstance(identity, dict) else {}
todo = _binding_text(run.get("todo_id") or identity.get("todo_id"))
effect = _binding_text(identity.get("effect_id"))
if todo and effect:
return todo, effect
for event in events:
if (
event.get("event_kind") != "quota_should_run"
or event.get("goal_id") != goal_id
or event.get("agent_id") != agent_id
or _binding_text(event.get("run_id")) != turn_instance_id
):
continue
details = _event_details(event)
todo = todo or _binding_text(event.get("todo_id") or details.get("todo_id"))
effect = effect or _binding_text(details.get("settlement_effect_id"))
return todo, effect


def _writeback_event_is_bound(
event: dict[str, Any], run: dict[str, Any], events: list[dict[str, Any]], *,
goal_id: str, agent_id: str, obligation_id: str, turn_instance_id: str,
) -> bool:
"""Require one positive identity shared with the accepted ACK.

The event obligation must equal the semantic delta, or its Todo and effect
must equal the ACK receipt. Missing fields do not count as agreement.
"""

if (
event.get("event_kind") != "refresh_state"
or event.get("goal_id") != goal_id
or event.get("agent_id") != agent_id
or _binding_text(event.get("run_id")) != turn_instance_id
):
return False
details = _event_details(event)
if details.get("autonomous_replan_recorded") is not True:
return False
event_obligation = _binding_text(details.get("replan_obligation_id"))
if event_obligation:
return event_obligation == obligation_id
event_todo = _binding_text(event.get("todo_id"))
event_effect = _binding_text(details.get("settlement_effect_id"))
if not event_todo or not event_effect:
return False
expected_todo, expected_effect = _expected_todo_receipt(
run, events, goal_id=goal_id, agent_id=agent_id, turn_instance_id=turn_instance_id)
return bool(
expected_todo and expected_effect
and event_todo == expected_todo and event_effect == expected_effect
)


def _original_writeback_event_index(
events: list[dict[str, Any]], runs: list[dict[str, Any]] | None, *,
goal_id: str, agent_id: str, obligation_id: str, turn_instance_id: str,
) -> int | None:
if not turn_instance_id or not obligation_id:
return None
run = _source_run(runs, turn_instance_id=turn_instance_id, obligation_id=obligation_id)
for index, event in enumerate(events):
if _writeback_event_is_bound(
event, run, events, goal_id=goal_id, agent_id=agent_id,
obligation_id=obligation_id, turn_instance_id=turn_instance_id,
):
return index
return None


def attach_historical_ack_writeback_order(
candidates: list[dict[str, Any]], events: list[dict[str, Any]], *,
goal_id: str, agent_id: str, obligation_id: str,
guard_recorded_at: str | None, guard_turn_instance_id: str | None,
runs: list[dict[str, Any]] | None = None,
) -> None:
"""Copy the original refresh event order onto matching ACK candidates.

The compact run clock is whole seconds. The decision owner compares this
event with admission; this reader only selects the bound original event.
"""

admission_index = _admission_event_index(
events, goal_id=goal_id, agent_id=agent_id,
turn_instance_id=str(guard_turn_instance_id or "").strip(),
recorded_at=str(guard_recorded_at or "").strip(),
)
for candidate in candidates:
turn_instance_id = _binding_text(candidate.get("turn_instance_id"))
evidence_index = _original_writeback_event_index(
events, runs, goal_id=goal_id, agent_id=agent_id, obligation_id=obligation_id,
turn_instance_id=turn_instance_id,
)
if evidence_index is None:
continue
event = events[evidence_index]
candidate["writeback_recorded_at"] = event.get("recorded_at")
candidate["writeback_goal_id"] = event.get("goal_id")
candidate["writeback_agent_id"] = event.get("agent_id")
candidate["writeback_turn_instance_id"] = event.get("run_id")
candidate["writeback_obligation_id"] = obligation_id
candidate["writeback_follows_admission"] = (
admission_index is not None and evidence_index > admission_index
)


def historical_ack_candidates_with_writeback_order(
newest_first_runs: list[dict[str, Any]] | None, *,
goal_id: str, agent_id: str, obligation_id: str | None,
guard_scoped: bool = True, runtime_root: Path | str | None = None,
source_route: Any = None,
guard_recorded_at: str | None = None, guard_turn_instance_id: str | None = None,
) -> list[dict[str, Any]]:
"""Project obligation candidates and attach their original writeback order."""
from ...rollout_event_log import load_rollout_events, rollout_event_log_path

selected = _binding_text(obligation_id) if guard_scoped else ""
candidates = autonomous_replan_ack_candidates_for_obligation(
newest_first_runs, goal_id=goal_id, agent_id=agent_id, obligation_id=selected or None)
route = source_route if isinstance(source_route, dict) else {}
root_text = runtime_root or route.get("runtime_root")
root = Path(str(root_text)) if root_text else None
if root is None or not selected:
return candidates
attach_historical_ack_writeback_order(
candidates, load_rollout_events(rollout_event_log_path(root, goal_id)),
goal_id=goal_id, agent_id=agent_id, obligation_id=selected,
guard_recorded_at=guard_recorded_at, guard_turn_instance_id=guard_turn_instance_id,
runs=newest_first_runs,
)
return candidates


def load_receipt_replan_ack_candidates(
runtime_root: Path, *, goal_id: str, agent_id: str, obligation_id: str,
guard_recorded_at: str | None = None, guard_turn_instance_id: str | None = None,
) -> list[dict[str, Any]]:
"""Read exact recovery candidates without widening ordinary status history."""
from ...history import load_index
Expand All @@ -277,8 +463,11 @@ def load_receipt_replan_ack_candidates(
runs, _ = load_index(runtime_root / "goals" / goal_id / "runs" / "index.jsonl")
newest_first = [run for _, run in sorted(enumerate(runs),
key=lambda item: (*chronology_key(item[1].get("generated_at")), item[0]), reverse=True)]
return autonomous_replan_ack_candidates_for_obligation(newest_first,
goal_id=goal_id, agent_id=agent_id, obligation_id=obligation_id)
return historical_ack_candidates_with_writeback_order(
newest_first, goal_id=goal_id, agent_id=agent_id, obligation_id=obligation_id,
runtime_root=runtime_root, guard_recorded_at=guard_recorded_at,
guard_turn_instance_id=guard_turn_instance_id,
)


def latest_blocked_successor_frontier_identity(
Expand Down
19 changes: 18 additions & 1 deletion loopx/control_plane/work_items/replan_semantics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,28 @@ function historicalAckDelta(
const ackTurn = typeof ack.turn_instance_id === "string" ? ack.turn_instance_id.trim() : "";
const generated = typeof ack.generated_at === "string"
? parseTodoTimestampMicros(ack.generated_at) : null;
// A generated_at that is already strictly later proves order on its own.
// The compact run clock is whole seconds, so a stamp inside the admission
// second can be either side of a fractional guard_recorded_at. That
// candidate needs the original refresh_state event, bound to this Goal,
// Agent, obligation, and ACK Turn, with both its recorded time and its
// log position after admission. Missing or conflicting order stays pending.
const admissionSecond = admitted / 1_000_000n * 1_000_000n;
const preciseLater = generated !== null && generated > admitted;
const sameSecond = generated !== null && generated % 1_000_000n === 0n &&
generated >= admissionSecond && !preciseLater;
const written = typeof ack.writeback_recorded_at === "string"
? parseTodoTimestampMicros(ack.writeback_recorded_at) : null;
const writebackAfterAdmission = sameSecond && written !== null && written > admitted &&
ack.writeback_follows_admission === true && ack.writeback_goal_id === goal &&
ack.writeback_agent_id === agent && ack.writeback_turn_instance_id === ackTurn &&
ack.writeback_obligation_id === selected;
const afterAdmission = preciseLater || writebackAfterAdmission;
const outcomes = strings(delta.outcomes);
const satisfying = strings(delta.satisfying_outcomes);
return ack.schema_version === "autonomous_replan_ack_v0" && ack.recorded === true &&
ack.goal_id === goal && ack.agent_id === agent && ackTurn && ackTurn !== guardTurn &&
generated !== null && generated > admitted &&
generated !== null && afterAdmission &&
delta.schema_version === "replan_semantic_delta_v0" && delta.accepted === true &&
delta.obligation_id === selected && outcomes.length > 0 && satisfying.length > 0 &&
outcomes.every(outcome => KNOWN_OUTCOMES.has(outcome)) &&
Expand Down
10 changes: 7 additions & 3 deletions loopx/control_plane/work_items/semantic_replan_writeback.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
)
from ..todos.succession_warning import todo_succession_gap_items
from .autonomous_replan_ack import (
autonomous_replan_ack_candidates_for_obligation,
historical_ack_candidates_with_writeback_order,
latest_monitor_replan_frontier_identity,
watch_lane_continuation_todo_ids,
)
Expand Down Expand Up @@ -294,9 +294,13 @@ def qualify_replan_writeback(
]
}
}
status_payload["receipt_bound_replan_ack_candidates"] = autonomous_replan_ack_candidates_for_obligation(
status_payload["receipt_bound_replan_ack_candidates"] = historical_ack_candidates_with_writeback_order(
newest_first_runs, goal_id=goal_id, agent_id=safe_agent_id,
obligation_id=guard_semantic_replan_obligation_id if guard_scoped else None)
obligation_id=guard_semantic_replan_obligation_id, guard_scoped=guard_scoped,
source_route=replan_source_route,
guard_recorded_at=receipt_bound_guard_recorded_at,
guard_turn_instance_id=receipt_bound_guard_turn_instance_id,
)
if capability_evidence is not None:
status_payload["bounded_research_frontier"] = capability_evidence.frontier
context = build_goal_frontier_projection_context_from_status(
Expand Down
76 changes: 76 additions & 0 deletions tests/control_plane/test_autonomous_replan_ack.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from loopx.control_plane.work_items.autonomous_replan_ack import (
AUTONOMOUS_REPLAN_ACK_MATERIAL_RUN_WINDOW,
AUTONOMOUS_REPLAN_ACK_RECOVERY_CANDIDATE_LIMIT,
attach_historical_ack_writeback_order,
autonomous_replan_ack_candidates_for_obligation,
compact_autonomous_replan_ack,
latest_autonomous_replan_ack_for_projection,
Expand Down Expand Up @@ -325,3 +326,78 @@ def test_long_chain_trigger_checkpoint_survives_ack_compaction() -> None:
assert compact["semantic_delta"]["trigger_checkpoints"] == [
{"kind": "long_todo_chain", "frontier_revision": frontier_revision}
]


def test_same_second_candidate_keeps_the_todo_bound_writeback_order() -> None:
turn = "guided-start:later"
run = {
"goal_id": GOAL_ID, "agent_id": AGENT_ID, "turn_instance_id": turn,
"todo_id": "todo-original",
"settlement_identity": {"todo_id": "todo-original", "effect_id": "effect-later"},
"autonomous_replan_ack": {"semantic_delta": {"obligation_id": LONG_CHAIN_OBLIGATION_ID}},
}
admission = {"event_kind": "quota_should_run", "goal_id": GOAL_ID, "agent_id": AGENT_ID,
"run_id": "guided-start:original", "recorded_at": "2026-08-01T00:00:01.500000Z"}
# A Todo-bound refresh leaves the obligation field empty. The semantic
# delta and the Todo receipt identify the writeback.
todo_event = {"event_kind": "refresh_state", "goal_id": GOAL_ID, "agent_id": AGENT_ID,
"run_id": turn, "todo_id": "todo-original", "recorded_at": "2026-08-01T00:00:01.900000Z",
"details": {"autonomous_replan_recorded": True, "replan_obligation_id": None,
"settlement_effect_id": "effect-later"}}
other_obligation = {"event_kind": "refresh_state", "goal_id": GOAL_ID, "agent_id": AGENT_ID,
"run_id": turn, "recorded_at": "2026-08-01T00:00:01.100000Z", "details": {
"autonomous_replan_recorded": True, "replan_obligation_id": "replan-ffffffffffffffff"}}
candidate = {"turn_instance_id": turn, "generated_at": "2026-08-01T00:00:01Z"}
attach_historical_ack_writeback_order(
[candidate], [other_obligation, admission, todo_event], goal_id=GOAL_ID, agent_id=AGENT_ID,
obligation_id=LONG_CHAIN_OBLIGATION_ID,
guard_recorded_at=admission["recorded_at"], guard_turn_instance_id="guided-start:original",
runs=[run],
)
assert candidate["writeback_recorded_at"] == "2026-08-01T00:00:01.900000Z"
assert candidate["writeback_follows_admission"] is True
assert candidate["writeback_obligation_id"] == LONG_CHAIN_OBLIGATION_ID
mismatched = {"turn_instance_id": turn}
mismatched_event = {**todo_event, "details": {**todo_event["details"], "settlement_effect_id": "effect-other"}}
attach_historical_ack_writeback_order(
[mismatched], [admission, mismatched_event], goal_id=GOAL_ID, agent_id=AGENT_ID,
obligation_id=LONG_CHAIN_OBLIGATION_ID,
guard_recorded_at=admission["recorded_at"], guard_turn_instance_id="guided-start:original",
runs=[run],
)
assert "writeback_recorded_at" not in mismatched
sparse_run = {
"goal_id": GOAL_ID, "agent_id": AGENT_ID, "turn_instance_id": turn,
"autonomous_replan_ack": {"semantic_delta": {"obligation_id": LONG_CHAIN_OBLIGATION_ID}},
}
later_receipt = {"event_kind": "quota_should_run", "goal_id": GOAL_ID, "agent_id": AGENT_ID,
"run_id": turn, "todo_id": "todo-original", "recorded_at": "2026-08-01T00:00:01.200000Z",
"details": {"settlement_effect_id": "effect-later", "todo_id": "todo-original"}}
filled = {"turn_instance_id": turn}
attach_historical_ack_writeback_order(
[filled], [admission, later_receipt, todo_event], goal_id=GOAL_ID, agent_id=AGENT_ID,
obligation_id=LONG_CHAIN_OBLIGATION_ID,
guard_recorded_at=admission["recorded_at"], guard_turn_instance_id="guided-start:original",
runs=[sparse_run],
)
assert filled["writeback_recorded_at"] == todo_event["recorded_at"]
foreign = {"turn_instance_id": turn}
foreign_event = {**todo_event, "todo_id": "todo-other",
"details": {**todo_event["details"], "settlement_effect_id": "effect-other"}}
attach_historical_ack_writeback_order(
[foreign], [admission, later_receipt, foreign_event], goal_id=GOAL_ID, agent_id=AGENT_ID,
obligation_id=LONG_CHAIN_OBLIGATION_ID,
guard_recorded_at=admission["recorded_at"], guard_turn_instance_id="guided-start:original",
runs=[sparse_run],
)
assert "writeback_recorded_at" not in foreign
blank = {"turn_instance_id": turn}
blank_event = {**todo_event, "todo_id": "", "details": {
"autonomous_replan_recorded": True, "replan_obligation_id": None, "settlement_effect_id": None}}
attach_historical_ack_writeback_order(
[blank], [admission, later_receipt, blank_event], goal_id=GOAL_ID, agent_id=AGENT_ID,
obligation_id=LONG_CHAIN_OBLIGATION_ID,
guard_recorded_at=admission["recorded_at"], guard_turn_instance_id="guided-start:original",
runs=[sparse_run],
)
assert "writeback_recorded_at" not in blank
Loading
Loading